python实现简单的贪吃蛇游戏

 更新时间:2021年3月19日 10:00  点击:1624

本文实例为大家分享了python实现贪吃蛇游戏的具体代码,加入按钮、难度、音乐、得分功能,供大家参考,具体内容如下

贪吃蛇小游戏,可以显示出得分,又背景音乐,难度选择和开始重启按钮设置。

游戏实现效果如下:

后面有完整代码和解析

import sys
import pygame
import random

class Button(object):#定义按钮类
 def __init__(self,begin1,begin2,restart1,restart2,position,position2):
 self.gamebegin1=pygame.image.load(begin1).convert_alpha()#导入开始和重启按钮图片
 self.gamebegin2=pygame.image.load(begin2).convert_alpha()
 self.gamerestart1=pygame.image.load(restart1).convert_alpha()
 self.gamerestart2=pygame.image.load(restart2).convert_alpha()
 self.position=position
 self.position2=position2
 
 def ifpress(self):
 point_x,point_y=pygame.mouse.get_pos()#找到鼠标光标所在位置
 x,y=self.position#指定的点击按钮位置
 w,h=self.gamebegin1.get_size()#定义按钮尺寸
 x-=w/2
 y-=h/2
 if_x=x-w/2<point_x<x+w/2#判断鼠标光标是否在按钮上
 if_y=y-h/2<point_y<y+h/2
 return if_x and if_y

 def ispress(self):
 x,y=self.position
 w,h=self.gamebegin1.get_size()
 x-=w/2
 y-=h/2
 if self.ifpress():#如果鼠标光标在按钮上,图片显示为gamebegin1,否则显示为gamebegin2
  screen.blit(self.gamebegin1,(x-w/2+8,y-h/2+7))  
 else:
  screen.blit(self.gamebegin2,(x-w/2,y-h/2))
 #定义重启按钮,方法同上
 def ifrepress(self):
 point_x,point_y=pygame.mouse.get_pos()
 x,y=self.position2
 w,h=self.gamerestart1.get_size()
 x-=w/2
 y-=h/2
 if_x=x-w/2<point_x<x+w/2
 if_y=y-h/2<point_y<y+h/2
 return if_x and if_y

 def isrepress(self):
 x,y=self.position2
 w,h=self.gamerestart1.get_size()
 x-=w/2
 y-=h/2
 if self.ifrepress():
  screen.blit(self.gamerestart1,(x-w/2,y-h/2))  
 else:
  screen.blit(self.gamerestart2,(x-w/2,y-h/2))
  
def choice():#定义选择难度
 screen.fill((0,0,0))#初始界面颜色设置为黑色
 Rect1=pygame.Rect(300,300,200,100)#设置按钮尺寸
 Rect2=pygame.Rect(300,450,200,100)
 pygame.draw.rect(screen,(136,189,186),Rect1)#创建按钮
 screen.blit(font.render('grade one:',-1,(255,255,255)),(300,300))
 pygame.draw.rect(screen,(136,189,186),Rect2)
 screen.blit(font.render('grade two:',-1,(255,255,255)),(300,450))
 pygame.display.flip()#显示到屏幕上
 point_x,point_y=pygame.mouse.get_pos()#找到鼠标光标所在位置
 global a,b#定义全局变量
 if 300<point_x<500 and 300<point_y<400:#判断光标是否在按钮上
 if pygame.mouse.get_pressed()[0]:#判断鼠标是否按下
  a=8#a表示没秒执行8次
  b=1#b表示设定的一个数,与后面判断执行时有关
 if 300<point_x<500 and 450<point_y<550:
 if pygame.mouse.get_pressed()[0]:
  a=12
  b=1
 pygame.display.update()#更新屏幕
 

def getResult():#游戏结束时出现得分结果和gameover
 final_text1='Game_Over'
 final_text2='Your final score is: '+str(score)
 ft1_font=pygame.font.SysFont('Arial',70)
 ft1_surf=font.render(final_text1,1,(242,3,36))
 screen.blit(ft1_surf,[screen.get_width()/2-ft1_surf.get_width()/2,100])
 pygame.display.flip()

