我正在做一本书中的pygame程序,里面有一个厨师扔比萨饼,你必须用平底锅把它们抓起来。厨师和潘雪碧只创造了一次,而披萨雪碧显然一直在创造。我试着让分数越高时,厨师的动作就越快(只在x轴上移动)。我想我在类属性和实例属性方面遇到了麻烦。我一直找不到从chef类访问score的方法,尽管我尝试将score设置为一个全局变量,甚至只将其分配给一个虚拟的全局变量(这将允许我在update方法中更改chefs的速度)。或者,我尝试在pan类中访问chefs dx,因为这是分数所在。我也无法访问它,即使使用getattr方法。如有任何建议,不胜感激。这是pan和chef类的代码。我已经把我试过但没用的东西的一部分注释掉了。在
from livewires import games, color
import random
games.init(screen_width = 640, screen_height = 480, fps = 50)
class Pan(games.Sprite):
"""
A pan controlled by player to catch falling pizzas.
"""
image = games.load_image("pan.bmp")
def __init__(self):
""" Initialize Pan object and create Text object for score. """
super(Pan, self).__init__(image = Pan.image,
x = games.mouse.x,
bottom = games.screen.height)
self.score = games.Text(value = 0, size = 25, color = color.black,
top = 5, right = games.screen.width - 10)
games.screen.add(self.score)
def update(self):
""" Move to mouse x position. """
self.x = games.mouse.x
if self.left < 0:
self.left = 0
if self.right > games.screen.width:
self.right = games.screen.width
self.check_catch()
def check_catch(self):
""" Check if catch pizzas. """
for pizza in self.overlapping_sprites:
self.score.value += 10
#increase the speed of the pizza
# if self.score.value % 100 == 0:
# Pizza.speed += 0.1
# print(Pizza.speed)
#increase the speed of the chef
# if self.score.value % 100 == 0:
# print(Chef.dx)
# print(x)
# y = int(x)*2
# print(y)
self.score.right = games.screen.width - 10
pizza.handle_caught()
class Chef(games.Sprite):
"""
A chef which moves left and right, dropping pizzas.
"""
image = games.load_image("chef.bmp")
speed = 2
def __init__(self, y = 55, odds_change = 200):
""" Initialize the Chef object. """
super(Chef, self).__init__(image = Chef.image,
x = games.screen.width / 2,
y = y,
dx = Chef.speed)
self.odds_change = odds_change
self.time_til_drop = 0
def update(self):
#x = getattr(Pan,"score")
#print(x)
""" Determine if direction needs to be reversed. """
if self.left < 0 or self.right > games.screen.width:
self.dx = -self.dx
elif random.randrange(self.odds_change) == 0:
self.dx = -self.dx
self.check_drop()
def check_drop(self):
""" Decrease countdown or drop pizza and reset countdown. """
if self.time_til_drop > 0:
self.time_til_drop -= 1
else:
new_pizza = Pizza(x = self.x)
games.screen.add(new_pizza)
# set buffer to approx 30% of pizza height, regardless of pizza speed
self.time_til_drop = int(new_pizza.height * 1.3 / Pizza.speed) + 1
def main():
""" Play the game. """
wall_image = games.load_image("wall.jpg", transparent = False)
games.screen.background = wall_image
the_chef = Chef()
games.screen.add(the_chef)
the_pan = Pan()
games.screen.add(the_pan)
games.mouse.is_visible = False
games.screen.event_grab = True
games.screen.mainloop()
# start it up!
main()
由于chef speed是一个类变量,因此需要添加类名才能访问它,如:
Chef.speed
。披萨课在哪里?我不知道Livewire,所以不能解释为什么你不能访问这个分数,但是你肯定可以把它设置成一个数字,然后用这种方式使用它?在谢谢你的时间。我可以通过在Pan类中创建一个属性标志来检查分数,然后在Chef的update方法中访问该属性标志,从而能够更改dx。主厨速度只是初始厨师速度,因此更改它不会更新厨师的dx。在
相关问题 更多 >
编程相关推荐