用python写一个贪吃蛇
时间: 2023-12-01 15:04:29 浏览: 70
python写的贪吃蛇
5星 · 资源好评率100%
当然可以!以下是一个使用Python编写的简单贪吃蛇游戏示例:
```python
import pygame
import random
# 游戏窗口的宽度和高度
WIDTH = 800
HEIGHT = 600
# 贪吃蛇方块的大小
BLOCK_SIZE = 20
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 初始化游戏
pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇")
clock = pygame.time.Clock()
# 贪吃蛇类
class Snake:
def __init__(self):
self.body = [(WIDTH / 2, HEIGHT / 2)]
self.direction = "right"
def move(self):
x, y = self.body[0]
if self.direction == "up":
y -= BLOCK_SIZE
elif self.direction == "down":
y += BLOCK_SIZE
elif self.direction == "left":
x -= BLOCK_SIZE
elif self.direction == "right":
x += BLOCK_SIZE
self.body.insert(0, (x, y))
self.body.pop()
def change_direction(self, direction):
if direction == "up" and self.direction != "down":
self.direction = direction
elif direction == "down" and self.direction != "up":
self.direction = direction
elif direction == "left" and self.direction != "right":
self.direction = direction
elif direction == "right" and self.direction != "left":
self.direction = direction
def draw(self):
for x, y in self.body:
pygame.draw.rect(window, WHITE, (x, y, BLOCK_SIZE, BLOCK_SIZE))
# 食物类
class Food:
def __init__(self):
self.x = random.randint(0, WIDTH - BLOCK_SIZE)
self.y = random.randint(0, HEIGHT - BLOCK_SIZE)
def draw(self):
pygame.draw.rect(window, RED, (self.x, self.y, BLOCK_SIZE, BLOCK_SIZE))
# 创建贪吃蛇和食物对象
snake = Snake()
food = Food()
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
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] == (food.x, food.y):
snake.body.append((food.x, food.y))
food = Food()
# 检查是否撞到自己的身体
if snake.body[0] in snake.body[1:]:
running = False
# 绘制游戏界面
window.fill(BLACK)
snake.draw()
food.draw()
pygame.display.flip()
# 控制游戏速度
clock.tick(10)
# 退出游戏
pygame.quit()
```
你可以将以上代码保存为一个 Python 文件,运行后将会弹出一个窗口,即可开始游戏。你可以使用上下左右箭头来控制贪吃蛇的移动方向,目标是吃到食物并尽可能地增长身体长度。如有需要,你可以根据自己的需求进行进一步的修改和扩展。
阅读全文