写一个人机对战的简易五子棋python代码
时间: 2023-10-11 18:07:11 浏览: 93
以下是一个简单的五子棋Python代码,可以实现人机对战:
```python
import random
# 棋盘大小
SIZE = 15
# 下棋标记
PLAYER = 1
COMPUTER = 2
# 初始化棋盘
board = [[0 for x in range(SIZE)] for y in range(SIZE)]
# 绘制棋盘
def print_board(board):
print(" ", end="")
for i in range(SIZE):
print(i, end="")
print()
for i in range(SIZE):
print(i, end="")
for j in range(SIZE):
if board[i][j] == PLAYER:
print("X", end="")
elif board[i][j] == COMPUTER:
print("O", end="")
else:
print(".", end="")
print()
# 检查是否有五个连续的棋子
def check_win(board, player):
# 横向检查
for i in range(SIZE):
for j in range(SIZE-4):
if board[i][j] == player and board[i][j+1] == player and board[i][j+2] == player and board[i][j+3] == player and board[i][j+4] == player:
return True
# 纵向检查
for i in range(SIZE-4):
for j in range(SIZE):
if board[i][j] == player and board[i+1][j] == player and board[i+2][j] == player and board[i+3][j] == player and board[i+4][j] == player:
return True
# 左上-右下斜向检查
for i in range(SIZE-4):
for j in range(SIZE-4):
if board[i][j] == player and board[i+1][j+1] == player and board[i+2][j+2] == player and board[i+3][j+3] == player and board[i+4][j+4] == player:
return True
# 右上-左下斜向检查
for i in range(SIZE-4):
for j in range(4, SIZE):
if board[i][j] == player and board[i+1][j-1] == player and board[i+2][j-2] == player and board[i+3][j-3] == player and board[i+4][j-4] == player:
return True
return False
# 人下棋
def player_move(board):
while True:
x = int(input("请输入行号(0-14):"))
y = int(input("请输入列号(0-14):"))
if board[x][y] == 0:
board[x][y] = PLAYER
break
else:
print("该位置已经有棋子,请重新输入。")
# 电脑下棋
def computer_move(board):
while True:
x = random.randint(0, SIZE-1)
y = random.randint(0, SIZE-1)
if board[x][y] == 0:
board[x][y] = COMPUTER
break
# 主函数
def main():
print_board(board)
while True:
player_move(board)
print_board(board)
if check_win(board, PLAYER):
print("恭喜你,你赢了!")
break
computer_move(board)
print_board(board)
if check_win(board, COMPUTER):
print("很遗憾,你输了!")
break
if __name__ == '__main__':
main()
```
这个代码使用了随机算法来实现电脑下棋,因此电脑的棋力相对较弱,可以根据需要自行优化算法。
阅读全文