当前位置: 首页 > 后端技术 > Python

每天用Python写一个爽跑

时间:2023-03-26 18:38:56 Python

感觉上次写的植物大战僵尸和俄罗斯方块反响还不错。这一次,这篇文章更有动力。这一次,我会每天写一篇酷跑。写的效果图是这样的。让我们更新所有代码或者定义`importpygame,sysimportrandom`*1*2并编写游戏配置`width=1200#Windowwidthheight=508#Windowheightsize=width,heightscore=None#ScoremyFont=myFont1=None#FontsurObject=None#ObstacleimagesurGameOver=None#Gameendimagebg=None#Backgroundobjectrole=None#Characterobjectobject=None#ObstacleobjectobjectList=[]#Obstacleobject数组clock=None#ClockgameState=None#游戏状态(0,1)表示(游戏中,游戏结束)`*1*2*3*4*5*6*7*8*9*10*11*12*13写角色`classRole:#字符def__init__(self,surface=None,y=None):self.surface=surfaceself.y=yself.w=(surface.get_width())/12self.h=surface.get_height()/2self.currentFrame=-1self.state=0#0代表跑步状态,1代表跳跃状态,2代表连续跳跃self.g=1#重力加速度self.vy=0#y轴速度self.vy_start=-20#起步速度defgetRect(self):返回(0,self.y+12,self.w,self.h)`*1*2*3*4*5*6*7*8*9*10*11*12*13写障碍物`classObject:#障碍物def__init__(self,surface,x=0,y=0):self.surface=surfaceself.x=xself.y=yself.w=surface.get_width()self.h=surface.get_height()self.currentFrame=random.randint(0,6)self.w=100self.h=100defgetRect(self):return(self.x,self.y,self.w,self.h)defcollision(self,rect1,rect2):#撞击检测if(rect2[0]>=rect1[2]-20)or(rect1[0]+40>=rect2[2])or(rect1[1]+rect1[3]=508-85:role.y=508-85role.state=0#障碍物的移动addObject()forobjectinobjectList:object.x-=10#ObstacleMovement#障碍物超出屏幕,移除障碍物ifobject.x+object.w<=0:objectList.remove(object)score+=10#避开障碍物,加10分print("Atargetwasremoved")#碰撞检测ifobject.collision(role.getRect(),object.getRect()):if(object.currentFrame==6):objectList.remove(object)score+=100#吃金币加100分print(score)print("吃一枚金币")else:gameState=1#游戏失败print("发生碰撞!")`*1*2*3*4*5*6*7*8*9*10*11*12*13*14*15*16*17*18*19*20*21*22*23*24*25*26*27*28*29*30*31*32*33*34*35*36*37*38*39*40*41*42*43*44*45*46*47*48*49*50*51*52*53*54*55*56*57*58*59*60*61*62*63*64*65*66*67*68*69*70*71*72*73*74*75*76*77*78*79*80*81*82*83*84*85*86*87*88*89*90*91*92*93*94*95ok,这就是天天酷跑的全部代码,有问题可以留言,我看到会回复。