Python Forum

Full Version: Generating number of objects for a game
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello!

I've started working on my game in Python, using tkinter (so not any pygame or other gaming libraries). I have already made some steps in my plan, what to create and what should the overall game logic look like, but I stuck on one point. I cannot understand, or I cannot imagine, how to create a generator of number of some, let's say enemies, or cars. What I want to do is to create some road and let a huge number of cars spawning and moving there, each car using the same logic given for cars generally. Please, can you give me any hint, how could I create such a generator of objects, using one and the same logic each? I know I should use some classes and parentship, but that's all I can imagine now.

I will appreciate any help. Thank you!
You create instances of your class:

class Car(object):
    # class code goes here.

car1 = Car()
car2 = Car()
...
Or better yet, cars = [Car() for car in range(num_cars)].
Here's a generator of objects
print([object for i in range(10)])
Output:
[<class 'object'>, <class 'object'>, <class 'object'>, <class 'object'>, <class 'object'>, <class 'object'>, <class 'object'>, <class 'object'>, <class 'object'>, <class 'object'>]
Thank you guys, this idea helped me a lot!

I'd like to know one other thing now, related to mouse events. This is a part of my code:

class ClassName:

    def __init__(self):
        self.canvas.bind("<ButtonPress>", self.click)
        ...

    ... # other methods

    def click(self, event):
        x, y = event.x, event.y
        if x > 150:
            self.canvas.bind('<Motion>', self.choose_car)
            move_car_cursor = True
    
        if move_car_cursor:
            move_car_cursor = False
            self.canvas.bind('<ButtonPress>', self.place_car)

    def choose_car(self, event):
        x, y = event.x, event.y
        try:
            self.canvas.delete(self.car_to_put)
        except AttributeError:
            pass
        self.car_to_put = self.canvas.create_image(x, y, image=self.car1_image)

    def place_car(self, event):
        ... # not implemented yet
So, as you can see, what I want to do is to choose a car (from some menu) and then put this car somewhere in canvas (on a road). But I have somehow lost in how bind functions work. After selecting a car from menu, it's picture should appear behind the cursor (while moving with cursor) - that works, but then, after second click somewhere on canvas, this image should be removed and displayed a new one - static on canvas (this is not completely implemented yet). I'm afraid, that the way how did I create these mouse event functions is not, in order to do this, correct. Can you help me?

Thanks.

EDIT: It's me kom2, I somehow lost my account password, but found it again. :D