用Python写一个人机对战的五子棋小游戏,请给出代码
时间: 2024-05-15 09:16:58 浏览: 108
以下是一个简单的五子棋小游戏的Python代码:
```python
import random
board = [['+' for _ in range(15)] for _ in range(15)]
def print_board():
for row in board:
print(' '.join(row))
def check_win(player):
# 检查行
for row in board:
if ''.join(row).count(player*5) > 0:
return True
# 检查列
for j in range(15):
col = [board[i][j] for i in range(15)]
if ''.join(col).count(player*5) > 0:
return True
# 检查对角线
for i in range(11):
for j in range(11):
diagonal = [board[i+k][j+k] for k in range(5)]
if ''.join(diagonal).count(player*5) > 0:
return True
for i in range(11):
for j in range(4, 15):
diagonal = [board[i+k][j-k] for k in range(5)]
if ''.join(diagonal).count(player*5) > 0:
return True
return False
def player_move():
while True:
x, y = map(int, input("请输入你要落子的坐标,用空格隔开(例如:5 10):").split())
if x < 0 or x > 14 or y < 0 or y > 14:
print("坐标不合法,请重新输入!")
elif board[x][y] != '+':
print("该位置已有棋子,请重新输入!")
else:
board[x][y] = 'X'
break
def computer_move():
while True:
x, y = random.randint(0, 14), random.randint(0, 14)
if board[x][y] == '+':
board[x][y] = 'O'
break
print("欢迎来到五子棋小游戏!")
print_board()
turn = 0
while True:
if turn % 2 == 0:
player_move()
if check_win('X'):
print("恭喜你,你赢了!")
break
else:
computer_move()
if check_win('O'):
print("很遗憾,你输了!")
break
turn += 1
print_board()
```
阅读全文