python跳一跳游戏代码
时间: 2024-02-03 18:10:18 浏览: 115
当然可以!以下是一个简单的Python跳一跳游戏代码示例:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置窗口大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("跳一跳")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 定义小人和方块的大小
player_size = 50
block_size = 50
# 定义小人的初始位置和速度
player_x = screen_width // 2 - player_size // 2
player_y = screen_height - player_size
player_speed = 5
# 定义方块的初始位置和速度
block_x = random.randint(0, screen_width - block_size)
block_y = -block_size
block_speed = 3
# 游戏主循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 获取键盘输入
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_x -= player_speed
if keys[pygame.K_RIGHT]:
player_x += player_speed
# 更新方块位置
block_y += block_speed
# 判断是否碰撞
if player_x < block_x + block_size and player_x + player_size > block_x and player_y < block_y + block_size and player_y + player_size > block_y:
# 碰撞后重新设置方块位置
block_x = random.randint(0, screen_width - block_size)
block_y = -block_size
# 绘制背景
screen.fill(BLACK)
# 绘制小人
pygame.draw.rect(screen, WHITE, (player_x, player_y, player_size, player_size))
# 绘制方块
pygame.draw.rect(screen, WHITE, (block_x, block_y, block_size, block_size))
# 更新屏幕
pygame.display.flip()
# 退出游戏
pygame.quit()
```
这是一个简单的跳一跳游戏代码示例,使用了pygame库来实现游戏窗口和绘制图形。在游戏中,你可以通过左右箭头键控制小人的移动,小人需要躲避从上方下落的方块。当小人与方块发生碰撞时,方块会重新出现在随机位置。
阅读全文