python制作五子棋
时间: 2023-07-31 17:05:02 浏览: 98
好的,下面给出一个简单的五子棋游戏实现:
```python
import os
# 初始化棋盘
def init_board():
board = []
for i in range(15):
board.append(['+'] * 15)
return board
# 打印棋盘
def print_board(board):
os.system('clear')
print(' ' + ' '.join([str(i+1) for i in range(15)]))
for i in range(15):
print(str(i+1).rjust(2) + ' ' + ' '.join(board[i]))
# 判断胜负
def check_win(board, row, col, ch):
count = 0
# 判断横向是否满足胜利条件
for i in range(15):
if board[row][i] == ch:
count += 1
else:
count = 0
if count == 5:
return True
# 判断纵向是否满足胜利条件
count = 0
for i in range(15):
if board[i][col] == ch:
count += 1
else:
count = 0
if count == 5:
return True
# 判断左上到右下斜线是否满足胜利条件
count = 0
for i in range(-4, 5):
if row+i < 0 or row+i > 14 or col+i < 0 or col+i > 14:
continue
if board[row+i][col+i] == ch:
count += 1
else:
count = 0
if count == 5:
return True
# 判断右上到左下斜线是否满足胜利条件
count = 0
for i in range(-4, 5):
if row+i < 0 or row+i > 14 or col-i < 0 or col-i > 14:
continue
if board[row+i][col-i] == ch:
count += 1
else:
count = 0
if count == 5:
return True
return False
# 主程序
def main():
board = init_board()
print_board(board)
player = 'x'
while True:
row = int(input('请输入落子的行号(1-15):')) - 1
col = int(input('请输入落子的列号(1-15):')) - 1
if board[row][col] != '+':
print('该位置已经有棋子,请重新输入!')
continue
board[row][col] = player
print_board(board)
if check_win(board, row, col, player):
print('恭喜玩家%s获胜!' % player)
break
if player == 'x':
player = 'o'
else:
player = 'x'
if __name__ == '__main__':
main()
```
运行后,将会在终端中显示一个棋盘,玩家可以输入行列坐标来落子,程序会判断胜负并输出结果。
阅读全文