我正在尝试重新创建那些旧的2D太空射击游戏之一,并且已经完成了大部分工作,但是我仍然停留在射击的实际部分。
我还会使用pythagaros定理来计算子弹与敌人之间的碰撞以及敌人与玩家之间的碰撞吗?
代码如下:
import pygame, random, os
pygame.init()
w, h = 1366, 768
screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
pygame.display.set_caption('SPACESHIPSHOOTER')
clock = pygame.time.Clock()
class player:
def __init__(self, pos=[w//2, h//7]):
self.pos = pos
self.player = pygame.image.load(os.path.join('GameData', 'player.png'))
self.player = pygame.transform.scale(self.player, (100, 83))
class enemy:
def __init__(self, pos=[random.randint(0, 1366), 700]):
self.pos = pos
self.enemy = pygame.image.load(os.path.join('GameData', 'enemy.png'))
self.enemy = pygame.transform.scale(self.enemy, (100, 83))
class bullet:
def __init__(self, pos):
self.pos = pos
self.bullet = pygame.image.load(os.path.join('GameData', 'missile.png'))
self.bullet = pygame.transform.scale(self.bullet, (50, 41))
self.exist = 0
def update(self):
if self.pos[1] < 700 and self.exist == 1:
self.pos[1] -= 5
you = player()
enemies = [enemy()]
bullets = []
running = True
speed = 1.2
clock = 0
xv = 0
while running:
screen.fill((0, 0, 0))
clock += 1
for event in pygame.event.get():
if event.type == pygame.QUIT: running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
if event.key == pygame.K_d:
xv = 8
if event.key == pygame.K_a:
xv = -8
if event.key == pygame.K_SPACE:
bullets.append(bullet([you.pos[0], you.pos[1]]))
if event.type == pygame.KEYUP:
if event.key == pygame.K_d or event.key == pygame.K_a:
xv = 0
you.pos[0] += xv
if len(bullets) > 0:
for bullet in bullets:
bullet.exist=1
bullet.update()
for badguy in enemies:
if badguy.pos[1] <= 5:
del enemies[enemies.index(badguy)]
enemies.append(enemy([random.randint(0, 1366), 700]))
badguy.pos[1] = badguy.pos[1] - speed
screen.blit(badguy.enemy, (badguy.pos[0], badguy.pos[1]))
if clock % 750 == 0:
speed += 0.05
if clock % 1200 == 0:
enemies.append(enemy([random.randint(0, 1366), 700]))
screen.blit(you.player, (you.pos[0], you.pos[1]))
pygame.display.flip()
pygame.quit()
quit()
那是游戏的代码,我不断得到的错误是:
Traceback (most recent call last):
File "D:/spaceshipgame/game.py", line 53, in <module>
bullets.append(bullet([you.pos[0], you.pos[1]]))
TypeError: 'bullet' object is not callable
预先感谢
答案 0 :(得分:3)
for bullet in bullets:
定义了一个同名变量bullet
,它将覆盖类对象。重命名类或变量。
按惯例,大写字母CamelCase
用于类名,lowercase_underscored
用于变量。
答案 1 :(得分:1)
问题在于线路
for bullet in bullets:
,其中您使用变量bullet
覆盖了类bullet
。这就是存在使用大写字母Bullet
编写类的约定的原因。