Pygame模块实现功能超赞的贪吃蛇
时间: 2024-02-12 08:03:34 浏览: 99
Pygame模块可以用来实现很多有趣的游戏,其中包括经典的贪吃蛇游戏。通过使用Pygame模块的绘图功能,可以实现一个具有视觉效果的贪吃蛇游戏。
下面是一个简单的贪吃蛇游戏的实现:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 定义游戏窗口大小
win_width = 800
win_height = 600
# 创建游戏窗口
win = pygame.display.set_mode((win_width, win_height))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义蛇的属性
snake_block = 10
snake_speed = 15
# 定义字体
font_style = pygame.font.SysFont(None, 50)
# 定义函数,用于显示文字
def message(msg, color):
message = font_style.render(msg, True, color)
win.blit(message, [win_width / 6, win_height / 3])
# 定义函数,用于绘制蛇
def draw_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(win, green, [x[0], x[1], snake_block, snake_block])
# 定义游戏循环
def game_loop():
game_over = False
game_close = False
# 定义蛇的初始位置
x1 = win_width / 2
y1 = win_height / 2
# 定义蛇的移动方向
x1_change = 0
y1_change = 0
# 定义蛇的初始长度
snake_List = []
Length_of_snake = 1
# 定义食物的初始位置
foodx = round(random.randrange(0, win_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, win_height - snake_block) / 10.0) * 10.0
# 游戏循环
while not game_over:
while game_close == True:
win.fill(white)
message("你输了,按 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 = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
# 判断蛇是否超出边界
if x1 >= win_width or x1 < 0 or y1 >= win_height or y1 < 0:
game_close = True
# 更新蛇的位置
x1 += x1_change
y1 += y1_change
# 绘制游戏背景
win.fill(white)
# 绘制食物
pygame.draw.rect(win, red, [foodx, foody, snake_block, snake_block])
# 更新蛇的长度
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(snake_block, snake_List)
# 更新游戏窗口
pygame.display.update()
# 判断蛇是否吃到食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, win_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, win_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
# 设置游戏速度
clock.tick(snake_speed)
# 退出游戏
pygame.quit()
quit()
# 启动游戏循环
game_loop()
```
这个程序可以实现一个基本的贪吃蛇游戏,玩家可以使用方向键控制蛇的移动方向,吃到食物后蛇的长度会增加。当蛇碰到边界或自己时,游戏结束。
阅读全文