以下是一个使用Python编写的简单贪吃蛇游戏的代码:

python
import pygame
import random
# 蛇类
class Snake():
# 初始化蛇的位置、速度和长度
def __init__(self):
self.length = 1
self.positions = [((SCREEN_WIDTH // 2), (SCREEN_HEIGHT // 2))]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.color = (0, 255, 0)
self.score = 0
# 获取头部位置
def head_position(self):
return self.positions[0]
# 移动蛇
def move(self):
cur = self.head_position()
x, y = self.direction
new = (((cur[0] + (x*GRIDSIZE)) % SCREEN_WIDTH), (cur[1] + (y*GRIDSIZE)) % SCREEN_HEIGHT)
if len(self.positions) > 2 and new in self.positions[2:]:
self.reset()
else:
self.positions.insert(0, new)
if len(self.positions) > self.length:
self.positions.pop()
# 吃食物
def eat(self):
self.length += 1
self.score += 1
# 重置蛇的位置和长度
def reset(self):
self.length = 1
self.positions = [((SCREEN_WIDTH // 2), (SCREEN_HEIGHT // 2))]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.score = 0
# 绘制蛇
def draw(self, surface):
for p in self.positions:
pygame.draw.rect(surface, self.color, (p[0], p[1], GRIDSIZE, GRIDSIZE))
# 食物类
class Food():
# 初始化食物的位置
def __init__(self):
self.position = (0, 0)
self.color = (255, 0, 0)
self.randomize_position()
# 随机生成食物的位置
def randomize_position(self):
self.position = (random.randint(0, GRID_WIDTH-1) * GRIDSIZE, random.randint(0, GRID_HEIGHT-1) * GRIDSIZE)
# 绘制食物
def draw(self, surface):
pygame.draw.rect(surface, self.color, (self.position[0], self.position[1], GRIDSIZE, GRIDSIZE))
# 初始化pygame
pygame.init()
# 定义常量
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 480
GRIDSIZE = 20
GRID_WIDTH = SCREEN_WIDTH // GRIDSIZE
GRID_HEIGHT = SCREEN_HEIGHT // GRIDSIZE
# 定义方向常量
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
# 创建游戏窗口
window = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 初始化蛇和食物
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_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.move()
if snake.head_position() == food.position:
snake.eat()
food.randomize_position()
# 绘制游戏界面
window.fill((0, 0, 0))
snake.draw(window)
food.draw(window)
pygame.display.update()
clock.tick(10)
# 退出游戏
pygame.quit()

查看详情

查看详情