我现在正在尝试制作一款迷你游戏,让用户躲避所有落下的比萨饼。然而,在比萨饼触摸图形屏幕的底部后,用户的分数会无限增加,我不知道为什么会这样。请帮我解决这个问题。
from livewires import games, color
import random
games.init(screen_width = 640, screen_height = 480, fps = 50)
class Pizza(games.Sprite):
image = games.load_image("pizza.bmp")
speed = 2
pizza_count = 0
def __init__(self, x, top):
super(Pizza, self).__init__(image = Pizza.image, x = x,
top = top, dy = Pizza.speed)
def update(self):
if self.bottom > games.screen.height:
Pizza.pizza_count += 1
self.destroy()
if self.left < 0:
self.left = 0
if self.right > games.screen.width:
self.right = games.screen.width
def end_game(self):
end_message = games.Message(value = "Game Over!",
size = 80,
x = games.screen.width/2,
y = games.screen.height/2,
color = color.red,
after_death = games.screen.quit,
lifetime = 5 * games.screen.fps)
games.screen.add(end_message)
class Runner(games.Sprite):
image = games.load_image("chef.bmp")
score = games.Text(value = 0, size = 50, color = color.black,
top = 50, right = games.screen.width - 10)
def __init__(self, x = games.screen.width/2, bottom = games.screen.height):
super(Runner, self).__init__(image = Runner.image,
x = x, bottom = bottom)
games.screen.add(Runner.score)
self.pizza_x = random.randrange(games.screen.width)
pizza = Pizza(x = self.pizza_x, top = 0)
games.screen.add(pizza)
def update(self):
if games.keyboard.is_pressed(games.K_LEFT):
self.x -= 3
if games.keyboard.is_pressed(games.K_RIGHT):
self.x += 3
if self.right > games.screen.width:
self.right = games.screen.width
if self.left < 0:
self.left = 0
for pizza in self.overlapping_sprites:
pizza.destroy()
pizza.end_game()
Runner.score.value += Pizza.pizza_count * 10
Runner.score.right = games.screen.width - 10
games.screen.add(Runner.score)
def main():
background_image = games.load_image("wall.jpg", transparent = False)
games.screen.background = background_image
runner = Runner()
games.screen.add(runner)
games.screen.mainloop()
main()
答案 0 :(得分:1)
只要没有对它的引用,垃圾收集器就会删除实例,所以仍然必须引用它...这里;
pizza = Pizza(x = self.pizza_x, top = 0) # pizza is still referring to it!
games.screen.add(pizza)
尝试放置&#39; pizza = None&#39;在&#39; games.screen.add(披萨)&#39;线。 如果一切顺利,self.destroy()函数应该删除最后一个引用并具有预期的效果。
使用一个标志来指示已经进行评分也是一个好主意,以防万一垃圾收集器的速度不足以移除实例..
def __init__(self, x, top):
super(Pizza, self).__init__(image = Pizza.image, x = x,
top = top, dy = Pizza.speed)
self.scoreFlag = False
def update(self):
if self.bottom > games.screen.height:
if self.scoreFlag == False:
Pizza.pizza_count += 1
self.scoreFlag = True
self.destroy()
self.destroy()