Rect 在 Pygame 内没有移动
Rect not moving in Pygame
我正在尝试在 pygame 中制作乒乓球游戏。所以我需要制作一个由玩家控制的矩形。我为此定义了一些变量。
变量
player = pygame.Rect(s_width - 10, s_height/2 - 35, 5, 70)
player_speed = 0
循环中
player.y += player_speed
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if pygame.key == pygame.K_DOWN:
player_speed += 5
if pygame.key == pygame.K_UP:
player_speed -= 5
if event.type == pygame.KEYUP:
if pygame.key == pygame.K_DOWN:
player_speed = 0
if pygame.key == pygame.K_UP:
player_speed = 0
你的代码只有一个问题;你不检查
if pygame.key == pygame.K_...
您需要将 pygame.key
替换为 event.key
:
if event.key == pygame.K_...
import pygame
pygame.init()
s_width, s_height = 600, 600
wn = pygame.display.set_mode((s_width, s_height))
player = pygame.Rect(s_width - 10, s_height/2 - 35, 5, 70)
player_speed = 0
clock = pygame.time.Clock()
while True:
clock.tick(60)
player.y += player_speed
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
player_speed += 5
print(player_speed)
if event.key == pygame.K_UP:
player_speed -= 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN:
player_speed = 0
if event.key == pygame.K_UP:
player_speed = 0
wn.fill((0, 0, 0))
pygame.draw.rect(wn, (255, 0, 0), player)
pygame.display.update()
输出:
我正在尝试在 pygame 中制作乒乓球游戏。所以我需要制作一个由玩家控制的矩形。我为此定义了一些变量。
变量
player = pygame.Rect(s_width - 10, s_height/2 - 35, 5, 70)
player_speed = 0
循环中
player.y += player_speed
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if pygame.key == pygame.K_DOWN:
player_speed += 5
if pygame.key == pygame.K_UP:
player_speed -= 5
if event.type == pygame.KEYUP:
if pygame.key == pygame.K_DOWN:
player_speed = 0
if pygame.key == pygame.K_UP:
player_speed = 0
你的代码只有一个问题;你不检查
if pygame.key == pygame.K_...
您需要将 pygame.key
替换为 event.key
:
if event.key == pygame.K_...
import pygame
pygame.init()
s_width, s_height = 600, 600
wn = pygame.display.set_mode((s_width, s_height))
player = pygame.Rect(s_width - 10, s_height/2 - 35, 5, 70)
player_speed = 0
clock = pygame.time.Clock()
while True:
clock.tick(60)
player.y += player_speed
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
player_speed += 5
print(player_speed)
if event.key == pygame.K_UP:
player_speed -= 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN:
player_speed = 0
if event.key == pygame.K_UP:
player_speed = 0
wn.fill((0, 0, 0))
pygame.draw.rect(wn, (255, 0, 0), player)
pygame.display.update()
输出: