在PyCharm上,我的左键和右键都没有反应。

问题描述 投票:1回答:1
#enable pygame mode
import pygame
pygame.init()

#create screen
screen = pygame.display.set_mode((900,600))

#Title + Logo
pygame.display.set_caption("Space Invader")
icon = pygame.image.load("chicken.png")
pygame.display.set_icon(icon)

#Player icon
player_icon = pygame.image.load("spaceship.png")
playerX = 400
playerY = 500

def player(x, y):
    screen.blit(player_icon, (x, y))

#game loop
running = True
while running:

    # backround colour  RGB
    screen.fill((0, 0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            #If key pressed check wether its right or left
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    print("key left pressed")
                if event.key == pygame.K_RIGHT:
                    print("key right pressed")
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    print("key stroke has benn released")


    #Player change in coordinates
    playerX += 0
    playerY += 0

    player(playerX, playerY)
    pygame.display.update()

在这次隔离期间,我一直在学习pygame和使用python进行游戏编程。我是通过看youtube上的教程来学习的。请不要给我降级,我已经很努力的把我的问题做的更好了,上次是我的第一个问题,被降级了2次。谢谢你的时间。

python windows pygame pycharm
1个回答
0
投票

这是个问题 缩进. 在你的代码中 pygame.KEYDOWN 事件只在以下情况下才会被评估 event.type == pygame.QUIT. "移动 "的 pygame.KEYDOWN 事件处理。

running = True
while running:

    # backround colour  RGB
    screen.fill((0, 0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # <--| INDENTATION

        #If key pressed check wether its right or left
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                print("key left pressed")
            if event.key == pygame.K_RIGHT:
                print("key right pressed")
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                print("key stroke has benn released")
© www.soinside.com 2019 - 2024. All rights reserved.