def main():
 pygame.init()#初始化pygame
 clock=pygame.time.Clock()#定义时间
 pygame.font.init()#初始化字符
 #需要在其它定义中出现的参数,这里还需要定义全局变量一下
 global score,screen,font,button,status,x,y,direction,snackhead,snackbody,foodposition,state,a,b
 screen=pygame.display.set_mode((640,640))#设置屏幕尺寸
 screen.fill((0,0,0))#填充屏幕颜色
 #指明图片路径
 beginname1='D://picture//gamebegin1.png'
 beginname2='D://picture//gamebegin2.png'
 restartname1='D://picture//restart1.png'
 restartname2='D://picture//restart2.png'
 pygame.display.set_caption('sanckgame')
 font=pygame.font.SysFont('Arial',40)#定义字符种类和大小
 snackhead=[120,120]#定义初始蛇的头部位置
 foodposition=[360,360]#定义初始食物位置
 snackbody=[[120,120],[100,120],[80,120]]#定义蛇全身位置 
 score=0
 x=300
 y=300
 state=0
 a=1
 b=0
 food_eat=1#食物被吃为0,否则为1
 direction='right'#定义初始运动方向
 re_direction=direction#re_direction为变化后的方向
 button = Button(beginname1,beginname2,restartname1,restartname2,(330,300),(600,320))#定义按钮数值 
 pygame.display.update()

 
 while True:
  
 for event in pygame.event.get():#遍历可能出现的事件

  if event.type == pygame.QUIT:#点击关闭,程序关闭
  pygame.quit()
  sys.exit()
 button.ispress()#显示按钮
 pygame.display.update()
 if button.ifpress():
  if pygame.mouse.get_pressed()[0]:   
  break #点击按钮,结束这里的循环,进入游戏选择难度界面
 while True:
 for event in pygame.event.get():

  if event.type == pygame.QUIT:
  pygame.quit()
  sys.exit()
 choice()#运行choice()
 if b==1:#如果点击了按钮,结束循环,进入游戏运行界面
  break
 pygame.mixer.init()#初始化音乐
 pygame.mixer.music.load('D://music//Above Everything - Capo Productions.ogg')#导入音乐 
 pygame.display.update()
 status=True
 screen=pygame.display.set_mode((640,640))
 screen.fill((0,0,0))
 while status:
 clock.tick(a)#运行速度
 
 for event in pygame.event.get():

  if event.type == pygame.QUIT:
  pygame.quit()
  sys.exit()
  
  elif event.type == pygame.KEYDOWN:#判断键盘事件
  if event.key == pygame.K_RIGHT or event.key == ord('d'):
   re_direction='right'
  if event.key == pygame.K_LEFT or event.key == ord('a'):
   re_direction='left'
  if event.key == pygame.K_UP or event.key == ord('w'):
   re_direction='up'
  if event.key == pygame.K_DOWN or event.key == ord('s'):
   re_direction='down'
 #跳出判断事件循环
 if re_direction=='right'and not direction =='left':
  direction=re_direction
 if re_direction=='left'and not direction =='right':
  direction=re_direction
 if re_direction=='up'and not direction =='down':
  direction=re_direction
 if re_direction=='down'and not direction =='up':
  direction=re_direction
 #头部坐标变化 
 if direction=='left':
  snackhead[0]-=20
 if direction=='right':
  snackhead[0]+=20
 if direction=='down':
  snackhead[1]+=20  
 if direction=='up':
  snackhead[1]-=20
 snackbody.insert(0,list(snackhead))#每移动一次,把头部新位置插入到最前面,形成新的头部
 
 if snackhead[0]==foodposition[0] and snackhead[1]==foodposition[1]:#判断蛇是否吃到了食物
  food_eat=0
  score+=1
  pygame.display.update()
 else:
  snackbody.pop()#没吃到则将位置变化前的尾部剔除出去,设的长度不变
 pygame.display.update()
 if food_eat==0:#迟到食物后生成新的食物
  x=random.randint(1,31)
  y=random.randint(1,31)
  for position in snackbody:#判断食物是否出现在蛇的身体处,出现则重新生成
  if not x == position[0] and not y == position[1]:
   state=1
  else:
   state=0
  if state ==1:
  foodposition=[int(x*20),int(y*20)]
  food_eat=1
  
 screen.fill((0,0,0))
 for position in snackbody:#画出蛇的身体和食物
  rect2=pygame.Rect(position[0],position[1],20,20)
  pygame.draw.rect(screen,(166,188,199),rect2)
  rect1=pygame.Rect(foodposition[0],foodposition[1],20,20)
  pygame.draw.rect(screen,(169,111,102),rect1)
 screen.blit(font.render('Score:'+str(score),-1,(255,255,255)),(100,50))#显示出得分
 pygame.display.update()
 #如果蛇撞到墙或自己的身体,则游戏结束
 if snackhead[0]<0 or snackhead[0]>620:
  restart()
 if snackhead[1]<0 or snackhead[1]>620:
  restart()
 for body in snackbody[1:]:
  if body[0]==snackhead[0]and body[1]==snackhead[1]:
  restart() 
 
 pygame.display.flip()
 pygame.display.update()
 if pygame.mixer.music.get_busy()==False:
  pygame.mixer.music.set_volume(0.3)
  pygame.mixer.music.play(-1)#音乐循环
 
