大家好!今天给你们带来了python贪吃蛇游戏!
安装pygame:
pip install pygeme
完整代码:
import random
import sys
import time
import pygame
from pygame.locals import *
from collections import deque
# 基础设置
Screen_Height = 480
Screen_Width = 600
Size = 20# 小方格大小
Line_Width = 1
# 游戏区域的坐标范围
Area_x = (0, Screen_Width // Size - 1)
Area_y = (2, Screen_Height // Size - 1)
# 食物的初步设置
# 食物的分值+颜色
Food_ style_List = [(10, (255, 100, 100)), (20, (100, 255, 100)), (30, (100, 100, 255))]
# 整体颜色设置
Light = (100, 100, 100)
Dark = (200, 200, 200)
Black = (0, 0, 0)
Back_Ground = (40, 40, 60)
# 文本输出格式设置
defPrint_Txt(screen, font, x, y, text, fcolor=(255, 255, 255)):
Text = font.render(text, True, fcolor)
screen.blit(Text, (x, y))
# 初始化蛇
definit_snake():
snake = deque()
# 蛇身初始化,存储位置和颜色,初始颜色设为Dark
snake.append(((2, Area_y[0]), Dark))
snake.append(((1, Area_y[0]), Dark))
snake.append(((0, Area_y[0]), Dark))
return snake
# 食物设置
defCreate_Food(snake, num_foods=5):
foods = []
while len(foods) < num_foods:
food_x = random.randint(Area_x[0], Area_x[1])
food_y = random.randint(Area_y[0], Area_y[1])
if (food_x, food_y) notin [s[0] for s in snake]: # 确保食物不在蛇身上
foods.append((food_x, food_y))
return foods
# 食物风格
defFood_ style():
return random.choice(Food_ style_List) # 返回随机的分值和颜色
defmain():
pygame.init()
screen = pygame.display.set_mode((Screen_Width, Screen_Height))
pygame.display.set_caption('贪吃蛇')
font1 = pygame.font.SysFont('SimHei', 24)
font2 = pygame.font.SysFont(None, 72)
fwidth, fheight = font2.size('GAME OVER')
b = True
snake = init_snake()
foods = Create_Food(snake) # 改为生成多个食物
food_ styles = [Food_ style() for _ in range(5)] # 每个食物一个风格
pos = (1, 0)
game_over = True
game_start = False
score = 0
orispeed = 0.3
speed = orispeed
last_move_time = None
pause = False
whileTrue:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_RETURN:
if game_over:
game_start = True
game_over = False
b = True
snake = init_snake()
foods = Create_Food(snake)
food_ styles = [Food_ style() for _ in range(5)]
pos = (1, 0)
score = 0
last_move_time = time.time()
elif event.key == K_SPACE:
ifnot game_over:
pause = not pause
elif event.key in (K_UP, K_w):
if b andnot pos[1]:
pos = (0, -1)
b = False
elif event.key in (K_DOWN, K_s):
if b andnot pos[1]:
pos = (0, 1)
b = False
elif event.key in (K_LEFT, K_a):
if b andnot pos[0]:
pos = (-1, 0)
b = False
elif event.key in (K_RIGHT, K_d):
if b andnot pos[0]:
pos = (1, 0)
b = False
screen.fill(Back_Ground)
for x in range(Size, Screen_Width, Size):
pygame.draw.line(screen, Black, (x, Area_y[0] * Size), (x, Screen_Height), Line_Width)
for y in range(Area_y[0] * Size, Screen_Height, Size):
pygame.draw.line(screen, Black, (0, y), (Screen_Width, y), Line_Width)
ifnot game_over:
curTime = time.time()
if curTime - last_move_time > speed:
ifnot pause:
b = True
last_move_time = curTime
next_s = (snake[0][0][0] + pos[0], snake[0][0][1] + pos[1])
eaten = False
for i, food in enumerate(foods):
if next_s == food:
# 吃到食物时,只有新加入的蛇头采用食物颜色,其余部分保持不变
snake.appendleft((next_s, food_ styles[i][1]))
score += food_ styles[i][0]
speed = orispeed - 0.03 * (score // 100)
foods[i] = Create_Food(snake, 1)[0] # 重新生成被吃掉的食物
food_ styles[i] = Food_ style()
eaten = True
break
ifnot eaten:
if Area_x[0] <= next_s[0] <= Area_x[1] and Area_y[0] <= next_s[1] <= Area_y[1] and next_s notin [s[0] for s in snake]:
snake.appendleft((next_s, snake[-1][1])) # 新增蛇头使用蛇尾的颜色
snake.pop()
else:
game_over = True
# 绘制食物
for i, food in enumerate(foods):
pygame.draw.rect(screen, food_ styles[i][1], (food[0] * Size, food[1] * Size, Size, Size), 0)
# 绘制蛇
for s in snake:
pygame.draw.rect(screen, s[1], (s[0][0] * Size + Line_Width, s[0][1] * Size + Line_Width, Size - Line_Width * 2, Size - Line_Width * 2), 0)
Print_Txt(screen, font1, 30, 7, f'速度: {score // 100}')
Print_Txt(screen, font1, 450, 7, f'得分: {score}')
if game_over:
if game_start:
Print_Txt(screen, font2, (Screen_Width - fwidth) // 2, (Screen_Height - fheight) // 2, 'GAME OVER', Red)
pygame.display.update()
if __name__ == '__main__':
main()