开发库使用:pygame random
直接在终端运行:pip install pygame
pycharm安装库:文件-设置-项目-Python 解释器
import pygame
import random
# 游戏窗口尺寸
window_width = 640
window_height = 480
# 蛇身和食物大小
block_size = 20
# 初始化pygame
pygame.init()
# 创建游戏窗口
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("贪吃蛇")
clock = pygame.time.Clock()
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义蛇类
class Snake:
def __init__(self):
self.body = [(window_width // 2, window_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))
def change_direction(self, new_direction):
if new_direction == "up" and self.direction != "down":
self.direction = new_direction
elif new_direction == "down" and self.direction != "up":
self.direction = new_direction
elif new_direction == "left" and self.direction != "right":
self.direction = new_direction
elif new_direction == "right" and self.direction != "left":
self.direction = new_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.position = self.generate_food_position()
def generate_food_position(self):
x = random.randint(0, (window_width - block_size) // block_size) * block_size
y = random.randint(0, (window_height - block_size) // block_size) * block_size
return x, y
def draw(self):
x, y = self.position
pygame.draw.rect(window, red, (x, y, block_size, block_size))
def check_collision(self, snake):
return snake.body[0] == self.position
# 创建蛇和食物对象
snake = Snake()
food = Food()
game_over = False
# 游戏主循环
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
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 food.check_collision(snake):
food.position = food.generate_food_position()
else:
snake.body.pop()
window.fill(black)
snake.draw()
food.draw()
pygame.display.update()
clock.tick(10)
# 退出游戏
pygame.quit()