How to add a combine a code from a Python file to the other?

Hello, I am building a game in Python. It’s already finished only must add the timer in it. The code of the game is in one file and the timer is in another file.
But I must add the timer so when you run the game the timer will appear in the game. But I’m struggling about how to add the timer then.
Does anyone have an idea of maybe clue, or solution for this?

You can use an import statement to access code in different files.
You should learn more about imports in python, it is very important for organizing code.

So in your game file, you could put:

import timer

and then access all global variables in timer.py with the timer name.

timer.do_timer_stuff()
timer.MyTimer()

When you import a file, all of its code is run. If you don’t want this to happen, put the code inside functions so that it is not run when the file is imported. Then, you can call the functions when you want to.

3 Likes

@NuclearPasta0 Thank you for the reply. And does it matter where i put the import timer in te game code that you just said in the message here before.

By convention, it is best to put any import statements at the top of your game code so that it is accessible everywhere in the file and it is easy to see the imports.

im working on it. I tried making classes now in the Timer file, but i did get an error. I will send first the code and then the screenshot of the error.

import pygame



pygame.init()

window = pygame.display.set_mode((500,500))

running = True
secs = 300

font = pygame.font.Font(None,32)
text = font.render(f"{secs}" ,True,  (112, 173, 71), (0, 0, 0))
textRect = text.get_rect()
textRect.center = 500 - text.get_width(), text.get_height()

clock = pygame.time.Clock()

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    window.fill((0, 0, 0))
    window.blit(text, textRect)
    pygame.display.update()

class Timer:
    def_init_(self, duration)
    pygame.init()
    pass

   def update(self):
    pygame.display.update()
    pass

    def get_time(self):
        running = True
        secs = 300

    if secs > 0:
        secs -=1
        text = font.render(f"{secs}", True, (112, 173, 71 ))

        clock.tick(1)

and this is the screenshot of the error that i got

Make sure your indentation is correct. A single indentation level should have 4 spaces in your project.
Inside functions, there is an extra level of indentation.

In addition to this, there are many other problems. You should avoid calling pygame.init() or pygame.display.update() inside of your Timer class.

Therefore, your code should look more like this.

import pygame

pygame.init()

window = pygame.display.set_mode((500, 500))

font = pygame.font.Font(None, 32)

clock = pygame.time.Clock()
running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    window.fill((0, 0, 0))


class Timer:
    def __init__(self, duration=300):
        self.duration = duration  # the current duration of the timer, in seconds

    def update(self):
        self.render_time()

    def render_time(self):
        """Renders the timer text onto the window."""
        if self.duration > 0:
            self.duration -= 1
        text = font.render(f"{self.duration}", True, (112, 173, 71))
        textRect = text.get_rect()
        textRect.center = 500 - text.get_width(), text.get_height()
        window.blit(text, textRect)

Now you can easily use your Timer class. To use it, create an instance and assign it to a variable, for example:

timer = Timer()

Then call timer.update() inside of the game loop.

If you already have a separate file with a game and you are importing this timer file, you need to get rid of the game loop that is inside of this timer file because you cannot have two game loops at the same time.

3 Likes

Thanks for the reply. And do I have to add something in the file or code from the game you think?

In the game file, you just have to import the timer file, and then use the timer.Timer class where you want to in the game file’s game loop.

So you mean like i only have to put the import timer in the code of the game above?

You have to put:

import timer

near the top of the game file. This will import the timer file named timer.py (if it is named something else then you have the change the timer in the import statement to something else).
Then, you have to use the Timer class somewhere in your game file,
so inside of your game file, you should create a Timer with something like

game_timer = timer.Timer()

You can then call the game_timer.update() method inside of your game loop inside of your game file.
Make sure that your game loop does one loop every second so that your timer is correct.
If you want your game loop to run many times every second, then there are a few changes you need to do for the Timer class.

Thanks for the reply. So the file where the timer in is, is called def time_limit and the file where the game in is is called main.py.
So I have to put then import def time_limit and put in the main file where i have the game in it, should i put it then down after from desert import as you see here below?
Here you can see the main.py file of the game.

There is one problem. Your timer file is called def time_limit.py but this is not good because it has a space in the name.
Rename your timer file to time_limit.py. Then you can put this in main.py where your game is:

import time_limit

A better way is to import the Timer class directly so that you can use it in main file like Timer() instead of time_limit.Timer(). So, instead of the import statement above, you could put this instead:

from time_limit import Timer

It does not matter where you put this line, as long as it is near the top of the file. For example, you could put this import statement after the from desert import * line.

Then, you will have to use the Timer somewhere in your main game file code. You can do this by creating a Timer instance. For example:

timer = Timer()

Then do timer.update() inside of your game loop.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.