我想写个贪吃蛇小程序
很好,以下是一个简单的贪吃蛇小程序的示例代码:
import pygame
import random
# 定义一些常量
WIDTH = 640
HEIGHT = 480
FPS = 10
BLOCK_SIZE = 20
# 初始化pygame
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义贪吃蛇的类
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 == "right":
x += BLOCK_SIZE
elif self.direction == "left":
x -= BLOCK_SIZE
elif self.direction == "up":
y -= BLOCK_SIZE
elif self.direction == "down":
y += BLOCK_SIZE
self.body.insert(0, (x, y))
self.body.pop()
def grow(self):
x, y = self.body[0]
if self.direction == "right":
x += BLOCK_SIZE
elif self.direction == "left":
x -= BLOCK_SIZE
elif self.direction == "up":
y -= BLOCK_SIZE
elif self.direction == "down":
y += BLOCK_SIZE
self.body.insert(0, (x, y))
# 定义食物的类
class Food:
def __init__(self):
self.x = random.randrange(0, WIDTH // BLOCK_SIZE) * BLOCK_SIZE
self.y = random.randrange(0, HEIGHT // BLOCK_SIZE) * BLOCK_SIZE
def draw(self, screen):
pygame.draw.rect(screen, RED, (self.x, self.y, BLOCK_SIZE, BLOCK_SIZE))
# 创建贪吃蛇和食物的实例
snake = Snake()
food = Food()
# 定义游戏主循环
running = True
clock = pygame.time.Clock()
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_RIGHT and snake.direction != "left":
snake.direction = "right"
elif event.key == pygame.K_LEFT and snake.direction != "right":
snake.direction = "left"
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] == (food.x, food.y):
snake.grow()
food = Food()
# 判断是否撞墙或撞到自己
if snake.body[0][0] < 0 or snake.body[0][0] >= WIDTH or snake.body[0][1] < 0 or snake.body[0][1] >= HEIGHT:
running = False
for i in range(1, len(snake.body)):
if snake.body[0] == snake.body[i]:
running = False
# 绘制屏幕
screen.fill(BLACK)
snake_rects = [pygame.Rect(x, y, BLOCK_SIZE, BLOCK_SIZE) for x, y in snake.body]
pygame.draw.rect(screen, GREEN, snake_rects[0])
pygame.draw.rect(screen, WHITE, snake_rects[0], 1)
for rect in snake_rects[1:]:
pygame.draw.rect(screen, GREEN, rect)
food.draw(screen)
pygame.display.flip()
# 控制帧率
clock.tick(FPS)
# 关闭pygame
pygame.quit()
这个程序使用了Pygame库,可以通过pip安装。运行程序后,按上下左右键控制贪吃蛇的方向,吃到食物后贪吃蛇会变长,撞到墙或自己后游戏结束
原文地址: http://www.cveoy.top/t/topic/hjKV 著作权归作者所有。请勿转载和采集!