如何在 pygame 中使用键盘输入?
How do I use keyboard inputs in pygame?
所以我正在制作一个游戏,其中这个角色(一个圆圈)必须戳破从天而降的气球才能获得分数。但是我一开始就无法让我的角色移动。
代码:
import pygame
from pygame.locals import *
pygame.init()
#Variables
white = (255, 255, 255)
blue = (70,130,180)
black = (0,0,0)
x = 400
y = 450
#screen stuff
screenwidth = 800
screenheight = 600
screen = pygame.display.set_mode((screenwidth, screenheight))
pygame.display.set_caption("Balloon Game!")
#end of screen stuff
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
# Draw Character
character = pygame.draw.circle(screen, (blue), (x, y), 50, 50)
#End of Drawing Character
# Making Arrow Keys
keyPressed = pygame.key.get_pressed()
if keyPressed[pygame.K_LEFT]:
character.x -= 1
if keyPressed[pygame.K_RIGHT]:
character.x += 1
pygame.display.update()
如果有人能告诉我为什么不是,我将不胜感激
使用固定代码。谢谢!
pygame.draw.circle
returns 圆的边界矩形(pygame.Rect
对象)。然而,圆心总是 (x
, y
)。因此,您需要更改 x
而不是 character.x
:
while True:
# [...]
pygame.draw.circle(screen, (blue), (x, y), 50, 50)
keyPressed = pygame.key.get_pressed()
if keyPressed[pygame.K_LEFT]:
x -= 1
if keyPressed[pygame.K_RIGHT]:
x += 1
这段代码甚至可以简化:
while True:
# [...]
pygame.draw.circle(screen, (blue), (x, y), 50, 50)
keyPressed = pygame.key.get_pressed()
x += (keyPressed[pygame.K_RIGHT] - keyPressed[pygame.K_LEFT])
所以我正在制作一个游戏,其中这个角色(一个圆圈)必须戳破从天而降的气球才能获得分数。但是我一开始就无法让我的角色移动。
代码:
import pygame
from pygame.locals import *
pygame.init()
#Variables
white = (255, 255, 255)
blue = (70,130,180)
black = (0,0,0)
x = 400
y = 450
#screen stuff
screenwidth = 800
screenheight = 600
screen = pygame.display.set_mode((screenwidth, screenheight))
pygame.display.set_caption("Balloon Game!")
#end of screen stuff
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
# Draw Character
character = pygame.draw.circle(screen, (blue), (x, y), 50, 50)
#End of Drawing Character
# Making Arrow Keys
keyPressed = pygame.key.get_pressed()
if keyPressed[pygame.K_LEFT]:
character.x -= 1
if keyPressed[pygame.K_RIGHT]:
character.x += 1
pygame.display.update()
如果有人能告诉我为什么不是,我将不胜感激 使用固定代码。谢谢!
pygame.draw.circle
returns 圆的边界矩形(pygame.Rect
对象)。然而,圆心总是 (x
, y
)。因此,您需要更改 x
而不是 character.x
:
while True:
# [...]
pygame.draw.circle(screen, (blue), (x, y), 50, 50)
keyPressed = pygame.key.get_pressed()
if keyPressed[pygame.K_LEFT]:
x -= 1
if keyPressed[pygame.K_RIGHT]:
x += 1
这段代码甚至可以简化:
while True:
# [...]
pygame.draw.circle(screen, (blue), (x, y), 50, 50)
keyPressed = pygame.key.get_pressed()
x += (keyPressed[pygame.K_RIGHT] - keyPressed[pygame.K_LEFT])