今天我们来用python做一款属于自己的小游戏——贪吃蛇。众所周知哈,pygame入门级游戏应该是非贪吃蛇莫属了,只需要一点简单的算法就能够完美还原童年的感觉。当然了,目前网上的贪吃蛇数量众多,质量参差不齐,直接复制别人的代码多多少少还是有点不安心的。于是乎,我们能不能打造一款完全属于自己的贪吃蛇小游戏呢,让我们来试试吧!
import pygame as py
import sys, random, time
def RandomColor():
R = random.randint(0, 200)
G = random.randint(0, 200)
B = random.randint(0, 200)
color = [R, G, B]
return color
def score(color):
s = sum(color) / 255 * (10 / 3)
return s
def food(X):
position = [10 * random.randint(0, 79), 10 * random.randint(31, 59)]
while True:
if position in X:
position = [10 * random.randint(0, 79), 10 * random.randint(0, 59)]
else:
break
return position
def DrawScore(GameScore, BasicFont):
py.draw.rect(screen, [255, 255, 255], [0, 0, 800, 30], 0)
ScoreSurf = BasicFont.render('Score:{}'.format(int(GameScore)), True, (0, 0, 128))
ScoreRect = ScoreSurf.get_rect()
ScoreRect.midtop = (400, 0)
screen.blit(ScoreSurf, ScoreRect)
py.display.flip()
def ThroughWall():
global Snake
if Snake[-1][0] >= 800:
Snake[-1][0] = 0
elif Snake[-1][1] >= 600:
Snake[-1][1] = 0
elif Snake[-1][1] < 0:
Snake[-1][1] = 590
elif Snake[-1][0] < 0:
Snake[-1][0] = 790
def SnakeMove(Direction):
global SnakeColor, Snake
Dele = [0, 0]
if Direction == 'up':
SnakeHead = [Snake[-1][0], Snake[-1][1] - 10]
Dele = Snake.pop(0)
Snake.append(SnakeHead)
elif Direction == 'down':
SnakeHead = [Snake[-1][0], Snake[-1][1] + 10]
Dele = Snake.pop(0)
Snake.append(SnakeHead)
elif Direction == 'left':
SnakeHead = [Snake[-1][0] - 10, Snake[-1][1]]
Dele = Snake.pop(0)
Snake.append(SnakeHead)
elif Direction == 'right':
SnakeHead = [Snake[-1][0] + 10, Snake[-1][1]]
Dele = Snake.pop(0)
Snake.append(SnakeHead)
ThroughWall()
for rect in range(0, len(Snake)):
py.draw.rect(screen, SnakeColor[rect], Snake[rect] + [10, 10], 0)
py.draw.rect(screen, [255, 255, 255], Dele + [10, 10], 0)
py.display.flip()
def PlaySound_eat():
global GameVoice
name = random.randint(1, 3)
sound = py.mixer.Sound('0{}.wav'.format(name))
py.mixer.music.set_volume(GameVoice)
sound.play(0, 0, 1)
def SnakeEatFood():
global food_position, food_screen, food_list, GameScore, food_color_list, GameVoice
if len(food_screen) == 1:
if food_position in Snake: # 吃到食物
PlaySound_eat()
food_list.append(food_position)
food_position = []
food_screen = []
GameScore += 1 # 计算得分
DrawScore(GameScore, BasicFont)
elif len(food_screen) == 0:
food_position = food(Snake)
food_screen.append(food_position)
food_color = RandomColor()
food_color_list.append(food_color)
py.draw.rect(screen, food_color, food_position + [10, 10], 0)
py.display.flip()
def SnakeGrowth(Snake):
global food_list, food_color_list
if len(food_list) > 0:
if food_list[0] not in Snake:
Snake.insert(0, food_list.pop(0))
SnakeColor.insert(0, food_color_list.pop(0))
def key_contrl(event):
global Direction, MusicPause, SnakeColor, Snake, GameVoice
Dele = [0, 0]
if event.key == py.K_UP and Direction != 'down':
SnakeHead = [Snake[-1][0], Snake[-1][1] - 10]
Dele = Snake.pop(0)
Snake.append(SnakeHead)
Direction = 'up'
elif event.key == py.K_DOWN and Direction != 'up':
SnakeHead = [Snake[-1][0], Snake[-1][1] + 10]
Dele = Snake.pop(0)
Snake.append(SnakeHead)
Direction = 'down'
elif event.key == py.K_LEFT and Direction != 'right':
SnakeHead = [Snake[-1][0] - 10, Snake[-1][1]]
Dele = Snake.pop(0)
Snake.append(SnakeHead)
Direction = 'left'
elif event.key == py.K_RIGHT and Direction != 'left':
SnakeHead = [Snake[-1][0] + 10, Snake[-1][1]]
Dele = Snake.pop(0)
Snake.append(SnakeHead)
Direction = 'right'
elif event.key == py.K_SPACE and MusicPause == False:
py.mixer.music.pause()
MusicPause = True
elif event.key == py.K_SPACE and MusicPause == True:
py.mixer.music.unpause()
MusicPause = False
elif event.key == py.K_1:
GameVoice += 0.1
elif event.key == py.K_2:
GameVoice -= 0.1
ThroughWall()
for rect in range(0, len(Snake)):
py.draw.rect(screen, SnakeColor[rect], Snake[rect] + [10, 10], 0)
py.draw.rect(screen, [255, 255, 255], Dele + [10, 10], 0)
py.display.flip()
def GameOver(Snake, BasicFont):
copy_SnakeHead = Snake[-1]
if Snake.count(copy_SnakeHead) > 1:
# py.quit()
OverSurf = BasicFont.render('Game Over', True, (0, 0, 0))
OverRect = OverSurf.get_rect()
OverRect.midtop = (400, 300)
screen.blit(OverSurf, OverRect)
py.display.flip()
time.sleep(3)
sys.exit()
def head_path(food_position, Snake):
SnakeHead = Snake[-1]
Dir = []
if food_position[0] > SnakeHead[0] and food_position[1] > SnakeHead[1]:
Dir = [3, 1]
elif food_position[0] < SnakeHead[0] and food_position[1] > SnakeHead[1]:
Dir = [2, 1]
elif food_position[0] > SnakeHead[0] and food_position[1] < SnakeHead[1]:
Dir = [3, 0]
elif food_position[0] < SnakeHead[0] and food_position[1] < SnakeHead[1]:
Dir = [2, 0]
return Dir
def AiContrlSnake(Snake, Direction):
global food_position
ShortPath = []
CopySnake = Snake
load_path = ['up', 'down', 'left', 'right']
Dir = head_path(food_position, Snake)
DirLoadPath = [load_path[Dir[0]], load_path[Dir[1]]]
# 同方向
if Direction in DirLoadPath:
SnakeHead = Snake[-1]
CopySnake.pop(0)
SnakeHead_path = [SnakeHead[0] + 2 * (Dir[0] - 2.5) * 10, SnakeHead[1] + 2 * (0.5 - Dir[1]) * 10]
SnakeHead1 = [SnakeHead[0], SnakeHead_path[1]]
SnakeHead2 = [SnakeHead_path[0], SnakeHead[1]]
VirSnake = [SnakeHead1, SnakeHead2]
path = []
for S in VirSnake:
if S in CopySnake:
path.append(False)
else:
path.append(True)
if __name__ == '__main__':
py.init()
GameVoice = 0.1 # 定义游戏音效
py.mixer.music.load('BGM.mp3') # 加载背景音乐
py.mixer.music.play(-1, 0.0) # 循环播放
py.mixer.music.set_volume(GameVoice) # 设置音量
FPSCLOCK = py.time.Clock()
screen = py.display.set_mode((800, 600))
py.display.set_caption('至尊彩虹贪吃蛇')
screen.fill([255, 255, 255])
py.display.flip()
BasicFont = py.font.SysFont("'resources/ARBERKLEY.ttf'", 40)
GameScore = 0
DrawScore(GameScore, BasicFont)
food_list, food_screen = [], []
Snake = [[0, 0], [10, 0], [20, 0]] # 定义蛇
SnakeColor = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] # 定义初始皮肤颜色
food_color_list = []
food_position = []
Direction = 'right'
Score = 0
MusicPause = False
while True:
SnakeEatFood()
SnakeMove(Direction)
GameOver(Snake, BasicFont)
SnakeGrowth(Snake)
for event in py.event.get():
if event.type == py.QUIT:
sys.exit()
elif event.type == py.KEYDOWN:
key_contrl(event)
SnakeGrowth(Snake)
py.display.flip()
FPSCLOCK.tick(11)
通过以上程序,我们实现了一个彩虹版的贪吃蛇(可以穿越边界),同时每次吃到食物都会弹出一个随机的音效,这里我设置了三款音效。有时间的话,下次我会加入一个排行榜,可以记录每次游戏的时间与最终得分。