python字符型五子棋人工对战
时间: 2023-10-08 19:11:16 浏览: 105
好的,我可以为您提供一个简单的Python字符型五子棋人工对战的代码。该代码基于命令行界面,使用Python 3编写。
代码如下:
```python
class GobangGame:
def __init__(self):
self.board = [['+' for i in range(15)] for j in range(15)]
self.current_player = 'X'
def display_board(self):
print(" ", end="")
for i in range(15):
print(chr(ord('A')+i), end=" ")
print("\n")
for i in range(15):
print("{:2d} ".format(i+1), end="")
for j in range(15):
print(self.board[i][j], end=" ")
print("\n")
def get_input(self):
while True:
pos = input("请{}方落子,输入位置坐标(例如A1):".format(self.current_player))
if len(pos) == 2 and 'A' <= pos[0] <= 'O' and '1' <= pos[1] <= '9':
x = ord(pos[0]) - ord('A')
y = int(pos[1]) - 1
if self.board[y][x] == '+':
return (x, y)
print("输入有误,请重新输入。")
def is_win(self, x, y):
directions = [(1, 0), (0, 1), (1, 1), (1, -1)]
for dx, dy in directions:
count = 1
nx, ny = x+dx, y+dy
while 0 <= nx < 15 and 0 <= ny < 15 and self.board[ny][nx] == self.current_player:
count += 1
nx += dx
ny += dy
nx, ny = x-dx, y-dy
while 0 <= nx < 15 and 0 <= ny < 15 and self.board[ny][nx] == self.current_player:
count += 1
nx -= dx
ny -= dy
if count >= 5:
return True
return False
def play(self):
while True:
self.display_board()
x, y = self.get_input()
self.board[y][x] = self.current_player
if self.is_win(x, y):
self.display_board()
print("{}方获胜!".format(self.current_player))
break
self.current_player = 'O' if self.current_player == 'X' else 'X'
if __name__ == '__main__':
game = GobangGame()
game.play()
```
代码使用了一个`GobangGame`类来表示五子棋游戏,包含了游戏的状态和操作。类中的`display_board`方法用于显示当前棋局状态,`get_input`方法用于获取玩家输入,`is_win`方法用于判断当前玩家是否胜利,`play`方法用于执行游戏流程。
您可以直接运行该代码,开始人机对战。在每个玩家轮流下棋时,输入位置坐标(例如A1)即可。当有一方获胜时,游戏结束,显示获胜方。
阅读全文