用python写出一个贪吃蛇游戏
时间: 2023-07-18 13:43:29 浏览: 75
好的,下面是一个简单的贪吃蛇游戏的Python代码:
```python
import pygame
import random
# 初始化
pygame.init()
# 设置游戏界面大小、背景颜色和标题
screen_width = 480
screen_height = 480
bg_color = (255, 255, 255)
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇")
# 定义颜色变量
red_color = (255, 0, 0)
green_color = (0, 255, 0)
black_color = (0, 0, 0)
# 定义蛇的初始位置和大小
snake_width = 20
snake_height = 20
snake_x = screen_width / 2 - snake_width / 2
snake_y = screen_height / 2 - snake_height / 2
snake_list = [[snake_x, snake_y], [snake_x - snake_width, snake_y], [snake_x - 2 * snake_width, snake_y]]
# 定义食物的初始位置和大小
food_width = 20
food_height = 20
food_x = random.randint(0, screen_width - food_width)
food_y = random.randint(0, screen_height - food_height)
# 定义蛇移动的初始方向
direction = "right"
# 定义字体
font = pygame.font.SysFont(None, 30)
# 定义游戏结束的函数
def game_over():
text = font.render("Game Over", True, red_color)
screen.blit(text, (screen_width / 2 - text.get_width() / 2, screen_height / 2 - text.get_height() / 2))
pygame.display.update()
pygame.time.delay(3000)
pygame.quit()
exit()
# 游戏循环
while True:
# 设置游戏帧率
pygame.time.Clock().tick(10)
# 处理游戏退出事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 处理键盘事件
keys = pygame.key.get_pressed()
if keys[pygame.K_UP] and direction != "down":
direction = "up"
elif keys[pygame.K_DOWN] and direction != "up":
direction = "down"
elif keys[pygame.K_LEFT] and direction != "right":
direction = "left"
elif keys[pygame.K_RIGHT] and direction != "left":
direction = "right"
# 移动蛇的位置
if direction == "up":
snake_y -= snake_height
elif direction == "down":
snake_y += snake_height
elif direction == "left":
snake_x -= snake_width
elif direction == "right":
snake_x += snake_width
# 判断是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = random.randint(0, screen_width - food_width)
food_y = random.randint(0, screen_height - food_height)
snake_list.insert(0, [snake_x, snake_y])
# 判断游戏是否结束
if snake_x < 0 or snake_x > screen_width - snake_width or snake_y < 0 or snake_y > screen_height - snake_height:
game_over()
for i in range(1, len(snake_list)):
if snake_x == snake_list[i][0] and snake_y == snake_list[i][1]:
game_over()
# 在屏幕上绘制蛇和食物
screen.fill(bg_color)
for i in range(len(snake_list)):
pygame.draw.rect(screen, green_color, [snake_list[i][0], snake_list[i][1], snake_width, snake_height])
pygame.draw.rect(screen, red_color, [food_x, food_y, food_width, food_height])
# 更新蛇的位置
snake_list.insert(0, [snake_x, snake_y])
snake_list.pop()
# 刷新屏幕
pygame.display.update()
```
这是一个比较简单的贪吃蛇游戏,如果需要完善可以添加更多的功能,比如计分、暂停、重新开始等等。
阅读全文