class Game:
def __init__(self, h, w):
# 行数
self.h = h
# 列数
self.w = w
# 棋盘
self.L = [['-' for _ in range(w)] for _ in range(h)]
# 当前玩家 - 表示空 X先下 然后是O
self.cur = 'X'
# 游戏胜利者
self.win_user = None
# 检查下完这步后有没有赢 y是行 x是列 返回True表示赢
def check_win(self, y, x):
directions = [
# 水平、垂直、两个对角线方向
(1, 0), (0, 1), (1, 1), (1, -1)
]
player = self.L[y][x]
for dy, dx in directions:
count = 0
# 检查四个方向上的连续相同棋子
for i in range(-4, 5): # 检查-4到4的范围,因为五子连珠需要5个棋子
ny, nx = y + i * dy, x + i * dx
if 0 <= ny < self.h and 0 <= nx < self.w and self.L[ny][nx] == player:
count += 1
if count == 5:
return True
else:
count = 0
return False
# 检查能不能下这里 y行 x列 返回True表示能下
def check(self, y, x):
return self.L[y][x] == '-' and self.win_user is None
# 打印棋盘 可视化用得到
def __str__(self):
# 确定行号和列号的宽度
row_width = len(str(self.h - 1))
col_width = len(str(self.w - 1))
# 生成带有行号和列号的棋盘字符串表示
result = []
# 添加列号标题
result.append(' ' * (row_width + 1) + ' '.join(f'{i:>{col_width}}' for i in range(self.w)))
# 添加分隔线(可选)
result.append(' ' * (row_width + 1) + '-' * (col_width * self.w))
# 添加棋盘行
for y, row in enumerate(self.L):
# 添加行号
result.append(f'{y:>{row_width}} ' + ' '.join(f'{cell:>{col_width}}' for cell in row))
return '\n'.join(result)
# 一步棋
def set(self, y, x):
if self.win_user or not self.check(y, x):
return False
self.L[y][x] = self.cur
if self.check_win(y, x):
self.win_user = self.cur
return True
self.cur = 'X' if self.cur == 'O' else 'O'
return True
def run_game01():
g = Game(10, 10)
while not g.win_user:
# 打印当前棋盘状态
while 1:
print(g)
try:
y,x=input(g.cur+':').split(',')
x=int(x)
y=int(y)
if g.set(y,x):
break
except Exception as e:
print(e)
print(g)
print('胜利者',g.win_user)
if __name__ == "__main__":
run_game01()