python的pygame 写一个小游戏
时间: 2023-07-25 07:26:30 浏览: 114
好的,以下是一个简单的小游戏示例:
```python
import pygame
import random
# 初始化
pygame.init()
# 设置屏幕大小和标题
screen_width = 480
screen_height = 640
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("小游戏")
# 加载背景图片
background = pygame.image.load("background.png").convert()
# 加载角色图片
character = pygame.image.load("character.png").convert_alpha()
character_width, character_height = character.get_rect().size
character_x = screen_width / 2 - character_width / 2
character_y = screen_height - character_height
# 加载敌人图片
enemy = pygame.image.load("enemy.png").convert_alpha()
enemy_width, enemy_height = enemy.get_rect().size
enemy_x = random.randrange(0, screen_width - enemy_width)
enemy_y = 0
enemy_speed = 10
# 设置字体
game_font = pygame.font.Font(None, 40)
# 初始化分数
score = 0
# 游戏主循环
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]:
character_x -= 5
if keys[pygame.K_RIGHT]:
character_x += 5
# 移动敌人
enemy_y += enemy_speed
if enemy_y > screen_height:
enemy_x = random.randrange(0, screen_width - enemy_width)
enemy_y = 0
score += 1
enemy_speed += 1
# 碰撞检测
character_rect = character.get_rect()
character_rect.left = character_x
character_rect.top = character_y
enemy_rect = enemy.get_rect()
enemy_rect.left = enemy_x
enemy_rect.top = enemy_y
if character_rect.colliderect(enemy_rect):
running = False
# 绘制背景、角色、敌人、分数
screen.blit(background, (0, 0))
screen.blit(character, (character_x, character_y))
screen.blit(enemy, (enemy_x, enemy_y))
score_text = game_font.render(f"Score: {score}", True, (255, 255, 255))
screen.blit(score_text, (10, 10))
# 刷新屏幕
pygame.display.update()
# 结束游戏
pygame.quit()
```
该示例中,我们使用了pygame库来创建了一个简单的小游戏,包括角色、敌人、背景、分数等元素,实现了角色移动、敌人下落、碰撞检测等功能。你可以根据自己的需要修改图片、调整参数,来创建自己的小游戏。
阅读全文