用python写一个五子棋小游戏
时间: 2023-12-07 21:41:35 浏览: 132
当然可以!下面是一个简单的五子棋小游戏的 Python 代码示例:
```python
# 初始化棋盘
board = [[' ' for _ in range(15)] for _ in range(15)]
# 定义一个函数以打印当前棋盘
def print_board(board):
print(' 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14')
print(' -----------------------------')
for i in range(15):
print(f'{i}|', end='')
for j in range(15):
print(board[i][j], end=' ')
print('|')
print(' -----------------------------')
# 定义一个函数以检查是否有玩家获胜
def check_win(board, row, col, player):
# 检查水平方向
count = 0
for i in range(col-4, col+5):
if i < 0 or i >= 15:
continue
if board[row][i] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 检查垂直方向
count = 0
for i in range(row-4, row+5):
if i < 0 or i >= 15:
continue
if board[i][col] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 检查正斜方向
count = 0
for i in range(-4, 5):
if row+i < 0 or row+i >= 15 or col+i < 0 or col+i >= 15:
continue
if board[row+i][col+i] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 检查反斜方向
count = 0
for i in range(-4, 5):
if row-i < 0 or row-i >= 15 or col+i < 0 or col+i >= 15:
continue
if board[row-i][col+i] == player:
count += 1
if count == 5:
return True
else:
count = 0
return False
# 游戏主循环
player = 'X'
while True:
print_board(board)
print(f"轮到玩家 {player} 下棋")
# 获取玩家输入
while True:
row = int(input("请输入行号(0-14):"))
col = int(input("请输入列号(0-14):"))
if row >= 0 and row < 15 and col >= 0 and col < 15 and board[row][col] == ' ':
break
else:
print("输入无效,请重新输入")
# 在棋盘上下棋
board[row][col] = player
# 检查是否有玩家获胜
if check_win(board, row, col, player):
print_board(board)
print(f"玩家 {player} 获胜!")
break
# 切换玩家
player = 'O' if player == 'X' else 'X'
```
这个代码实现了一个简单的五子棋小游戏。玩家可以通过输入行号和列号来下棋,程序会根据玩家的输入在棋盘上放置棋子,并在每一步后检查是否有玩家获胜。如果有玩家获胜,则游戏结束并打印获胜信息。否则,游戏将继续进行,切换到另一个玩家下棋。
阅读全文