键盘控制方块下落的代码
时间: 2024-03-12 09:49:41 浏览: 50
以下是一个示例代码,可以通过键盘控制方块下落:
```python
import pygame
# 初始化 Pygame
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 设置屏幕大小
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 500
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# 设置标题
pygame.display.set_caption("方块下落")
# 定义方块大小和速度
BLOCK_SIZE = 20
BLOCK_SPEED = 5
# 定义方块初始位置和速度
block_x = SCREEN_WIDTH / 2 - BLOCK_SIZE / 2
block_y = 0
block_speed_x = 0
block_speed_y = BLOCK_SPEED
# 游戏循环
done = False
clock = pygame.time.Clock()
while not done:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
block_speed_x = -BLOCK_SPEED
elif event.key == pygame.K_RIGHT:
block_speed_x = BLOCK_SPEED
# 移动方块
block_x += block_speed_x
block_y += block_speed_y
# 检测方块是否超出边界
if block_x < 0:
block_x = 0
elif block_x + BLOCK_SIZE > SCREEN_WIDTH:
block_x = SCREEN_WIDTH - BLOCK_SIZE
# 绘制屏幕
screen.fill(WHITE)
pygame.draw.rect(screen, BLUE, [block_x, block_y, BLOCK_SIZE, BLOCK_SIZE])
pygame.display.flip()
# 控制帧率
clock.tick(60)
# 退出 Pygame
pygame.quit()
```
这个示例代码使用 Pygame 库来创建一个窗口,并在窗口中绘制一个蓝色的方块。通过监听键盘事件来控制方块的左右移动,每次循环更新方块的位置并重新绘制屏幕。
阅读全文