功能:
- 上下左右键控制贪吃蛇朝各个方向移动,每吃一个食物就长大一截;
- 黑底白框易于机器识别;
- 机器实现自动化时,可以深度游戏底层,自创user event事件,用pygame.event.post提交键盘事件。
- 空格键暂停,esc键退出。
代码:
import pygame
import sys,os,random
pygame.init()
screen = pygame.display.set_mode((600,600))
pygame.display.set_caption('巴拉巴拉小魔仙')
fclock = pygame.time.Clock()
snake = [[300,300],[290,300],[280,300]]
directions = {'up':(0,-10),'down':(0,10),'left':(-10,0),'right':(10,0)}
direct = 'right'
pause = True
fps = 10
def manhattan_distance(p1,p2):
return abs(p1[0]-p2[0]) + abs(p1[1]-p2[1])
def gen_food_pos():
x,y = random.randint(0,590),random.randint(0,590)
if (x,y) in snake:
gen_food_pos()
return x,y
def gen_food(food_pos):
return pygame.draw.rect(screen, (255,255,255), [food_pos[0],food_pos[1], 10, 10])
def gen_snake(snake):
snake_body = []
for x,y in snake:
snake_body.append(pygame.draw.rect(screen, (255,255,255), [x, y, 10, 10]))
return snake_body
def move(dircetion):
step = directions.get(dircetion)
snake[1:] = snake[:-1]
snake[0] = snake[0][0] + step[0] ,snake[0][1] + step[1]
return snake
def inhance_snake(pos,snake):
head = snake_body[0]
if pos[0] < head.x :
if abs(pos[0] - head.x) > abs(pos[1] - head.y) :
newhead = [[head.x-10,head.y]]
snake = newhead + snake
else:
newhead = [[head.x+10,head.y]]
snake = newhead + snake
else :
if abs(pos[1] - head.y) > abs(pos[0] - head.x) :
newhead = [[head.x-10,head.y-10]]
snake = newhead + snake
else:
newhead = [[head.x-10,head.y+10]]
snake = newhead + snake
return snake
while True:
food_pos = gen_food_pos()
while True:
if food_pos != snake [0]:
for event in pygame.event.get():
if event.type == pygame.QUIT:sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP :direct = 'up'
elif event.key == pygame.K_DOWN :direct = 'down'
elif event.key == pygame.K_LEFT :direct = 'left'
elif event.key == pygame.K_RIGHT:direct = 'right'
elif event.key == pygame.K_ESCAPE:sys.exit()
elif event.key == pygame.K_SPACE and pause is True:
directions = {'up':(0,0),'down':(0,0),'left':(0,0),'right':(0,0)}
pause = False
elif event.key == pygame.K_SPACE and pause is False:
directions = {'up':(0,-10),'down':(0,10),'left':(-10,0),'right':(10,0)}
pause = True
else :pass
fclock.tick(fps)
screen.fill((0,0,0))
food = gen_food(food_pos)
snake = move(direct)
snake_body = gen_snake(snake)
pygame.display.update()
head = snake_body[0]
if manhattan_distance(food_pos,(head.x,head.y)) <= 15:
snake = inhance_snake(food_pos,snake)
break
可以改善的地方:
- 增加积分制,作为深度学习的激励函数;
- 没有实现小蛇的惩罚项,目前无论是碰到四壁还是自身都不会死的。
样本:
巴拉巴拉小魔仙贪吃蛇
网友评论