【发布时间】:2021-09-23 18:10:10
【问题描述】:
我是一名年轻的 Python 程序员。我决定使用 pygame 创建一个 2D 游戏 游戏目的:在汽车上尽可能远地行驶,而不会撞到在游戏中“生成”的物体。汽车将驶过田野。
我的装饰精灵有问题(在游戏过程中,树木会“倒”在窗户边缘) Fig1.pic1
所以,树应该在之前的树到达窗口中间之后立即生成,但是当新树生成时,这就是我的情况:图 2。然后游戏开始卡死pic2
这是我的代码:
from superwires import games, color
from random import randrange
games.init(screen_width = 530, screen_height = 600, fps = 60)
#Car sprite
class Car(games.Sprite):
image = games.load_image("C:/python/car.bmp")
def __init__(self):
super(Car, self).__init__(image = Car.image,
x = games.mouse.x,
bottom = games.screen.height - 10)
self.score = games.Text(value = 0, size = 25, color = color.yellow,
top = 5, right = games.screen.width/2)
games.screen.add(self.score)
def update(self):
self.x = games.mouse.x
if self.left < 65:
self.left = 65
if self.right > games.screen.width - 65:
self.right = games.screen.width - 65
#Tree sprite
class Bush1(games.Sprite):
image = games.load_image("C:/python/bush.bmp")
speed = 1
def __init__(self, x = 20, y = 100):
super(Bush1, self).__init__(image = Bush1.image,
x = x, y = y,
dy = Bush1.speed)
def update(self):
if self.bottom > games.screen.height/2:
newbush = Bush1()
newbush.__init__(x = 20, y = -100)
games.screen.add(newbush)
class Bush2(games.Sprite):
image = games.load_image("C:/python/bush.bmp")
speed = 1
def __init__(self, x = 515, y = 100):
super(Bush2, self).__init__(image = Bush2.image,
x = x, y = y,
dy = Bush2.speed)
#Spawning new trees
def update(self):
if self.bottom > games.screen.height/2:
newbush = Bush2()
newbush.__init__(x = 515, y = -100)
games.screen.add(newbush)
#Start
def main():
road = games.load_image("road.jpg", transparent = False)
games.screen.background = road
bush1 = Bush1()
bush2 = Bush2()
car = Car()
games.screen.add(bush1)
games.screen.add(bush2)
games.screen.add(car)
games.mouse.is_visible = False
games.screen.event_grab = True
games.screen.mainloop()
main()
我很高兴知道我在哪里犯了错误。
使用过:Python 3.9、superwires、游戏
【问题讨论】:
-
您是否在其他地方输出了任何错误?此外,看起来
Bush1和Bush2是同一个类,并且您在update方法中以一种奇怪的方式使用__init__。__init__在你实例化一个新对象时被调用——直接调用它可能会导致意想不到的结果。同样,由于这些类依赖于在全局范围内的games,因此您可能会遇到引用问题 - 缺少它们或覆盖它们。 -
@NathanielFord 我没有收到任何错误,只是 pic2 中的内容
-
我看不出这两张图片有什么区别。
-
创建一个新对象会自动调用
__init__。你应该做newbush = Bush2(x=515, y=-100)。而且,由于这些是默认值,因此您根本不需要指定它们。 -
@TimRoberts 请再次检查照片