写一个python的小游戏贪吃蛇代码
时间: 2024-05-16 15:14:01 浏览: 54
一个简单的贪吃蛇游戏的完整 Python 代码
好的,以下是一个简单的贪吃蛇游戏的Python代码:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置游戏窗口
window_width = 640
window_height = 480
game_window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("贪吃蛇游戏")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义蛇的初始位置和方向
snake_x = window_width / 2
snake_y = window_height / 2
snake_direction = "right"
# 定义蛇身列表和初始长度
snake_list = [(snake_x, snake_y)]
snake_length = 1
# 定义食物位置
food_x = round(random.randrange(0, window_width - 10) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - 10) / 10.0) * 10.0
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义游戏结束函数
def game_over():
message = font.render("Game Over! Press Q-Quit or C-Play Again", True, white)
message_rect = message.get_rect()
message_rect.center = (window_width / 2, window_height / 2)
game_window.blit(message, message_rect)
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit()
quit()
elif event.key == pygame.K_c:
game_loop()
# 定义游戏循环函数
def game_loop():
global snake_direction, snake_x, snake_y, snake_list, snake_length, food_x, food_y
game_exit = False
while not game_exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and snake_direction != "right":
snake_direction = "left"
elif event.key == pygame.K_RIGHT and snake_direction != "left":
snake_direction = "right"
elif event.key == pygame.K_UP and snake_direction != "down":
snake_direction = "up"
elif event.key == pygame.K_DOWN and snake_direction != "up":
snake_direction = "down"
# 移动蛇头
if snake_direction == "right":
snake_x += 10
elif snake_direction == "left":
snake_x -= 10
elif snake_direction == "up":
snake_y -= 10
elif snake_direction == "down":
snake_y += 10
# 检查蛇是否吃到了食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, window_width - 10) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - 10) / 10.0) * 10.0
snake_length += 1
# 更新蛇身列表
snake_head = (snake_x, snake_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# 检查蛇是否撞到了自己
for body in snake_list[:-1]:
if body == snake_head:
game_over()
# 检查蛇是否撞到了边界
if snake_x < 0 or snake_x >= window_width or snake_y < 0 or snake_y >= window_height:
game_over()
# 绘制游戏界面
game_window.fill(black)
pygame.draw.rect(game_window, red, [food_x, food_y, 10, 10])
for body in snake_list:
pygame.draw.rect(game_window, white, [body[0], body[1], 10, 10])
pygame.display.update()
# 控制游戏的帧率
clock.tick(15)
# 开始游戏
game_loop()
# 退出Pygame
pygame.quit()
quit()
```
运行以上代码,即可开始玩贪吃蛇游戏。按左、右、上、下箭头控制蛇的移动方向,吃到食物后蛇的长度会增加,撞到边界或撞到自己则游戏结束。
阅读全文