我正在尝试用pygame编写“太空侵略者”游戏,但无法让玩家正确移动。但是,向左移动会很好。
我对Sprite和Player类的代码是:
class Sprite(pygame.sprite.Sprite):
def __init__(self, x, y, image = None):
pygame.sprite.Sprite.__init__(self)
if image is None:
self.image = pygame.Surface((25, 25))
self.image.fill((0, 255, 0))
else:
self.image = image
self.rect = self.image.get_rect()
self.rect.x, self.rect.y = x, y
self.speed = 0.5
def moveLeft(self):
self.rect.x -= self.speed
def moveRight(self):
self.rect.x += self.speed
def draw(self):
screen.blit(self.image, (self.rect.x, self.rect.y))
class Player(Sprite):
def __init__(self, startpos):
try:
image = pygame.image.load(PLAYER_SPRITE_LOCATION)
except: image = None
Sprite.__init__(self, startpos[0], startpos[1], image)
print("Player class initialized at %a with sprite %s" % (self.rect, self.image))
self.score = 0
其余的代码是:
RESOLUTION = (224, 256)
PLAYERPOS = [112, 220]
pygame.init()
screen = pygame.display.set_mode(RESOLUTION)
player = Player(PLAYERPOS)
end = False
fps = 60
clock = pygame.time.Clock()
printString = ""
PRINTFPS, time = pygame.USEREVENT+1, 1000
pygame.time.set_timer(PRINTFPS, time)
curr_fps = 0
invaders = pygame.sprite.Group()
bullets = pygame.sprite.Group()
fullscreen = False
while not end:
for event in pygame.event.get():
if event.type == pygame.QUIT:
end = True
if event.type == PRINTFPS:
curr_fps = clock.get_fps()
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT] or pressed[pygame.K_a]:
player.moveLeft()
if pressed[pygame.K_RIGHT] or pressed[pygame.K_d]:
player.moveRight()
if pressed[pygame.K_SPACE] or pressed[pygame.K_s] or pressed[pygame.K_UP]:
player.score += 1
if pressed[pygame.K_F11]:
if not fullscreen:
screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
fullscreen = True
else:
screen = pygame.display.set_mode(RESOLUTION)
fullscreen = False
# Print game data
prevPrintString = printString
printString = "\rPlayer: (%s, %s)" % (str("%.3f" % player.rect.x).zfill(7),
str("%.3f" % player.rect.y).zfill(7))
printString += "; Score: %i" % player.score
printString += "; FPS: %s" % (str("%.2f" % curr_fps).zfill(5))
if printString != prevPrintString:
print(printString, end = "")
# Background (not really needed)
screen.fill((0, 0, 255)) # Blue screen!
# Update sprites, e.g. invaders moving and bullets flying
invaders.update()
bullets.update()
# Drawing sprites
invaders.draw(screen)
bullets.draw(screen)
player.draw()
# Update screen and maintain constant FPS
clock.tick(fps)
pygame.display.flip()
问题不是输入不起作用:我可以确定它确实起作用。我认为问题出在moveRight
函数本身上,以某种方式它可能无法与加法一起使用?但是我不知道。
谢谢你!
答案 0 :(得分:0)
pygame Rect中存储的所有字段都是整数,但是您要添加或减去分数(0.5)。我最好的猜测是,当您从x坐标减去0.5时,它从(例如)112变为111.5,并被截断为111,因此您向左移动了一个像素。但是,如果添加0.5,则它从112变为112.5,并被截断为112,因此您完全不会移动。我建议只使用整数。