游戏源代码中只用到pygame的小游戏源代码
时间: 2024-01-29 17:18:40 浏览: 29
好的,以下是一个简单的使用pygame编写的“贪吃蛇”小游戏的源代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
# 设置贪吃蛇和食物的大小
BLOCK_SIZE = 10
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义一个函数,用于在屏幕上显示文字
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
window.blit(screen_text, [WINDOW_WIDTH/6, WINDOW_HEIGHT/2])
# 定义一个函数,用于绘制贪吃蛇
def draw_snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(window, BLACK, [x[0], x[1], snake_block_size, snake_block_size])
# 定义游戏循环
def game_loop():
game_over = False
game_close = False
# 初始位置
x1 = WINDOW_WIDTH / 2
y1 = WINDOW_HEIGHT / 2
# 初始速度
x1_change = 0
y1_change = 0
# 初始长度
snake_List = []
Length_of_snake = 1
# 随机生成食物位置
foodx = round(random.randrange(0, WINDOW_WIDTH - BLOCK_SIZE) / 10.0) * 10.0
foody = round(random.randrange(0, WINDOW_HEIGHT - BLOCK_SIZE) / 10.0) * 10.0
while not game_over:
while game_close == True:
window.fill(WHITE)
message_to_screen("游戏结束,按Q退出,按C重新开始", RED)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -BLOCK_SIZE
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = BLOCK_SIZE
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -BLOCK_SIZE
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = BLOCK_SIZE
x1_change = 0
# 判断贪吃蛇是否撞到边界
if x1 >= WINDOW_WIDTH or x1 < 0 or y1 >= WINDOW_HEIGHT or y1 < 0:
game_close = True
# 更新蛇头坐标
x1 += x1_change
y1 += y1_change
# 绘制游戏界面
window.fill(WHITE)
pygame.draw.rect(window, RED, [foodx, foody, BLOCK_SIZE, BLOCK_SIZE])
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
if len(snake_List) > Length_of_snake:
del snake_List[0]
for x in snake_List[:-1]:
if x == snake_Head:
game_close = True
draw_snake(BLOCK_SIZE, snake_List)
pygame.display.update()
# 判断贪吃蛇是否吃到食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, WINDOW_WIDTH - BLOCK_SIZE) / 10.0) * 10.0
foody = round(random.randrange(0, WINDOW_HEIGHT - BLOCK_SIZE) / 10.0) * 10.0
Length_of_snake += 1
# 刷新游戏界面
pygame.display.update()
# 退出pygame
pygame.quit()
# 开始游戏循环
game_loop()
```
这是一个比较简单的贪吃蛇游戏,其中使用了pygame库来实现游戏界面的绘制和事件的处理。希望能对你有所帮助!