写一段python代码实现贪吃蛇游戏
时间: 2023-07-25 12:42:46 浏览: 110
好的,以下是一个简单的贪吃蛇游戏的Python代码:
```python
import pygame
import random
# 游戏窗口大小
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 480
# 贪吃蛇每个方块的大小
BLOCK_SIZE = 20
# 初始化pygame
pygame.init()
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 贪吃蛇类
class Snake:
def __init__(self):
# 初始位置在屏幕中央
self.x = WINDOW_WIDTH // 2
self.y = WINDOW_HEIGHT // 2
# 初始方向向右
self.direction = "right"
# 初始长度为3
self.length = 3
# 初始身体坐标列表
self.body = []
for i in range(self.length):
self.body.append((self.x - i * BLOCK_SIZE, self.y))
# 向左移动
def move_left(self):
self.x -= BLOCK_SIZE
self.direction = "left"
# 向右移动
def move_right(self):
self.x += BLOCK_SIZE
self.direction = "right"
# 向上移动
def move_up(self):
self.y -= BLOCK_SIZE
self.direction = "up"
# 向下移动
def move_down(self):
self.y += BLOCK_SIZE
self.direction = "down"
# 移动一步
def move(self):
if self.direction == "left":
self.move_left()
elif self.direction == "right":
self.move_right()
elif self.direction == "up":
self.move_up()
elif self.direction == "down":
self.move_down()
# 在头部添加新坐标
self.body.insert(0, (self.x, self.y))
# 如果长度超过了蛇身体的实际长度,则删除尾部坐标
if len(self.body) > self.length:
self.body.pop()
# 绘制蛇
def draw(self):
for i, (x, y) in enumerate(self.body):
# 头部用红色
if i == 0:
pygame.draw.rect(window, RED, (x, y, BLOCK_SIZE, BLOCK_SIZE))
# 身体用绿色
else:
pygame.draw.rect(window, GREEN, (x, y, BLOCK_SIZE, BLOCK_SIZE))
# 食物类
class Food:
def __init__(self):
# 随机生成一个坐标
self.x = random.randint(0, WINDOW_WIDTH - BLOCK_SIZE)
self.y = random.randint(0, WINDOW_HEIGHT - BLOCK_SIZE)
# 绘制食物
def draw(self):
pygame.draw.rect(window, WHITE, (self.x, self.y, BLOCK_SIZE, BLOCK_SIZE))
# 创建贪吃蛇和食物
snake = Snake()
food = Food()
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and snake.direction != "right":
snake.direction = "left"
elif event.key == pygame.K_RIGHT and snake.direction != "left":
snake.direction = "right"
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()
# 蛇长度加1
snake.length += 1
# 绘制游戏界面
window.fill(BLACK)
snake.draw()
food.draw()
pygame.display.update()
# 判断是否撞墙或撞到自己
if snake.body[0][0] < 0 or snake.body[0][0] >= WINDOW_WIDTH or snake.body[0][1] < 0 or snake.body[0][1] >= WINDOW_HEIGHT:
pygame.quit()
quit()
for i in range(1, len(snake.body)):
if snake.body[0][0] == snake.body[i][0] and snake.body[0][1] == snake.body[i][1]:
pygame.quit()
quit()
# 控制游戏速度
pygame.time.Clock().tick(10)
```
这是一个比较简单的实现,你可以根据自己的需求来修改。
阅读全文