python简单的五子棋游戏
时间: 2023-07-08 12:35:00 浏览: 125
python五子棋游戏,可双人对弈玩耍,运行简单,项目可作为毕业设计,下载即可运行
好的,以下是一个简单的 Python 五子棋游戏的代码示例:
```python
board = [[0 for i in range(15)] for j in range(15)]
def print_board():
for i in range(15):
for j in range(15):
print(board[i][j], end=' ')
print()
def check_win(row, col, player):
count = 1
# 横向检查
for i in range(col-1, -1, -1):
if board[row][i] == player:
count += 1
else:
break
for i in range(col+1, 15):
if board[row][i] == player:
count += 1
else:
break
if count >= 5:
return True
# 竖向检查
count = 1
for i in range(row-1, -1, -1):
if board[i][col] == player:
count += 1
else:
break
for i in range(row+1, 15):
if board[i][col] == player:
count += 1
else:
break
if count >= 5:
return True
# 左上到右下检查
count = 1
for i, j in zip(range(row-1, -1, -1), range(col-1, -1, -1)):
if board[i][j] == player:
count += 1
else:
break
for i, j in zip(range(row+1, 15), range(col+1, 15)):
if board[i][j] == player:
count += 1
else:
break
if count >= 5:
return True
# 右上到左下检查
count = 1
for i, j in zip(range(row-1, -1, -1), range(col+1, 15)):
if board[i][j] == player:
count += 1
else:
break
for i, j in zip(range(row+1, 15), range(col-1, -1, -1)):
if board[i][j] == player:
count += 1
else:
break
if count >= 5:
return True
return False
player = 1
while True:
print_board()
row = int(input("请输入行号:"))
col = int(input("请输入列号:"))
if board[row][col] != 0:
print("该位置已经有棋子,请重新输入!")
continue
board[row][col] = player
if check_win(row, col, player):
print("玩家 %d 获胜!" % player)
break
player = 3 - player
```
该示例使用一个 15x15 的二维列表表示棋盘,玩家1使用1表示棋子,玩家2使用2表示棋子。玩家输入行号和列号来下棋,每次下完棋之后会检查是否有一方胜利。如果有一方胜利,游戏结束。
阅读全文