帮我用python写个 贪吃蛇游戏
时间: 2024-02-28 10:27:08 浏览: 91
好的,以下是一个简单的贪吃蛇游戏的Python代码。这个游戏使用了Pygame模块。
```
import pygame
import random
# 初始化游戏
pygame.init()
# 定义窗口尺寸和标题
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置字体
font = pygame.font.Font(None, 36)
# 定义贪吃蛇类
class Snake:
def __init__(self, x, y):
self.x = x
self.y = y
self.size = 10
self.speed = 10
self.direction = 'right'
self.body = [[x, y], [x-self.size, y], [x-(2*self.size), y]]
def move(self):
if self.direction == 'right':
self.x += self.speed
elif self.direction == 'left':
self.x -= self.speed
elif self.direction == 'up':
self.y -= self.speed
elif self.direction == 'down':
self.y += self.speed
self.body.insert(0, [self.x, self.y])
self.body.pop()
def draw(self, screen):
for pos in self.body:
pygame.draw.rect(screen, GREEN, [pos[0], pos[1], self.size, self.size])
# 定义食物类
class Food:
def __init__(self):
self.size = 10
self.x = random.randrange(0, SCREEN_WIDTH-self.size, self.size)
self.y = random.randrange(0, SCREEN_HEIGHT-self.size, self.size)
def draw(self, screen):
pygame.draw.rect(screen, RED, [self.x, self.y, self.size, self.size])
# 创建贪吃蛇和食物
snake = Snake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2)
food = Food()
# 设置游戏循环标志
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_RIGHT and snake.direction != 'left':
snake.direction = 'right'
elif event.key == pygame.K_LEFT and snake.direction != 'right':
snake.direction = 'left'
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'
# 移动贪吃蛇
snake.move()
# 判断是否吃到食物
if snake.body[0][0] == food.x and snake.body[0][1] == food.y:
food = Food()
snake.body.append(snake.body[-1])
# 判断是否碰到边界或自身
if snake.body[0][0] < 0 or snake.body[0][0] > SCREEN_WIDTH-snake.size or snake
阅读全文