python五子棋人机对战
时间: 2023-09-02 17:14:00 浏览: 71
好的,下面是一个简单的Python五子棋人机对战程序:
```python
import random
class Board:
def __init__(self):
self.board = [[' ' for i in range(15)] for j in range(15)]
self.player = 'X'
self.computer = 'O'
def show(self):
print(" ", end='')
for i in range(15):
print(" " + str(i + 1) + " ", end='')
print("")
for i in range(15):
print(str(i + 1) + " ", end='')
for j in range(15):
print(self.board[i][j] + " |", end='')
print("")
print(" ---" * 15)
def has_winner(self, player):
for i in range(15):
for j in range(11):
if self.board[i][j] == self.board[i][j + 1] == self.board[i][j + 2] == self.board[i][j + 3] == self.board[i][j + 4] == player:
return True
for i in range(11):
for j in range(15):
if self.board[i][j] == self.board[i + 1][j] == self.board[i + 2][j] == self.board[i + 3][j] == self.board[i + 4][j] == player:
return True
for i in range(11):
for j in range(11):
if self.board[i][j] == self.board[i + 1][j + 1] == self.board[i + 2][j + 2] == self.board[i + 3][j + 3] == self.board[i + 4][j + 4] == player:
return True
if self.board[i][j + 4] == self.board[i + 1][j + 3] == self.board[i + 2][j + 2] == self.board[i + 3][j + 1] == self.board[i + 4][j] == player:
return True
return False
def get_winner(self):
if self.has_winner(self.player):
return self.player
elif self.has_winner(self.computer):
return self.computer
else:
return None
def get_legal_moves(self):
legal_moves = []
for i in range(15):
for j in range(15):
if self.board[i][j] == ' ':
legal_moves.append((i, j))
return legal_moves
def player_move(self, row, col):
if self.board[row][col] == ' ':
self.board[row][col] = self.player
return True
else:
return False
def computer_move(self):
legal_moves = self.get_legal_moves()
row, col = random.choice(legal_moves)
self.board[row][col] = self.computer
def game_over(self):
if self.get_winner() is not None:
return True
for i in range(15):
for j in range(15):
if self.board[i][j] == ' ':
return False
return True
def main():
board = Board()
while not board.game_over():
board.show()
if board.player == 'X':
while True:
row = int(input("Enter row number: ")) - 1
col = int(input("Enter column number: ")) - 1
if board.player_move(row, col):
break
else:
print("Illegal move, try again.")
else:
board.computer_move()
board.player, board.computer = board.computer, board.player
board.show()
winner = board.get_winner()
if winner is None:
print("It's a tie!")
else:
print(winner + " wins!")
if __name__ == '__main__':
main()
```
这个程序中,我们定义了一个`Board`类,它代表了五子棋棋盘。在类中,我们定义了一些方法来实现游戏逻辑:
- `show()`方法用于显示当前棋盘状态;
- `has_winner(player)`方法用于检查指定玩家是否获胜;
- `get_winner()`方法用于获取获胜方,如果没有获胜方则返回`None`;
- `get_legal_moves()`方法用于获取当前合法的落子位置;
- `player_move(row, col)`方法用于让玩家落子;
- `computer_move()`方法用于让电脑落子;
- `game_over()`方法用于检查游戏是否结束。
在`main()`函数中,我们创建一个`Board`对象,并在循环中交替让玩家和电脑落子,直到游戏结束。最后,我们打印出胜利者或者平局的结果。
你可以试着运行这个程序并和电脑对战,体验一下五子棋的乐趣。
阅读全文