使用pygame模块编写贪吃蛇的实例讲解
python###刚学了python不久,发现了一个好玩的库pygame
使用pygame模块利用面向对象的思想编写贪吃蛇,主要用到pygame.sprite:
游戏主类
importpygame,sys fromsnake_spriteimportGame_sprite,Snake,Food SCREEN_RECT=pygame.Rect(0,0,828,600) IMG_URL="./image/bg.jpg" #主类 classSnakegame(object): def__init__(self): self.screen=pygame.display.set_mode(SCREEN_RECT.size) self.clock=pygame.time.Clock() self.__create_sprites() def__create_sprites(self): bg=Game_sprite(IMG_URL) self.snake=Snake() forposinself.snake.snake_point: self.screen.blit(self.snake.image,pos) food=Food() self.bg_group=pygame.sprite.Group(bg) self.snake_group=pygame.sprite.Group(self.snake) self.food_group=pygame.sprite.Group(food) defstart_game(self): whileTrue: #1.时钟设置 self.clock.tick(30) #2.事件监听 self.__event_handler() #3.碰撞检测 self.__check_collide() #4.精灵更新 self.__update_sprites() #5.屏幕更新 pygame.display.update() def__event_handler(self): foreventinpygame.event.get(): ifevent.type==pygame.QUIT: Snakegame.__game_over() elifevent.type==pygame.KEYDOWNandevent.key==pygame.K_RIGHTand\ self.snake.direction!='L': self.snake.speedy=0 self.snake.speedx=1 self.snake.direction='R' elifevent.type==pygame.KEYDOWNandevent.key==pygame.K_LEFTand\ self.snake.direction!='R': self.snake.speedy=0 self.snake.speedx=-1 self.snake.direction='L' elifevent.type==pygame.KEYDOWNandevent.key==pygame.K_UPand\ self.snake.direction!='D': self.snake.speedx=0 self.snake.speedy=-1 self.snake.direction='U' elifevent.type==pygame.KEYDOWNandevent.key==pygame.K_DOWNand\ self.snake.direction!='U': self.snake.speedx=0 self.snake.speedy=1 self.snake.direction='D' def__check_collide(self): pass def__update_sprites(self): self.bg_group.update() self.bg_group.draw(self.screen) self.snake_group.update() self.snake_group.draw(self.screen) self.food_group.update() self.food_group.draw(self.screen) @staticmethod def__game_over(): pygame.quit() exit() #游戏启动 if__name__=='__main__': snake=Snakegame() snake.start_game()
工具类
importpygame importrandom SNAKE_IMG="./image/snake.png" FOOD_IMG="./image/food.jpg" classGame_sprite(pygame.sprite.Sprite): def__init__(self,img_name,speedx=1,speedy=0): #调用父类的初始化方法 super(Game_sprite,self).__init__() #属性 self.image=pygame.image.load(img_name) self.rect=self.image.get_rect() self.speedx=speedx self.speedy=speedy defupdate(self): pass #蛇实物 classSnake(Game_sprite): def__init__(self,direction='R',snakelist=[[40,40],[80,40]]): self.direction=direction self.snake_point=snakelist super().__init__(SNAKE_IMG) self.rect.x=self.snake_point[1][0] self.rect.y=self.snake_point[1][1] defupdate(self): self.rect.x+=self.speedx self.rect.y+=self.speedy classFood(Game_sprite): def__init__(self): super(Food,self).__init__(FOOD_IMG) self.rect.x=random.randint(50,828) self.rect.y=random.randint(38,600) defupdate(self): pass
关于这次demo
我发现自己并没有弄懂pygame的具体画面更新机制,以及精灵的控制,对于贪吃蛇头部及身体的画面更新并没有做出来,还有对身体和头的数据结构如何构建并不是很了解。毕竟第一次,希望有大佬看到这篇博客能够指点下。
附上函数式编程的代码
importpygame importtime importrandom x=pygame.init() white=(255,255,255) black=(0,0,0) red=(255,0,0) green=(0,155,0) display_width=800 display_height=600 gameDisplay=pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption('Slither') gameDisplay.fill(white) pygame.display.update() block_size=20 applethickness=30 FPS=10 icon=pygame.image.load('appleimage.jpg') pygame.display.set_icon(icon) img=pygame.image.load('snakeimage.jpg') appleimage=pygame.image.load('appleimage.jpg') clock=pygame.time.Clock() smallfont=pygame.font.SysFont(None,30) midfont=pygame.font.SysFont(None,50) largefont=pygame.font.SysFont("comicsansms",80) direction="right" defpause(): paused=True message_to_screen("暂停",black,-100,"large") message_to_screen("空格暂停Q退出",black,30) pygame.display.update() whilepaused: foreventinpygame.event.get(): ifevent.type==pygame.QUIT: pygame.quit() quit() ifevent.type==pygame.KEYDOWN: ifevent.key==pygame.K_SPACE: paused=False elifevent.key==pygame.K_q: pygame.quit() quit() #gameDisplay.fill(white) clock.tick(5) defscore(score): text1=smallfont.render("Score:"+str(score),True,black) gameDisplay.blit(text1,(0,0)) defrandApplegen(): randAppleX=round(random.randrange(0,display_width-applethickness))#/10.0)*10.0 randAppleY=round(random.randrange(0,display_height-applethickness))#/10.0)*10.0 returnrandAppleX,randAppleY defintro(): intro=True message_to_screen("按c开始游戏",red,150) pygame.display.update() whileintro: foreventinpygame.event.get(): ifevent.type==pygame.QUIT: pygame.quit() quit() ifevent.type==pygame.KEYDOWN: ifevent.key==pygame.K_c: intro=False ifevent.key==pygame.K_q: pygame.quit() quit() clock.tick(15) defsnake(snakelist): forxnyinsnakelist[:-1]: pygame.draw.rect(gameDisplay,green,[xny[0],xny[1],block_size,block_size]) if(direction=="right"): head=pygame.transform.rotate(img,270) elif(direction=="left"): head=pygame.transform.rotate(img,90) elif(direction=="up"): head=img elif(direction=="down"): head=pygame.transform.rotate(img,180) gameDisplay.blit(head,(snakelist[-1][0],snakelist[-1][1])) deftext_objects(text,color,size): if(size=="small"): textsurface=smallfont.render(text,True,color) elif(size=="middle"): textsurface=midfont.render(text,True,color) elif(size=="large"): textsurface=largefont.render(text,True,color) returntextsurface,textsurface.get_rect() defmessage_to_screen(msg,color,y_displace=0,size="small"): textsurf,textsurf_rect=text_objects(msg,color,size) textsurf_rect.center=(display_width/2),(display_height/2)+y_displace gameDisplay.blit(textsurf,textsurf_rect) defgameLoop(): globaldirection direction="right" gameExit=False gameOver=False lead_x=display_width/2 lead_y=display_height/2 lead_x_change=10 lead_y_change=0 randAppleX,randAppleY=randApplegen() snakelist=[] snakelength=1 whilenotgameExit: ifgameOver==True: message_to_screen("GameOver",red,-50,"large") message_to_screen("PressCtoplayagainorQtoquitthegame",black,50,"small") pygame.display.update() whilegameOver==True: #gameDisplay.fill(white) foreventinpygame.event.get(): ifevent.type==pygame.KEYDOWN: ifevent.key==pygame.K_q: gameExit=True gameOver=False ifevent.key==pygame.K_c: gameLoop() pygame.quit() quit() ifevent.type==pygame.QUIT: gameExit=True gameOver=False #pygame.quit() #quit() foreventinpygame.event.get(): ifevent.type==pygame.QUIT: gameExit=True ifevent.type==pygame.KEYDOWN: ifevent.key==pygame.K_LEFTanddirection!="right": direction="left" lead_x_change=-block_size lead_y_change=0 elifevent.key==pygame.K_RIGHTanddirection!="left": direction="right" lead_x_change=block_size lead_y_change=0 elifevent.key==pygame.K_UPanddirection!="down": direction="up" lead_y_change=-block_size lead_x_change=0 elifevent.key==pygame.K_DOWNanddirection!="up": direction="down" lead_y_change=block_size lead_x_change=0 elifevent.key==pygame.K_SPACE: pause() iflead_x+block_size/2>=display_widthorlead_x<0orlead_y+block_size/2>=display_heightorlead_y<0: gameOver=True lead_x+=lead_x_change lead_y+=lead_y_change gameDisplay.fill(white) gameDisplay.blit(appleimage,(randAppleX,randAppleY)) #pygame.draw.rect(gameDisplay,red,[350,350,100,10]) #gameDisplay.fill(red,rect=[200,200,50,50])#goodmethod snakehead=[] snakehead.append(lead_x) snakehead.append(lead_y) snakelist.append(snakehead) iflen(snakelist)>snakelength: delsnakelist[0] foreachinsnakelist[:-1]: ifeach==snakehead: gameOver=True snake(snakelist) score(snakelength-1) pygame.display.update() iflead_x>=randAppleXandlead_x<=randAppleX+applethicknessorlead_x+block_size>=randAppleXandlead_x+block_size<=randAppleX+applethickness: iflead_y>=randAppleYandlead_y<=randAppleY+applethicknessorlead_y+block_size>=randAppleYandlead_y+block_size<=randAppleY+applethickness: randAppleX,randAppleY=randApplegen() snakelength+=1; clock.tick(FPS) intro() gameLoop() pygame.quit() quit()
以上这篇使用pygame模块编写贪吃蛇的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。