帮我写一个python的贪吃蛇代码
时间: 2024-05-03 08:21:44 浏览: 174
100行python代码完成的贪吃蛇游戏,简单方便快捷,下载即可运行,可做毕业设计
抱歉,作为AI语言模型,我无法编写实时代码。以下是一个简单的Python贪吃蛇游戏的基本框架,您可以根据自己的需求进行修改和完善:
```
import pygame
import random
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义每个方格的大小
block_size = 10
# 初始化pygame
pygame.init()
# 设置游戏窗口的大小
screen_width = 500
screen_height = 500
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇")
# 设置时钟
clock = pygame.time.Clock()
# 定义贪吃蛇的初始位置和长度
snake_pos = [[200, 200], [210, 200], [220, 200]]
snake_length = 3
# 定义贪吃蛇的移动方向
direction = "right"
# 生成食物的位置
food_pos = [random.randrange(1, screen_width // block_size) * block_size,
random.randrange(1, screen_height // block_size) * block_size]
# 定义游戏结束的标志
game_over = False
# 定义函数,绘制贪吃蛇和食物
def draw_snake(snake_pos):
for pos in snake_pos:
pygame.draw.rect(screen, GREEN, [pos[0], pos[1], block_size, block_size])
def draw_food(food_pos):
pygame.draw.rect(screen, RED, [food_pos[0], food_pos[1], block_size, block_size])
# 游戏循环
while not game_over:
# 监听事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and direction != "right":
direction = "left"
elif event.key == pygame.K_RIGHT and direction != "left":
direction = "right"
elif event.key == pygame.K_UP and direction != "down":
direction = "up"
elif event.key == pygame.K_DOWN and direction != "up":
direction = "down"
# 移动贪吃蛇
if direction == "right":
snake_head = [snake_pos[0][0] + block_size, snake_pos[0][1]]
elif direction == "left":
snake_head = [snake_pos[0][0] - block_size, snake_pos[0][1]]
elif direction == "up":
snake_head = [snake_pos[0][0], snake_pos[0][1] - block_size]
elif direction == "down":
snake_head = [snake_pos[0][0], snake_pos[0][1] + block_size]
snake_pos.insert(0, snake_head)
# 判断贪吃蛇是否吃到食物
if snake_pos[0] == food_pos:
food_pos = [random.randrange(1, screen_width // block_size) * block_size,
random.randrange(1, screen_height // block_size) * block_size]
snake_length += 1
else:
snake_pos.pop()
# 判断贪吃蛇是否撞到边界或自身
if snake_pos[0][0] < 0 or snake_pos[0][0] >= screen_width or snake_pos[0][1] < 0 or snake_pos[0][1] >= screen_height:
game_over = True
for pos in snake_pos[1:]:
if snake_pos[0] == pos:
game_over = True
# 绘制游戏界面
screen.fill(BLACK)
draw_snake(snake_pos)
draw_food(food_pos)
pygame.display.update()
# 控制游戏帧率
clock.tick(10)
# 退出游戏
pygame.quit()
```
阅读全文