在我的游戏中,我可以在屏幕上的任何地方放置大炮。我希望我的大炮能够发射子弹,子弹应该在移动100像素后重置。下面是我的cannon课程,我还是OOP新手,所以我需要一些帮助,但我也无法使用列表完成这项任务。谢谢你的帮助
class Cannon():
global cannon_list
global bullet_list
def __init__(self, x, y, track, old_x):
self.x = x
self.y = y
self.track = track
self.old_x = old_x
def spawnBullet(self):
for j in bullet_list:
self.old_x = self.x
self.track = j[2]
screen.blit(bullet, (j[0], j[1]))
def moveBullet(self):
if self.x <= self.track:
self.x += 3
def resetBullet(self):
if self.x >= self.track:
self.x = self.old_x
def spawnCannon(self):
for i in cannon_list:
screen.blit(cannon, i)
使用cannon类。这是在重画游戏窗口下
for j in bullet_list:
cannonsAndBullets = Cannon(j[0], j[1], j[2], j[0])
cannonsAndBullets.spawnCannon()
cannonsAndBullets.spawnBullet()
cannonsAndBullets.moveBullet()
cannonsAndBullets.resetBullet()
下面是我在bullet_list
和cannon_list
中添加的内容。x和y是我球员的位置
cannon_list.append([x,y])
bullet_list.append([x,(y+25),100, x])
我班上的编辑
class Cannon():
global cannon_list
global bullet_list
def __init__(self, x, y, track, old_x):
self.x = x
self.y = y
self.track = track
self.old_x = old_x
def spawnBullet(self):
# for j in bullet_list:
# self.x, self.y, self.track, self.old_x = j
screen.blit(bullet, (self.x, self.y))
def moveBullet(self):
# for j in bullet_list:
# self.x, self.y, self.track, self.old_x = j
if self.track <= 100:
print(self.track)
self.track += 3
self.x += 3
def resetBullet(self):
# for j in bullet_list:
# self.x, self.y, self.track, self.old_x = j
if self.track >= 100:
print(self.track)
self.x = self.old_x
def spawnCannon(self):
for i in cannon_list:
screen.blit(cannon, i)
让我们放弃一切,从头开始,利用pygame的功能,如精灵和向量数学
我们从pygame游戏的基本框架开始,一个简单的窗口:
现在,我们想放一些雪碧。让我们创建一个表示大炮的
Sprite
类,并用鼠标放置它们:现在我们想让大炮发射子弹。为此,我们利用了一些面向对象的特性,比如多态性。子弹和大炮是不同的类型,但它们提供相同的接口:
update
和draw
。就这样。请注意,我们的主循环不需要知道精灵的确切类型我们还确保子弹的所有逻辑都在
Bullet
类中,而大炮的所有逻辑都在Cannon
类中:使用一个向量并简单地将每个帧的移动距离相加,就可以很容易地检查每个
Bullet
是否已经移动了100个像素。如果为true,只需调用kill
即可将其删除相关问题 更多 >
编程相关推荐