请一段可以在python运行的贪吃蛇游戏代码
时间: 2024-04-30 16:23:32 浏览: 230
很抱歉,作为AI语言模型,我没有能力编写完整的代码。但是,以下是一个简单的贪吃蛇游戏代码框架,希望对您有所帮助:
```
import pygame
import random
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 初始化Pygame
pygame.init()
# 设置屏幕大小和标题
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇游戏")
# 定义方向常量
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.size = 3 # 蛇的初始长度
self.pos = [(screen_width / 2, screen_height / 2)] * self.size # 蛇的初始位置
self.direction = RIGHT # 蛇的初始方向
def move(self):
# 根据方向移动蛇头
if self.direction == UP:
new_head = (self.pos[0][0], self.pos[0][1] - 10)
elif self.direction == DOWN:
new_head = (self.pos[0][0], self.pos[0][1] + 10)
elif self.direction == LEFT:
new_head = (self.pos[0][0] - 10, self.pos[0][1])
elif self.direction == RIGHT:
new_head = (self.pos[0][0] + 10, self.pos[0][1])
self.pos.insert(0, new_head)
# 如果蛇头和食物的位置重合,增加蛇的长度
if self.pos[0] == food.pos:
food.create()
self.size += 1
# 如果蛇的长度大于3,删除蛇尾
if len(self.pos) > self.size:
self.pos.pop()
def change_direction(self, direction):
# 改变蛇的方向,但不能掉头
if direction == UP and self.direction != DOWN:
self.direction = UP
elif direction == DOWN and self.direction != UP:
self.direction = DOWN
elif direction == LEFT and self.direction != RIGHT:
self.direction = LEFT
elif direction == RIGHT and self.direction != LEFT:
self.direction = RIGHT
def draw(self):
# 绘制蛇的身体
for i, p in enumerate(self.pos):
if i == 0:
pygame.draw.rect(screen, GREEN, (p[0], p[1], 10, 10))
else:
pygame.draw.rect(screen, BLUE, (p[0], p[1], 10, 10))
# 定义食物类
class Food:
def __init__(self):
self.pos = (0, 0)
self.create()
def create(self):
# 随机生成食物的位置
x = random.randint(0, screen_width - 10)
y = random.randint(0, screen_height - 10)
self.pos = (x // 10 * 10, y // 10 * 10)
def draw(self):
# 绘制食物
pygame.draw.rect(screen, RED, (self.pos[0], self.pos[1], 10, 10))
# 初始化贪吃蛇和食物
snake = Snake()
food = Food()
# 游戏主循环
running = True
clock = pygame.time.Clock()
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake.change_direction(UP)
elif event.key == pygame.K_DOWN:
snake.change_direction(DOWN)
elif event.key == pygame.K_LEFT:
snake.change_direction(LEFT)
elif event.key == pygame.K_RIGHT:
snake.change_direction(RIGHT)
# 更新贪吃蛇和食物
snake.move()
# 绘制背景和对象
screen.fill(BLACK)
snake.draw()
food.draw()
# 刷新屏幕
pygame.display.flip()
# 控制游戏帧率
clock.tick(10)
# 退出Pygame
pygame.quit()
```
以上是一个简单的贪吃蛇游戏代码框架,您可以根据自己的需求进行修改和扩展。
阅读全文