用python写一个贪吃蛇的程序
时间: 2023-08-22 09:07:09 浏览: 134
好的,下面是一个简单的贪吃蛇程序:
```python
import pygame
import random
# 设置窗口尺寸
WINDOW_WIDTH = 400
WINDOW_HEIGHT = 400
# 设置蛇的大小和速度
SNAKE_SIZE = 10
SNAKE_SPEED = 10
# 设置颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 初始化 pygame
pygame.init()
# 创建窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义蛇类
class Snake:
def __init__(self):
self.x = WINDOW_WIDTH / 2
self.y = WINDOW_HEIGHT / 2
self.direction = "up"
self.body = []
self.length = 1
self.score = 0
# 更新蛇的位置
def update(self):
if self.direction == "up":
self.y -= SNAKE_SPEED
elif self.direction == "down":
self.y += SNAKE_SPEED
elif self.direction == "left":
self.x -= SNAKE_SPEED
elif self.direction == "right":
self.x += SNAKE_SPEED
# 添加新的身体部分
self.body.insert(0, (self.x, self.y))
# 删除多余的身体部分
if len(self.body) > self.length:
self.body.pop()
# 绘制蛇
def draw(self):
for x, y in self.body:
pygame.draw.rect(window, GREEN, (x, y, SNAKE_SIZE, SNAKE_SIZE))
# 改变蛇的方向
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 eat_food(self, food):
if self.x == food.x and self.y == food.y:
self.length += 1
self.score += 1
return True
return False
# 检查是否碰到自己或墙壁
def check_collision(self):
if self.x < 0 or self.x > WINDOW_WIDTH - SNAKE_SIZE or self.y < 0 or self.y > WINDOW_HEIGHT - SNAKE_SIZE:
return True
for x, y in self.body[1:]:
if self.x == x and self.y == y:
return True
return False
# 定义食物类
class Food:
def __init__(self):
self.x = random.randint(0, WINDOW_WIDTH - SNAKE_SIZE)
self.y = random.randint(0, WINDOW_HEIGHT - SNAKE_SIZE)
# 绘制食物
def draw(self):
pygame.draw.rect(window, RED, (self.x, self.y, SNAKE_SIZE, SNAKE_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_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.update()
if snake.eat_food(food):
food = Food()
if snake.check_collision():
pygame.quit()
quit()
# 绘制游戏场景
window.fill(BLACK)
snake.draw()
food.draw()
pygame.display.update()
```
这个程序使用 pygame 模块实现了一个简单的贪吃蛇游戏。你可以运行这个程序,看看效果如何。
阅读全文