我正在从一本书中做一个pygame程序,其中一位厨师放下比萨饼,你必须用平底锅捕捉它们。厨师和平底锅精灵只创造一次,而披萨精灵显然不断创造。我试图让它变得更高,厨师开始更快地移动(仅在x中移动)。我认为我遇到了类属性与实例属性的问题。我一直无法找到从厨师班获得分数的方法,即使我尝试将分数作为全局变量,或者甚至只是将其分配给虚拟全局变量(这将允许我更改厨师的速度)更新方法)。或者,我尝试访问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()
答案 0 :(得分:0)
由于厨师速度是一个类变量,您需要添加类名来访问它,如:Chef.speed
。披萨类在哪里?我不知道Livewire所以无法解释为什么你无法访问乐谱,但你肯定可以用某种方式将它设置为数字并以这种方式使用它?
答案 1 :(得分:0)
感谢您的时间。我能够通过在Pan类中创建属性标志来检查分数,然后在Chef的更新方法中访问该属性标志来解决它,然后能够更改dx。 Chef.speed只是最初的厨师速度,因此更改它不会更新厨师的dx。