pygame小游戏代码
时间: 2023-07-09 18:49:58 浏览: 150
下面是一个简单的pygame小游戏代码,可以让你了解pygame的基本用法:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
screen_width = 600
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏标题
pygame.display.set_caption("小游戏")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
# 定义游戏角色
player_size = 50
player_pos = [screen_width/2, screen_height-2*player_size]
# 定义敌人角色
enemy_size = 50
enemy_pos = [random.randint(0, screen_width-enemy_size), 0]
enemy_list = [enemy_pos]
# 定义移动速度
speed = 10
# 定义分数
score = 0
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义游戏结束函数
def game_over():
text = font.render("游戏结束,得分为:" + str(score), True, black)
screen.blit(text, [screen_width/2, screen_height/2])
pygame.display.update()
pygame.time.delay(2000)
pygame.quit()
quit()
# 定义游戏循环
while True:
# 监听事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
x = player_pos[0]
y = player_pos[1]
if event.key == pygame.K_LEFT:
x -= player_size
elif event.key == pygame.K_RIGHT:
x += player_size
player_pos = [x, y]
# 清屏幕
screen.fill(white)
# 更新敌人位置
for idx, enemy_pos in enumerate(enemy_list):
if enemy_pos[1] >= 0 and enemy_pos[1] < screen_height:
enemy_pos[1] += speed
else:
enemy_list.pop(idx)
score += 1
# 检测碰撞
if (enemy_pos[1] + enemy_size) > player_pos[1]:
if (enemy_pos[0] >= player_pos[0]) and (enemy_pos[0] < (player_pos[0] + player_size)) or \
(player_pos[0] >= enemy_pos[0]) and (player_pos[0] < (enemy_pos[0] + enemy_size)):
game_over()
# 更新敌人列表
if random.randint(0, 10) == 0:
enemy_list.append([random.randint(0, screen_width-enemy_size), 0])
# 绘制游戏角色
pygame.draw.rect(screen, black, (player_pos[0], player_pos[1], player_size, player_size))
# 绘制敌人角色
for enemy_pos in enemy_list:
pygame.draw.rect(screen, black, (enemy_pos[0], enemy_pos[1], enemy_size, enemy_size))
# 显示分数
text = font.render("得分:" + str(score), True, black)
screen.blit(text, [0, 0])
# 刷新屏幕
pygame.display.update()
```
这个小游戏是一个简单的飞机躲避游戏,玩家需要控制方块躲避从上方掉落的方块,每躲避一个方块就会得到一分。如果玩家和方块相撞,游戏就会结束。
阅读全文