python儿童学游戏编程知识点总结
python爬虫基本告一段落,琢磨搞点其他的,正好在网上看到一个帖子,一个外国13岁小朋友用python写的下棋程序,内容详细,也有意思,拿来练手。
13岁啊。。我这年纪还在敲dir啥的吧
想到原先玩跑跑卡丁车时看到欧酷有个4岁熊孩子玩的完美漂移录像,深受打击,从此退出车坛。。。
废话不多说,记录一下这几天的游戏编程折腾史
游戏规则:6*6的方格棋盘,两个人轮流点击棋盘画横线或竖线,谁成功围成一个格子,这个格子算作此人的积分。
游戏架构:客户端和服务端。
先来看下游戏准备工作,需要用到pygame这个python包。
下载小朋友准备的Resource文件,游戏用到的图片、声音啥的。
一下为BoxGame(客户端)和Server代码,已添加注释。
boxes.py
1importpygame
importmath fromPodSixNet.ConnectionimportConnectionListener,connection fromtimeimportsleep #客户端游戏类 classBoxesGame(ConnectionListener): definitSound(self): pygame.mixer.music.load("music.wav") self.winSound=pygame.mixer.Sound('win.wav') self.loseSound=pygame.mixer.Sound('lose.wav') self.placeSound=pygame.mixer.Sound('place.wav') pygame.mixer.music.play() #收到来自Server的action:close指令后调用下面方法 defNetwork_close(self,data): exit() defNetwork_yourturn(self,data): self.turn=data['torf'] defNetwork_startgame(self,data): self.running=True self.num=data["player"] self.gameid=data["gameid"] defNetwork_place(self,data): self.placeSound.play() x=data["x"] y=data["y"] hv=data["is_horizontal"] ifhv: self.boardh[y][x]=True else: self.boardv[y][x]=True #设定某个格子为自己的 defNetwork_win(self,data): self.owner[data["x"]][data["y"]]="win" self.boardh[data["y"]][data["x"]]=True self.boardv[data["y"]][data["x"]]=True self.boardh[data["y"]+1][data["x"]]=True self.boardv[data["y"]][data["x"]+1]=True self.winSound.play() self.me+=1 defNetwork_lose(self,data): self.owner[data["x"]][data["y"]]="lose" self.boardh[data["y"]][data["x"]]=True self.boardv[data["y"]][data["x"]]=True self.boardh[data["y"]+1][data["x"]]=True self.boardv[data["y"]][data["x"]+1]=True self.loseSound.play() self.otherplayer+=1 def__init__(self): self.justplaced=10 pygame.init() pygame.font.init() width,height=389,489 self.me=0 self.otherplayer=0 self.didwin=False self.gameid=None self.num=None self.num=0 self.screen=pygame.display.set_mode((width,height)) self.owner=[[0forxinrange(6)]foryinrange(6)] self.clock=pygame.time.Clock() self.turn=True self.running=False self.boardh=[[Falseforxinrange(6)]foryinrange(7)] self.boardv=[[Falseforxinrange(7)]foryinrange(6)] print(self.boardh) print(self.boardv) self.initGraphics() self.initSound() self.drawHUD() pygame.display.set_caption("Boxes") #address=raw_input("Host:Port(localhost:8080):") #try: #ifnotaddress: #host,port="localhost",3721 #else: #host,port=address.split(":") #self.Connect((host,port)) #except: #print("ErrorConnectingtoServer") #print("Usage:host:port") #print("eg127.0.0.1;3721") #exit() self.Connect() print("Boxesclientstarted") whilenotself.running: self.Pump() connection.Pump() self.running=True sleep(0.01) print("notrunning,connecting...") ifself.num==0: #self.turn=True self.marker=self.greenplayer self.othermarker=self.blueplayer else: self.turn=False self.marker=self.blueplayer self.othermarker=self.greenplayer definitGraphics(self): self.normallinev=pygame.image.load("normalline.png") self.normallineh=pygame.transform.rotate(self.normallinev,-90) self.bar_donev=pygame.image.load("bar_done.png") self.bar_doneh=pygame.transform.rotate(self.bar_donev,-90) self.hoverlinev=pygame.image.load("hoverline.png") self.hoverlineh=pygame.transform.rotate(self.hoverlinev,-90) #self.boardh[5][4]=True #self.boardv[5][5]=True self.separators=pygame.image.load("separators.png") self.score_panel=pygame.image.load("score_panel.png") self.redindicator=pygame.image.load("redindicator.png") self.greenindicator=pygame.image.load("greenindicator.png") self.greenplayer=pygame.image.load("greenplayer.png") self.blueplayer=pygame.image.load("blueplayer.png") self.winningscreen=pygame.image.load("youwin.png") self.gameover=pygame.image.load("gameover.png") defdrawBoard(self): forxinrange(6): foryinrange(7): ifnotself.boardh[y][x]: self.screen.blit(self.normallineh,[(x)*64+5,(y)*64]) else: self.screen.blit(self.bar_doneh,[(x)*64+5,(y)*64]) forxinrange(7): foryinrange(6): ifnotself.boardv[y][x]: self.screen.blit(self.normallinev,[(x)*64,(y)*64+5]) else: self.screen.blit(self.bar_donev,[(x)*64,(y)*64+5]) defupdate(self): #判断方格是否已经都有归属 ifself.me+self.otherplayer==36: self.didwin=Trueifself.me>self.otherplayerelseFalse return1 self.justplaced-=1 #print('pumpconnectinfo') connection.Pump() self.Pump() #print('pumpconnectinfofinish') self.clock.tick(60) self.screen.fill(0) self.drawBoard() self.drawHUD() self.drawOwnermap() foreventinpygame.event.get(): ifevent.type==pygame.QUIT: exit() mouse=pygame.mouse.get_pos() xpos=int(math.ceil((mouse[0]-32)/64.0)) ypos=int(math.ceil((mouse[1]-32)/64.0)) #判断鼠标位置更接近与那条线 is_horizontal=abs(mouse[1]-ypos*64)server.py
1__author__='Administrator'
importPodSixNet.Channel importPodSixNet.Server fromtimeimportsleep #定义客户端通道,继承PodSixNet.Channel.Channel classClientChannel(PodSixNet.Channel.Channel): defNetwork(self,data): printdata defNetwork_place(self,data): hv=data["is_horizontal"] x=data["x"] y=data["y"] #客户标号 num=data["num"] #本游戏id self.gameid=data["gameid"] self._server.placeLine(hv,x,y,data,self.gameid,num) defClose(self): self._server.close(self.gameid) #定义游戏服务端 classBoxesServer(PodSixNet.Server.Server): channelClass=ClientChannel def__init__(self,*args,**kwargs): PodSixNet.Server.Server.__init__(self,*args,**kwargs) self.games=[] self.queue=None self.currentIndex=0 defConnected(self,channel,addr): print'newconnection:',channel #如果队列为空,则新建一局game ifself.queue==None: self.currentIndex+=1 channel.gameid=self.currentIndex self.queue=Game(channel,self.currentIndex) #如果队列中已有一局game在等待,则将新连进来的channel作为第二名游戏者与等待游戏者配对,加入games[]列表,将queue清空 else: channel.gameid=self.currentIndex self.queue.player1=channel self.queue.player0.Send({"action":"startgame","player":0,"gameid":self.queue.gameid}) self.queue.player1.Send({"action":"startgame","player":1,"gameid":self.queue.gameid}) self.games.append(self.queue) self.queue=None #defplaceLine(self,is_h,x,y,data,gameid,num): #ifnum==self.turn: #self.turn=0ifself.turnelse1 #self.player1.Send({"action":"yourturn","torf":Trueifself.turn==1elseFalse}) #self.player0.Send({"action":"yourturn","torf":Trueifself.turn==0elseFalse}) #ifis_h: #self.boardh[y][x]=True #else: #self.boardv[y][x]=True #self.player0.Send(data) #self.player1.Send(data) #通知GameServer哪句游戏要划线,调用游戏placeLine defplaceLine(self,is_h,x,y,data,gameid,num): game=[aforainself.gamesifgameid==a.gameid] iflen(game)==1: game[0].placeLine(is_h,x,y,data,num) #关闭某局game defclose(self,gameid): try: game=[aforainself.gamesifa.gameid==gameid][0] game.player0.Send({"action":"close"}) game.player1.Send({"action":"close"}) except: pass #判断方格归属 deftick(self): index=0 #状态未改变code3 change=3 #扫描每局游戏 forgameinself.games: change=3 #扫描2次,因为存在放置一个线条完成两个方格占领的情况 fortimeinrange(2): foryinrange(6): forxinrange(6): #判断是否是新围成的方格 ifgame.boardh[y][x]andgame.boardv[y][x]andgame.boardh[y+1][x]andgame.boardv[y][x+1]andnotgame.owner[x][y]: #是否为己方围成的,围成的一方可以继续走一步 #此处self.games[index]能否替换为game? ifself.games[index].turn==0: self.games[index].owner[x][y]=2 game.player1.Send({"action":"win","x":x,"y":y}) game.player0.Send({"action":"lose","x":x,"y":y}) change=1 print("player1win1grid") else: self.games[index].owner[x][y]=1 game.player0.Send({"action":"win","x":x,"y":y}) game.player1.Send({"action":"lose","x":x,"y":y}) change=0 print("player0win1grid") #如果状态改变了(即有一方完成了方格占领)则下一步仍由该方走棋;否则正常交替走棋 self.games[index].turn=changeifchange!=3elseself.games[index].turn game.player1.Send({"action":"yourturn","torf":Trueifself.games[index].turn==1elseFalse}) game.player0.Send({"action":"yourturn","torf":Trueifself.games[index].turn==0elseFalse}) index+=1 self.Pump() #单纯一局游戏的控制类 classGame: def__init__(self,player0,currentIndex): self.turn=0 self.owner=[[Falseforxinrange(6)]foryinrange(6)] self.boardh=[[Falseforxinrange(6)]foryinrange(7)] self.boardv=[[Falseforxinrange(7)]foryinrange(6)] self.player0=player0 self.player1=None self.gameid=currentIndex #whilenotself.running: #self.Pump() #connection.Pump() #sleep(0.01) #ifself.num==0: #self.turn=True #self.marker=self.greenplayer #self.othermarker=self.blueplayer #else: #self.turn=False #self.marker=self.blueplayer #self.othermarker=self.greenplayer #划线 defplaceLine(self,is_h,x,y,data,num): ifnum==self.turn: self.turn=0ifself.turnelse1 self.player1.Send({"action":"yourturn","torf":Trueifself.turn==1elseFalse}) self.player0.Send({"action":"yourturn","torf":Trueifself.turn==0elseFalse}) ifis_h: self.boardh[y][x]=True else: self.boardv[y][x]=True self.player0.Send(data) self.player1.Send(data) #defNetwork_palce(self,data): #x=data["x"] #y=data["y"] #hv=data["is_horizontal"] #ifhv: #self.boardh[y][x]=True #else: #self.boardv[y][x]=True print"Staringserveronlocalhost" address=raw_input("Host:Port(localhost:8080):") ifnotaddress: host,port="localhost",31425 print("defaulthostandport") print(host,":",port) else: host,port=address.split(":") print(host,":",port) boxesServer=BoxesServer(localaddr=("127.0.0.1",31425)) #boxesServer=BoxesServer() whileTrue: boxesServer.Pump() boxesServer.tick() sleep(0.01)就是这样,休息,休息一下。以上就是本次介绍的儿童学习python游戏编程的全部知识点内容,感谢大家对毛票票的支持。