def restart():#重新开始按钮
  
 getResult()#显示结果
 while True:
 for event in pygame.event.get():

  if event.type == pygame.QUIT:
  pygame.quit()
  sys.exit()
  
  button.isrepress()
  pygame.display.update()
  if button.ifrepress():
  pygame.display.update()
  if pygame.mouse.get_pressed()[0]:
   main()

main()

按钮图片如下,可以自己画图做,音乐最好用ogg格式的,否则可能出问题。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持猪先飞。

[!--infotagslink--]

相关文章

  • python opencv 画外接矩形框的完整代码

    这篇文章主要介绍了python-opencv-画外接矩形框的实例代码,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-04
  • Python astype(np.float)函数使用方法解析

    这篇文章主要介绍了Python astype(np.float)函数使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-06-08
  • 最炫Python烟花代码全解析

    2022虎年新年即将来临,小编为大家带来了一个利用Python编写的虎年烟花特效,堪称全网最绚烂,文中的示例代码简洁易懂,感兴趣的同学可以动手试一试...2022-02-14
  • python中numpy.empty()函数实例讲解

    在本篇文章里小编给大家分享的是一篇关于python中numpy.empty()函数实例讲解内容,对此有兴趣的朋友们可以学习下。...2021-02-06
  • Python 图片转数组,二进制互转操作

    这篇文章主要介绍了Python 图片转数组,二进制互转操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-09
  • python-for x in range的用法(注意要点、细节)

    这篇文章主要介绍了python-for x in range的用法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-05-10
  • Python中的imread()函数用法说明

    这篇文章主要介绍了Python中的imread()函数用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-16
  • python实现b站直播自动发送弹幕功能

    这篇文章主要介绍了python如何实现b站直播自动发送弹幕,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下...2021-02-20
  • python Matplotlib基础--如何添加文本和标注

    这篇文章主要介绍了python Matplotlib基础--如何添加文本和标注,帮助大家更好的利用Matplotlib绘制图表,感兴趣的朋友可以了解下...2021-01-26
  • 解决python 使用openpyxl读写大文件的坑

    这篇文章主要介绍了解决python 使用openpyxl读写大文件的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-13
  • python 计算方位角实例(根据两点的坐标计算)

    今天小编就为大家分享一篇python 计算方位角实例(根据两点的坐标计算),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-04-27
  • python实现双色球随机选号

    这篇文章主要为大家详细介绍了python实现双色球随机选号,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-05-02
  • python中使用np.delete()的实例方法

    在本篇文章里小编给大家整理的是一篇关于python中使用np.delete()的实例方法,对此有兴趣的朋友们可以学习参考下。...2021-02-01
  • 使用Python的pencolor函数实现渐变色功能

    这篇文章主要介绍了使用Python的pencolor函数实现渐变色功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-03-09
  • python自动化办公操作PPT的实现

    这篇文章主要介绍了python自动化办公操作PPT的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-05
  • Python getsizeof()和getsize()区分详解

    这篇文章主要介绍了Python getsizeof()和getsize()区分详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-20
  • PyTorch一小时掌握之迁移学习篇

    这篇文章主要介绍了PyTorch一小时掌握之迁移学习篇,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-08
  • python实现学生通讯录管理系统

    这篇文章主要为大家详细介绍了python实现学生通讯录管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-25
  • 解决python 两个时间戳相减出现结果错误的问题

    这篇文章主要介绍了解决python 两个时间戳相减出现结果错误的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-12
  • Python绘制的爱心树与表白代码(完整代码)

    这篇文章主要介绍了Python绘制的爱心树与表白代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-04-06