python 写一个贪吃蛇代码
时间: 2023-10-16 22:11:10 浏览: 31
好的,以下是一个简单的贪吃蛇代码:
```python
import pygame
from pygame.locals import *
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 480
WINDOW_TITLE = '贪吃蛇'
# 设置颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 创建游戏窗口
game_window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption(WINDOW_TITLE)
# 定义字体
font = pygame.font.SysFont(None, 30)
# 定义方向
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
# 定义蛇类
class Snake:
def __init__(self):
self.size = 3
self.positions = [(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2)]
# 随机生成食物位置
self.food_position = self._generate_food()
# 初始方向向右
self.direction = RIGHT
def _generate_food(self):
x = random.randint(0, WINDOW_WIDTH - 20)
y = random.randint(0, WINDOW_HEIGHT - 20)
return x, y
def move(self):
x, y = self.positions[0]
if self.direction == UP:
y -= 20
elif self.direction == DOWN:
y += 20
elif self.direction == LEFT:
x -= 20
elif self.direction == RIGHT:
x += 20
self.positions.insert(0, (x, y))
if len(self.positions) > self.size:
self.positions.pop()
def turn(self, direction):
self.direction = direction
def get_head_position(self):
return self.positions[0]
def get_body_position(self):
return self.positions[1:]
def eat_food(self):
self.size += 1
self.food_position = self._generate_food()
def draw(self, surface):
for position in self.positions:
pygame.draw.rect(surface, GREEN, (position[0], position[1], 20, 20))
# 定义食物类
class Food:
def __init__(self, position):
self.position = position
def draw(self, surface):
pygame.draw.rect(surface, RED, (self.position[0], self.position[1], 20, 20))
# 创建贪吃蛇和食物
snake = Snake()
food = Food(snake.food_position)
# 游戏循环
clock = pygame.time.Clock()
game_over = False
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == QUIT:
game_over = True
elif event.type == KEYDOWN:
if event.key == K_UP:
snake.turn(UP)
elif event.key == K_DOWN:
snake.turn(DOWN)
elif event.key == K_LEFT:
snake.turn(LEFT)
elif event.key == K_RIGHT:
snake.turn(RIGHT)
# 移动贪吃蛇
snake.move()
# 判断贪吃蛇是否吃到食物
if snake.get_head_position() == food.position:
snake.eat_food()
food = Food(snake.food_position)
# 判断贪吃蛇是否撞墙或者自己
if snake.get_head_position()[0] < 0 or snake.get_head_position()[0] > WINDOW_WIDTH - 20 or snake.get_head_position()[1] < 0 or snake.get_head_position()[1] > WINDOW_HEIGHT - 20 or snake.get_head_position() in snake.get_body_position():
game_over = True
# 绘制游戏窗口
game_window.fill(BLACK)
snake.draw(game_window)
food.draw(game_window)
pygame.display.update()
# 控制游戏帧率
clock.tick(10)
# 游戏结束
game_over_text = font.render('GAME OVER', True, WHITE, BLACK)
game_window.blit(game_over_text, (WINDOW_WIDTH / 2 - 80, WINDOW_HEIGHT / 2 - 15))
pygame.display.update()
# 等待3秒后退出
pygame.time.wait(3000)
pygame.quit()
```
这是一个基础版本的贪吃蛇,你可以根据自己的需求进行修改和完善。
阅读全文