- ホスト側だとホームディレクトリのnotebooks/easyAI/Connectxディレクトリに以下の内容で作成
- Connect X の処理を行うクラス
- BWIDTHで盤の幅
- BHEIGHTで盤の高さ
- NEEDLENで勝利条件の長さ(4なら4個以上同じ陣営のコマを縦横あるいは斜めに連続で並べたら勝ち)
BWIDTH=7 # board width
BHEIGHT=6 # board height
NEEDLEN=4 # How many must be arranged to win
class Connectx(object):
def __init__(self):
self.color=[[2] * BWIDTH for i in range(BHEIGHT)]
self.v=[" O "," X "," . "]
self.turn=0
self.history=[]
self.isEnd=False
self.winner=2
def clear(self, stone=True):
self.color=[[2] * BWIDTH for i in range(BHEIGHT)]
self.turn=0
self.history.clear()
self.isEnd=False
self.winner=2
def showboard(self):
print(" ",end="")
for x in range(BWIDTH):
print("{0:2d}".format(x),end=" ")
print()
for y in range(BHEIGHT):
print("{0:2d}".format(y)+" | ",end="")
for x in range(BWIDTH):
c=self.color[y][x]
print(self.v[c] ,end="")
print(" | "+"{0:2d}".format(y))
print(" ",end="")
for x in range(BWIDTH):
print("{0:2d}".format(x),end=" ")
print()
print("isEnd : "+str(self.isEnd))
if self.isEnd:
print("game is over winner is "+str(self.winner))
print(self.history)
print()
def legal(self, v):
ans=False
if self.color[0][v]==2:
ans=True
return ans
def isValidXY(self ,xy):
v,y=xy
return (v>=0 and v<BWIDTH and y>=0 and y<BHEIGHT)
def getColor(self,xy):
ans=3
if self.isValidXY(xy):
v,y=xy
ans=self.color[y][v]
return ans
def check(self):
ans=False
for x in range(BWIDTH):
if ans:
break
for y in reversed(range(BHEIGHT)):
if ans:
break
c=self.color[y][x]
if c<2:
#print(">>>***************",end="")
#print((x,y))
if self.bcheck((x,y)):
ans=True
break
return ans
def bcheck(self,xy):
x,y=xy
ans=False
c=self.color[y][x]
if c<2:
for dx in [1,0,-1]:
for dy in [1,0,-1]:
#print("*****(dx,dy)",end=" ")
#print((dx,dy))
if (not (dx==0 and dy==0)) and (not ans):
c1=1
for i in range(1,NEEDLEN):
nx=x+dx*i
ny=y+dy*i
#print("(nx,ny)",end=" ")
#print((nx,ny))
if self.isValidXY((nx,ny)):
nc=self.getColor((nx,ny))
if nc==c:
#print((nx,ny),end=" ")
c1+=1
#print(c1)
if c1>=NEEDLEN:
#print("*** TRUE")
ans=True
break
else:
break
return ans
def getEnableVs(self):
ans=[]
for i in range(BWIDTH):
if self.color[0][i]==2:
ans.append(i)
return ans
def checkEnd(self):
evs=self.getEnableVs()
ans=len(evs)>0 or self.isEnd
if ans:
self.isEnd=True
return ans
def play(self,v):
ans=False
if self.legal(v):
ans=True
for y in reversed(range(BHEIGHT)):
if self.color[y][v]==2:
self.color[y][v]=self.turn
self.history.append([v,y])
#print(self.check())
if not self.isEnd:
if self.check():
self.isEnd=True
self.winner=self.turn
# print("game is over winner is "+str(self.winner))
# print(self.history)
self.turn=int(self.turn==0)
break
return ans
def unmake_move(self, move): # optional method (speeds up the AI)
if len(self.history)>0:
x,y=self.history[-1]
self.color[y][x]=2
#for i in range(BHEIGHT):
# if self.color[y][i]<2:
# self.color[y][i]=2
# break
self.history=self.history[:-1]
self.turn=int(self.turn==0)
self.isEnd=False
self.winner=2