我正在制作类似于atari游戏的游戏;杆位。我试图找出每次有人越过起跑线时如何让随机车出现。我在调用多辆随机汽车时遇到问题。我没有收到任何错误消息。以下是我的代码。 (如果你有关于如何让赛车专门出现在赛道上的任何建议,这也会有所帮助)我是编程的初学者,我仍在努力解决这个问题。感谢您的任何建议。
import random
import time
class Game:
def __init__(self):
self.tk = Tk()
self.tk.title("Car Game")
self.tk.resizable(0, 0)
self.tk.wm_attributes("-topmost", 1)
self.canvas = Canvas(self.tk, width=1280, height=750, bd=0, highlightthickness=0)
self.canvas.pack()
self.tk.update()
self.bg = PhotoImage(file="road.gif")
self.canvas.create_image(0, 0, image=self.bg, anchor='nw')
def your_car_sprite(self):
self.yourCar = PhotoImage(file="carForgame.gif")
self.canvas.create_image(850,570,image=self.yourCar, anchor='nw')
def random_cars_sprite(self):
x = random.randint(0,1280)
y = random.randint(0,750)
self.randomCar = PhotoImage(file='Car2.gif')
self.canvas.create_image(x, y, image=self.randomCar, anchor='nw')
for i in range(1,5):
self.canvas.create_image(x, y, image=self.randomCar, anchor='nw')
def mainloop(self):
while 1:
self.tk.update_idletasks()
self.tk.update()
time.sleep(0.01)
g = Game()
g.your_car_sprite()
rCars = g.random_cars_sprite()
main = mainloop()
答案 0 :(得分:0)
我看到为什么你的随机车不会出现的两个原因:
PhotoImage
时,必须保留对每个不同图片的引用(请参阅this answer和the documentation)以下是解决问题的方法:
def random_cars_sprite(self):
self.randomCars = []
for i in range(1,5):
x = random.randint(0,1280)
y = random.randint(0,750)
randomCar = PhotoImage(file=os.path.join(folder, "purple.png"))
self.canvas.create_image(x, y, image=randomCar, anchor='nw')
self.randomCars.append(randomCar)