python语言写一个贪吃蛇游戏
时间: 2024-05-05 21:19:41 浏览: 58
Python编写一个贪吃蛇游戏
好的,以下是一个简单的贪吃蛇游戏的 Python 代码:
```python
import pygame
import random
# 初始化 pygame
pygame.init()
# 游戏窗口大小
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 设置游戏时钟
clock = pygame.time.Clock()
# 贪吃蛇方块大小
BLOCK_SIZE = 10
# 字体对象
font = pygame.font.SysFont(None, 25)
# 绘制文字的函数
def draw_text(text, color, x, y):
text_obj = font.render(text, True, color)
window.blit(text_obj, (x, y))
# 绘制贪吃蛇的函数
def draw_snake(snake_list):
for snake in snake_list:
pygame.draw.rect(window, GREEN, [snake[0], snake[1], BLOCK_SIZE, BLOCK_SIZE])
# 游戏主循环
def game_loop():
# 初始化贪吃蛇位置
snake_x = 250
snake_y = 250
# 初始化贪吃蛇移动方向
snake_x_change = 0
snake_y_change = 0
# 初始化食物位置
food_x = round(random.randrange(0, WINDOW_WIDTH - BLOCK_SIZE) / 10.0) * 10.0
food_y = round(random.randrange(0, WINDOW_HEIGHT - BLOCK_SIZE) / 10.0) * 10.0
# 初始化贪吃蛇长度列表
snake_list = []
snake_length = 1
# 游戏结束标志
game_over = False
while not game_over:
# 处理事件
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:
snake_x_change = -BLOCK_SIZE
snake_y_change = 0
elif event.key == pygame.K_RIGHT:
snake_x_change = BLOCK_SIZE
snake_y_change = 0
elif event.key == pygame.K_UP:
snake_y_change = -BLOCK_SIZE
snake_x_change = 0
elif event.key == pygame.K_DOWN:
snake_y_change = BLOCK_SIZE
snake_x_change = 0
# 移动贪吃蛇
snake_x += snake_x_change
snake_y += snake_y_change
# 判断贪吃蛇是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, WINDOW_WIDTH - BLOCK_SIZE) / 10.0) * 10.0
food_y = round(random.randrange(0, WINDOW_HEIGHT - BLOCK_SIZE) / 10.0) * 10.0
snake_length += 1
# 判断贪吃蛇是否撞墙或撞到自己
if snake_x >= WINDOW_WIDTH or snake_x < 0 or snake_y >= WINDOW_HEIGHT or snake_y < 0:
game_over = True
head = []
head.append(snake_x)
head.append(snake_y)
snake_list.append(head)
if len(snake_list) > snake_length:
del snake_list[0]
for segment in snake_list[:-1]:
if segment == head:
game_over = True
# 绘制游戏窗口
window.fill(WHITE)
draw_text("贪吃蛇长度: " + str(snake_length - 1), BLACK, 10, 10)
pygame.draw.rect(window, RED, [food_x, food_y, BLOCK_SIZE, BLOCK_SIZE])
draw_snake(snake_list)
pygame.display.update()
# 设置游戏帧率
clock.tick(20)
# 退出 pygame
pygame.quit()
# 运行游戏
game_loop()
```
这个游戏使用了 Pygame 库,需要先安装 Pygame 库才能运行。游戏规则是控制贪吃蛇吃到食物,贪吃蛇长度每吃到一次食物就加1,遇到墙壁或者自己的身体就会游戏结束。
阅读全文