python控制台簡單實現五子棋


 
        
#棋盤
#落子
#規則
import random
class chess:
def __init__(self):
print('#---------------棋盤----------------#')
self.grid = []
self.si = []
for i in range(8):
self.grid.append([' □ ']*8)
for j in range(8):
print(''.join(self.grid[j]),'\n') #''.join(grid[j]))

def getPos(self,x,y):
print('#----------------落子----------------#')
self.x = x
self.y = y
if self.grid[self.x][self.y]== ' ○ ' or self.grid[self.x][self.y]== ' ● ': # 判斷棋子是否重復
print('\t\t\t棋子有重復')
else:
self.l = 0
self.grid[self.x][self.y] = ' ● '
if self.x==7 or self.y==0 :
self.grid[random.randint(self.x-2,self.x-1)][random.randint(self.y-2,self.y-1)] = ' ○ '
else:

self.grid[self.x][self.y] = ' ● '
self.grid[self.x + 1][ self.y + 1] =' ○ '
self.si.append([self.x, self.y])
for i in range(len(self.si)):
if self.si[i-1][0] == self.si[i][0] or self.si[i-1][1] == self.si[i][1] or self.si[i][1]==self.si[i][0] and self.si[i-1][1]==self.si[i-1][0] and (self.grid[self.x-1][self.y] != ' □ ' or self.grid[self.x+1][self.y+1] != ' □ '
or self.grid[self.x-1][self.y-1] != ' □ '
or self.grid[self.x+1][self.y] != ' □ '
or self.grid[self.x-1][self.y] != ' □ '
or self.grid[self.x][self.y-1] != ' □ ' or self.grid[self.x][self.y+1] != ' □ '
or self.grid[self.x][self.y-1] != ' □ '): # 判斷玩家是否排成一條線
self.l += 1
for j in range(8):
print(''.join(self.grid[j])+'\n') #''.join(grid[j]))

def rulers(self):
recode = []
recode.append([self.x,self.y])
print(self.si)

for i in range(len(recode)):
for j in range(len(recode[i])):
if self.l==5: # 標記,當為5時結束游戲
print('游戲結束')
print('玩家勝利')
self.t = False
return self.t
elif len(self.si)>6: # 判斷平局,因為條件簡單,所以不會出現電腦贏的情況
print('游戲結束')
print('平局')
self.t = False
return self.t
else:
self.t = True
return self.t




play = chess()
t = True
while t: # 循環實現棋盤出現
x,y = input("\t請輸入x,y坐標用','分割:\n").split(',')
play.getPos(int(x),int(y))
t = play.rulers()

這只是簡單練習

小白一枚,AI訓練方式還未學習,后面會持續出更

繼續努力


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM