写贪吃蛇用python
时间: 2023-09-29 20:06:51 浏览: 65
好的,下面是一个简单的贪吃蛇游戏,使用 Python 语言编写。
```python
import pygame
import random
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义方块大小
BLOCK_SIZE = 20
# 初始化 pygame
pygame.init()
# 设置窗口大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
WINDOW_SIZE = (WINDOW_WIDTH, WINDOW_HEIGHT)
screen = pygame.display.set_mode(WINDOW_SIZE)
# 设置窗口标题
pygame.display.set_caption("贪吃蛇")
# 设置时钟对象
clock = pygame.time.Clock()
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.body = [(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2)]
self.direction = "right"
def move(self):
head_x, head_y = self.body[0]
if self.direction == "up":
new_head = (head_x, head_y - BLOCK_SIZE)
elif self.direction == "down":
new_head = (head_x, head_y + BLOCK_SIZE)
elif self.direction == "left":
new_head = (head_x - BLOCK_SIZE, head_y)
elif self.direction == "right":
new_head = (head_x + BLOCK_SIZE, head_y)
self.body.insert(0, new_head)
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 draw(self, screen):
for block in self.body:
x, y = block
pygame.draw.rect(screen, 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, screen):
pygame.draw.rect(screen, RED, (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()
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.body[0][0] == food.x and snake.body[0][1] == food.y:
snake.body.append((food.x, food.y))
food = Food()
# 判断是否碰到边界或自己的身体
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 \
or snake.body[0] in snake.body[1:]:
pygame.quit()
exit()
# 绘制背景和贪吃蛇和食物
screen.fill(BLACK)
snake.draw(screen)
food.draw(screen)
# 刷新屏幕
pygame.display.flip()
# 控制帧率
clock.tick(10)
```
这是一个简单的贪吃蛇游戏,其中包括贪吃蛇类和食物类,以及游戏循环和事件处理等。你可以将代码复制到你的 Python 编辑器中执行,或者将代码保存为 `.py` 文件并在命令行中运行。
阅读全文