绘制一条游行的蛇pyhton
时间: 2023-09-21 21:06:52 浏览: 73
利用Python绘制出一条会动的蟒蛇
以下是使用 Python 的 Pygame 库绘制游行蛇的示例代码:
```python
import pygame
import random
# 定义常量
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
SNAKE_SIZE = 20
FOOD_SIZE = 10
SNAKE_COLOR = (0, 255, 0)
FOOD_COLOR = (255, 0, 0)
BACKGROUND_COLOR = (0, 0, 0)
# 初始化 Pygame
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Snake Game')
# 定义 Snake 类
class Snake:
def __init__(self):
self.x = SCREEN_WIDTH // 2
self.y = SCREEN_HEIGHT // 2
self.direction = random.choice(['up', 'down', 'left', 'right'])
self.body = [(self.x, self.y)]
def move(self):
if self.direction == 'up':
self.y -= SNAKE_SIZE
elif self.direction == 'down':
self.y += SNAKE_SIZE
elif self.direction == 'left':
self.x -= SNAKE_SIZE
elif self.direction == 'right':
self.x += SNAKE_SIZE
self.body.insert(0, (self.x, self.y))
self.body.pop()
def draw(self):
for x, y in self.body:
pygame.draw.rect(screen, SNAKE_COLOR, (x, y, SNAKE_SIZE, SNAKE_SIZE))
# 定义 Food 类
class Food:
def __init__(self):
self.x = random.randint(0, SCREEN_WIDTH - FOOD_SIZE)
self.y = random.randint(0, SCREEN_HEIGHT - FOOD_SIZE)
def draw(self):
pygame.draw.rect(screen, FOOD_COLOR, (self.x, self.y, FOOD_SIZE, FOOD_SIZE))
# 创建 Snake 和 Food 对象
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.direction = 'up'
elif event.key == pygame.K_DOWN:
snake.direction = 'down'
elif event.key == pygame.K_LEFT:
snake.direction = 'left'
elif event.key == pygame.K_RIGHT:
snake.direction = 'right'
# 移动 Snake
snake.move()
# 判断是否吃到了 Food
if snake.body[0][0] == food.x and snake.body[0][1] == food.y:
snake.body.append((snake.body[-1][0], snake.body[-1][1]))
food = Food()
# 绘制游戏界面
screen.fill(BACKGROUND_COLOR)
snake.draw()
food.draw()
pygame.display.update()
```
运行以上代码,即可在 Pygame 窗口中看到游行蛇的效果。玩家可以通过方向键控制蛇的移动方向,目标是吃到食物并尽可能长时间地存活下去。
阅读全文