python写一个五子棋游戏
时间: 2023-07-07 11:39:09 浏览: 82
好的,以下是一个简单的五子棋游戏示例代码:
```python
import os
board = [['+' for i in range(15)] for j in range(15)] # 初始化棋盘
def print_board():
os.system('cls' if os.name == 'nt' else 'clear') # 清屏
print(" ", end="")
for i in range(15):
print(chr(ord('A') + i), end=" ")
print()
for i in range(15):
print("{:2d}".format(i+1), end=" ")
for j in range(15):
print(board[i][j], end=" ")
print()
def is_win(x, y, c):
count = 1
i, j = x-1, y
while i >= 0 and board[i][j] == c:
count += 1
i -= 1
i, j = x+1, y
while i < 15 and board[i][j] == c:
count += 1
i += 1
if count >= 5:
return True
count = 1
i, j = x, y-1
while j >= 0 and board[i][j] == c:
count += 1
j -= 1
i, j = x, y+1
while j < 15 and board[i][j] == c:
count += 1
j += 1
if count >= 5:
return True
count = 1
i, j = x-1, y-1
while i >= 0 and j >= 0 and board[i][j] == c:
count += 1
i -= 1
j -= 1
i, j = x+1, y+1
while i < 15 and j < 15 and board[i][j] == c:
count += 1
i += 1
j += 1
if count >= 5:
return True
count = 1
i, j = x-1, y+1
while i >= 0 and j < 15 and board[i][j] == c:
count += 1
i -= 1
j += 1
i, j = x+1, y-1
while i < 15 and j >= 0 and board[i][j] == c:
count += 1
i += 1
j -= 1
if count >= 5:
return True
return False
print_board()
player = 1
while True:
try:
pos = input("Player {} (x,y): ".format(player)).strip()
if pos == 'q':
break
x, y = map(int, pos.split(','))
if x < 1 or x > 15 or y < 1 or y > 15 or board[x-1][y-1] != '+':
raise ValueError
if player == 1:
board[x-1][y-1] = 'O'
if is_win(x-1, y-1, 'O'):
print("Player 1 Win!!")
break
player = 2
else:
board[x-1][y-1] = 'X'
if is_win(x-1, y-1, 'X'):
print("Player 2 Win!!")
break
player = 1
print_board()
except:
print("Invalid input!")
```
这个示例中,我们使用一个二维列表 `board` 来表示棋盘,初始化为全是 `+`。我们定义了一个函数 `print_board()` 来打印当前的棋盘状态,以及一个函数 `is_win()` 来判断是否有玩家获胜。
游戏的主循环中,我们让玩家交替输入落子的坐标,然后判断是否获胜,如果有一方获胜,则输出胜利信息并结束游戏。注意,输入的坐标以逗号分隔,如 `1,1` 表示第一行第一列。如果输入的坐标不合法,则输出错误信息并要求重新输入。
阅读全文