基本信息
源码名称:python实现贪吃蛇小游戏(面向对象)
源码大小:4.58KB
文件格式:.zip
开发语言:Python
更新时间:2020-04-20
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 6 元×
微信扫码支付:6 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
用python(面向对象)的方法实现贪吃蛇小游戏
python 3 ,pygame 2.0
from snakeclass import snake from snakeblockclass import snakeblock import pygame from libs import color import sys from foodclass import food import threading from snakeblockclass import snakeblock class game: gamewindowwidth=1000 gamewindowheight=500 gamecaption="" #标题 gameclock=None gamescreen=None gamespeed=4 #刷新4/s 数值越大 刷新率越高 #gameblock=snakeblock(gamescreen) #小方块对象 gamesnake=None gamefood=None def initgame(self): #需要一次性处理的东西 pygame.init() #pygame必须要引入的一句话 self.gameclock = pygame.time.Clock() #设置时钟 #设置运行窗口 一个参数 self.gamescreen = pygame.display.set_mode((self.gamewindowwidth, self.gamewindowheight))#画布 self.gamecaption="贪吃蛇游戏1.0" #self.gameevent=event.EVENT_NONE #self.gameclock = snakeblock(self.gamescreen) # 触发构造函数 要给出参数 #设置标题 pygame.display.set_caption(self.gamecaption)#设置标题 self.gamesnake=snake(self.gamescreen) self.gamefood=food(self.gamescreen) self.gamefood.randfood() def rungame(self): #进行初始化 self.initgame() #进行刷新 while True: self.gamescreen.fill(color.whilte) #屏幕背景 重新画成白色的 将原来的覆盖 清屏 #self.gamesnake.initsnake() self.gamesnake.move() self.gamesnake.showsnake() #显示蛇 self.gamefood.showfood() #显示食物 self.eatfood() #调用吃蛇 # self.gameblock.move(self.gameblock.snakeblocklocationx self.gameblock.snakeblocksize,self.gameblock.snakeblocklocationy) pygame.display.update() # 刷新屏幕 遇到这句话 才会更新显示器 否则只在内存 上不到屏幕 self.gameclock.tick(self.gamespeed) # 定时刷新 相当于暂停1/4秒 相当于sleep 时钟周期 #监听 for event in pygame.event.get(): if event.type == pygame.QUIT: self.gameover() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.gameover() if event.key == pygame.K_LEFT: self.gamesnake.changedirection("left") if event.key == pygame.K_RIGHT: self.gamesnake.changedirection("right") if event.key == pygame.K_UP: self.gamesnake.changedirection("up") if event.key == pygame.K_DOWN: self.gamesnake.changedirection("down") def iseatfood(self): #代码变短 比较清楚 if self.gamesnake.snakebody[0].snakeblocklocationx != self.gamefood.foodlocationx : return False if self.gamesnake.snakebody[0].snakeblocklocationy != self.gamefood.foodlocationy : return False return True def eatfood(self): #先写最简单的 反向思维 先排除 用 if-return if self.iseatfood() == False: return None self.gamesnake.eatfood() #吃食物 self.gamefood.randfood() #刷新食物 def gameover(self): pygame.quit() sys.exit()