贪吃蛇Python代码
时间: 2023-11-05 08:12:48 浏览: 27
以下是一个简单的贪吃蛇Python代码:
```python
import pygame
import random
# 游戏参数
WIDTH = 500
HEIGHT = 500
GRID_SIZE = 20
# 颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 初始化游戏
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.body = [(WIDTH/2, HEIGHT/2)]
self.direction = random.choice(["UP", "DOWN", "LEFT", "RIGHT"])
def move(self):
x, y = self.body[0]
if self.direction == "UP":
y -= GRID_SIZE
elif self.direction == "DOWN":
y += GRID_SIZE
elif self.direction == "LEFT":
x -= GRID_SIZE
elif self.direction == "RIGHT":
x += GRID_SIZE
self.body.insert(0, (x, y))
self.body.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 grow(self):
x, y = self.body[0]
if self.direction == "UP":
y -= GRID_SIZE
elif self.direction == "DOWN":
y += GRID_SIZE
elif self.direction == "LEFT":
x -= GRID_SIZE
elif self.direction == "RIGHT":
x += GRID_SIZE
self.body.insert(0, (x, y))
def draw(self):
for x, y in self.body:
pygame.draw.rect(screen, GREEN, (x, y, GRID_SIZE, GRID_SIZE))
def check_collision(self):
x, y = self.body[0]
if x < 0 or x >= WIDTH or y < 0 or y >= HEIGHT:
return True
for i in range(1, len(self.body)):
if self.body[i] == self.body[0]:
return True
return False
# 定义食物类
class Food:
def __init__(self):
self.x = random.randrange(0, WIDTH, GRID_SIZE)
self.y = random.randrange(0, HEIGHT, GRID_SIZE)
def draw(self):
pygame.draw.rect(screen, RED, (self.x, self.y, GRID_SIZE, GRID_SIZE))
# 创建贪吃蛇和食物
snake = Snake()
food = Food()
# 游戏循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
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()
# 检查贪吃蛇是否碰撞
if snake.check_collision():
pygame.quit()
sys.exit()
# 检查贪吃蛇是否吃到食物
if snake.body[0] == (food.x, food.y):
snake.grow()
food = Food()
# 绘制游戏界面
screen.fill(BLACK)
snake.draw()
food.draw()
pygame.display.update()
# 控制游戏速度
clock.tick(10)
```