python简单贪吃蛇开发
本文实例为大家分享了python简单贪吃蛇的具体代码,供大家参考,具体内容如下
importsys
importrandom
importpygame
frompygame.localsimport*
#目标方块的颜色红色
redColor=pygame.Color(255,0,0)
#游戏界面的背景颜色纯黑色
blackColor=pygame.Color(0,0,0)
#贪吃蛇的颜色白色
whiteColor=pygame.Color(255,255,255)
#定义游戏结束的函数
defgameOver():
pygame.quit()
sys.exit()
#定义main函数
defmain():
#初始化pygame
pygame.init()
#定义一个控制速度的函数
fpsClock=pygame.time.Clock()
#创建显示层
playSurface=pygame.display.set_mode((640,480))#界面的大小
pygame.display.set_caption('贪吃蛇')
#初始化蛇的位置
snake_position=[100,100]
#初始化蛇的长度
snake_body=[[100,100],[80,100],[60,100]]
#初始化目标方块的位置
target_position=[300,300]
#目标方块的状态
target_flag=1
#初始化一个方向
direction='right'
#定义蛇的方向变量
changeDirection=direction
whileTrue:
#pygame的交互模块和事件队列
foreventinpygame.event.get():
#是否推出
ifevent.type==QUIT:
pygame.quit()
sys.exit()
#判断键盘事件
elifevent.type==KEYDOWN:
ifevent.key==K_RIGHT:
changeDirection='right'
ifevent.key==K_LEFT:
changeDirection='left'
ifevent.key==K_UP:
changeDirection='up'
ifevent.key==K_DOWN:
changeDirection='down'
ifevent.key==K_SPACE:
pygame.event.post(pygame.event.Event(QUIT))
#根据键盘反应确定方向
ifchangeDirection=='left'andnotdirection=='right':
direction=changeDirection
ifchangeDirection=='right'andnotdirection=='left':
direction=changeDirection
ifchangeDirection=='up'andnotdirection=='down':
direction=changeDirection
ifchangeDirection=='down'andnotdirection=='up':
direction=changeDirection
#根据方向移动蛇头的坐标
ifdirection=='right':
snake_position[0]+=20
ifdirection=='left':
snake_position[0]-=20
ifdirection=='up':
snake_position[1]-=20
ifdirection=='down':
snake_position[1]+=20
#蛇与自身的碰撞检测
forbodyinsnake_body:
ifsnake_position[0]==body[0]andsnake_position[1]==body[1]:
gameOver()
#蛇移动
snake_body.insert(0,list(snake_position))
ifsnake_position[0]==target_position[0]andsnake_position[1]==target_position[1]:
target_flag=0
else:
#如果没吃到,蛇尾弹出栈
snake_body.pop()
#如果吃掉目标方块,重新生成一个目标方块
iftarget_flag==0:
x=random.randrange(1,32)
y=random.randrange(1,24)
#20*20的像素为一个小矩形
target_position=[int(x*20),int(y*20)]
target_flag=1
#绘制显示层
playSurface.fill(blackColor)
#绘制蛇
forpositioninsnake_body:
pygame.draw.rect(playSurface,redColor,Rect(position[0],position[1],20,20))
#画目标方块
pygame.draw.rect(playSurface,whiteColor,Rect(target_position[0],target_position[1],20,20))
pygame.display.flip()
#判断死亡
ifsnake_position[0]>620orsnake_position[1]<0:
gameOver()
elifsnake_position[1]>460orsnake_position[1]<0:
gameOver()
#控制游戏的速度
fpsClock.tick(5)
if__name__=='__main__':
main()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。