您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關python如何實現棋盤游戲的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
游戲規則:6*6的方格棋盤,兩個人輪流點擊棋盤畫橫線或豎線,誰成功圍成一個格子,這個格子算作此人的積分。
游戲架構:客戶端和服務端。
先來看下游戲準備工作,需要用到pygame這個python包。
下載小朋友準備的Resource文件,游戲用到的圖片、聲音啥的。
一下為BoxGame(客戶端)和Server代碼,已添加注釋。
boxes.py
1 import pygame
import math from PodSixNet.Connection import ConnectionListener,connection from time import sleep # 客戶端游戲類 class BoxesGame(ConnectionListener): def initSound(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指令后調用下面方法 def Network_close(self,data): exit() def Network_yourturn(self,data): self.turn=data['torf'] def Network_startgame(self,data): self.running=True self.num=data["player"] self.gameid=data["gameid"] def Network_place(self,data): self.placeSound.play() x=data["x"] y=data["y"] hv=data["is_horizontal"] if hv: self.boardh[y][x]=True else: self.boardv[y][x]=True # 設定某個格子為自己的 def Network_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 def Network_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=[[0 for x in range(6)] for y in range(6)] self.clock = pygame.time.Clock() self.turn = True self.running=False self.boardh = [[False for x in range(6)] for y in range(7)] self.boardv = [[False for x in range(7)] for y in range(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: # if not address: # host,port="localhost",3721 # else: # host,port=address.split(":") # self.Connect((host,port)) # except: # print("Error Connecting to Server") # print("Usage: host:port") # print("eg 127.0.0.1;3721") # exit() self.Connect() print("Boxes client started") while not self.running: self.Pump() connection.Pump() self.running=True sleep(0.01) print("not running ,connecting...") if self.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 def initGraphics(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") def drawBoard(self): for x in range(6): for y in range(7): if not self.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]) for x in range(7): for y in range(6): if not self.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]) def update(self): # 判斷方格是否已經都有歸屬 if self.me+self.otherplayer==36: self.didwin=True if self.me>self.otherplayer else False return 1 self.justplaced-=1 # print('pump connect info') connection.Pump() self.Pump() # print('pump connect info finish') self.clock.tick(60) self.screen.fill(0) self.drawBoard() self.drawHUD() self.drawOwnermap() for event in pygame.event.get(): if event.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) < abs(mouse[0] - xpos * 64) ypos = ypos - 1 if mouse[1] - ypos * 64 < 0 and not is_horizontal else ypos xpos = xpos - 1 if mouse[0] - ypos * 64 < 0 and is_horizontal else xpos board = self.boardh if is_horizontal else self.boardv isoutofbounds = False try: if not board[ypos][xpos]: self.screen.blit(self.hoverlineh if is_horizontal else self.hoverlinev, [xpos * 64 + 5 if is_horizontal else xpos * 64, ypos * 64 if is_horizontal else ypos * 64 + 5]) except: isoutofbounds = True pass if not isoutofbounds: alreadyplaced = board[ypos][xpos] else: alreadyplaced = False # 鼠標點擊時,發送place信號給自己劃線 if pygame.mouse.get_pressed()[0] and not alreadyplaced and not isoutofbounds and self.turn==True and self.justplaced<=10: self.justplaced=10 if is_horizontal: self.boardh[ypos][xpos] = True self.Send({"action":"place","x":xpos,"y":ypos,"is_horizontal":is_horizontal,"gameid":self.gameid,"num":self.num}) else: self.boardv[ypos][xpos] = True self.Send({"action":"place","x":xpos,"y":ypos,"is_horizontal":is_horizontal,"gameid":self.gameid,"num":self.num}) pygame.display.flip() # 畫記分區域 def drawHUD(self): self.screen.blit(self.score_panel, [0, 389]) myfont = pygame.font.SysFont(None, 32) label = myfont.render("Your turn", 1, (255, 255, 255)) self.screen.blit(label, (10, 400)) self.screen.blit(self.greenindicator if self.turn else self.redindicator ,(130, 395)) myfont64 = pygame.font.SysFont(None, 64) myfont20 = pygame.font.SysFont(None, 20) scoreme = myfont64.render(str(self.me), 1, (255, 255, 255)) scoreother = myfont64.render(str(self.otherplayer), 1, (255, 255, 255)) scoretextme = myfont20.render("You", 1, (255, 255, 255)) scoretextother = myfont20.render("Other Player", 1, (255, 255, 255)) self.screen.blit(scoretextme, (10, 425)) self.screen.blit(scoreme, (10, 435)) self.screen.blit(scoretextother, (280, 425)) self.screen.blit(scoreother, (280, 435)) # 給占領與被占領格子著色 def drawOwnermap(self): for x in range(6): for y in range(6): if self.owner[x][y]!=0: if self.owner[x][y]=="win": self.screen.blit(self.marker,(x*64+5,y*64+5)) if self.owner[x][y]=="lose": self.screen.blit(self.othermarker,(x*64+5,y*64+5)) # 游戲結束后顯示gameover或winning的圖案 def finished(self): self.screen.blit(self.gameover if not self.didwin else self.winningscreen,(0,0)) while 1: for event in pygame.event.get(): if event.type==pygame.QUIT: exit() pygame.display.flip() bg = BoxesGame() while 1: if bg.update()==1: break bg.finished()
server.py
1 __author__ = 'Administrator'
import PodSixNet.Channel import PodSixNet.Server from time import sleep # 定義客戶端通道,繼承PodSixNet.Channel.Channel class ClientChannel(PodSixNet.Channel.Channel): def Network(self,data): print data def Network_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) def Close(self): self._server.close(self.gameid) # 定義游戲服務端 class BoxesServer (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 def Connected(self,channel,addr): print 'new connection:',channel # 如果隊列為空,則新建一局game if self.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 # def placeLine(self,is_h,x,y,data,gameid,num): # if num==self.turn: # self.turn=0 if self.turn else 1 # self.player1.Send({"action":"yourturn","torf":True if self.turn==1 else False}) # self.player0.Send({"action":"yourturn","torf":True if self.turn==0 else False}) # if is_h: # self.boardh[y][x]=True # else: # self.boardv[y][x]=True # self.player0.Send(data) # self.player1.Send(data) #通知GameServer哪句游戲要劃線,調用游戲placeLine def placeLine(self,is_h,x,y,data,gameid,num): game=[a for a in self.games if gameid==a.gameid] if len(game)==1: game[0].placeLine(is_h,x,y,data,num) # 關閉某局game def close(self,gameid): try: game=[a for a in self.games if a.gameid==gameid][0] game.player0.Send({"action":"close"}) game.player1.Send({"action":"close"}) except: pass # 判斷方格歸屬 def tick(self): index=0 # 狀態未改變 code 3 change=3 # 掃描每局游戲 for game in self.games: change=3 # 掃描2次,因為存在放置一個線條完成兩個方格占領的情況 for time in range(2): for y in range(6): for x in range(6): # 判斷是否是新圍成的方格 if game.boardh[y][x] and game.boardv[y][x] and game.boardh[y+1][x] and game.boardv[y][x+1] and not game.owner[x][y]: # 是否為己方圍成的,圍成的一方可以繼續走一步 # 此處self.games[index]能否替換為game? if self.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("player1 win 1 grid") 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("player0 win 1 grid") # 如果狀態改變了(即有一方完成了方格占領)則下一步仍由該方走棋;否則正常交替走棋 self.games[index].turn=change if change!=3 else self.games[index].turn game.player1.Send({"action":"yourturn","torf":True if self.games[index].turn==1 else False}) game.player0.Send({"action":"yourturn","torf":True if self.games[index].turn==0 else False}) index+=1 self.Pump() # 單純一局游戲的控制類 class Game: def __init__(self,player0,currentIndex): self.turn=0 self.owner=[[False for x in range(6)] for y in range(6)] self.boardh=[[False for x in range(6)] for y in range(7)] self.boardv=[[False for x in range(7)] for y in range(6)] self.player0=player0 self.player1=None self.gameid=currentIndex # while not self.running: # self.Pump() # connection.Pump() # sleep(0.01) # if self.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 # 劃線 def placeLine(self,is_h,x,y,data,num): if num==self.turn: self.turn=0 if self.turn else 1 self.player1.Send({"action":"yourturn","torf":True if self.turn==1 else False}) self.player0.Send({"action":"yourturn","torf":True if self.turn==0 else False}) if is_h: self.boardh[y][x]=True else: self.boardv[y][x]=True self.player0.Send(data) self.player1.Send(data) # def Network_palce(self,data): # x=data["x"] # y=data["y"] # hv=data["is_horizontal"] # if hv: # self.boardh[y][x]=True # else: # self.boardv[y][x]=True print "Staring server on localhost" address=raw_input("Host:Port(localhost:8080):") if not address: host,port="localhost",31425 print("default host and port") print(host,":",port) else: host,port=address.split(":") print(host,":",port) boxesServer=BoxesServer( localaddr=("127.0.0.1", 31425)) # boxesServer=BoxesServer() while True: boxesServer.Pump() boxesServer.tick() sleep(0.01) 就是這樣,休息,休息一下。
感謝各位的閱讀!關于“python如何實現棋盤游戲”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。