0

Let's say I have a hypothetical program or game with class Car and I want to create a new car object any time players e.g click mouse. In folowing example we create newCarNrI; I want be able to create : newCarNr1, newCarNr2, newCarNr3, newCarNr4, newCarNr5 on every click.

import pygame

class Car:
   def __init__(self,name):
      self.name = name

def main():

   #pygame initialisation and logic and stuff ...

   #game Loop
   while True:
      click = pygame.mouse.get_pressed()
      if click[0] == 1:
         # Create new Car object when click
          newCarNrI = Car(aCarName)

if __name__ = '__mian__':
   main()

Is it possible? How to do it?

Taku
  • 31,927
  • 11
  • 74
  • 85
Onebus
  • 1
  • 2
  • 2
  • 1
    why not have a list of `Car` and just append to it? – Nullman May 21 '17 at 16:19
  • Don't, use a list or dictionary. See http://stackoverflow.com/q/1373164/3001761. Also note that `'__mian__' != '__main__'`. – jonrsharpe May 21 '17 at 16:20
  • I guess something else you might be able to try is to directly add the Car onto the pygame board and have functions in the Car handle its behavior in the game (like if it is clicked). – Daniel Li May 21 '17 at 16:21

1 Answers1

2

You should not create that many names in the locals() scope, try using a dict and save it as key and values.

import pygame

class Car:
   def __init__(self,name):
      self.name = name

def main():

   #pygame initialisation and logic and stuff ...

   #game Loop
   counter = 0
   cardict = {}
   while True:
      click = pygame.mouse.get_pressed()
      if click[0] == 1:
         counter += 1
         # Create new Car object when click
         cardict['newCarNr%i' % counter] = Car("aCarName")
    # access cardict["newCarNr7"] Car instance later

if __name__ = '__main__':
   main()

But I don't even believe you need to have an unique key for every Car instance, you should instead make a list and access the Car instance you wanted by indexing.

import pygame

class Car:
   def __init__(self,name):
      self.name = name

def main():

   #pygame initialisation and logic and stuff ...

   #game Loop

   carlist = []
   while True:
      click = pygame.mouse.get_pressed()
      if click[0] == 1:
         # Create new Car object when click
         carlist.append(Car("aCarName"))
    # access carlist[7] Car instance later

if __name__ = '__main__':
   main()
Taku
  • 31,927
  • 11
  • 74
  • 85