[python]代码库
import random
# 定义棋盘
board = [[' ' for _ in range(3)] for _ in range(3)]
# 打印棋盘
def print_board():
print('-------------')
for i in range(3):
print('|', board[i][0], '|', board[i][1], '|', board[i][2], '|')
print('-------------')
# 判断胜负
def check_win(player):
for i in range(3):
if board[i][0] == board[i][1] == board[i][2] == player:
return True
if board[0][i] == board[1][i] == board[2][i] == player:
return True
if board[0][0] == board[1][1] == board[2][2] == player:
return True
if board[0][2] == board[1][1] == board[2][0] == player:
return True
return False
# 人类玩家落子
def human_player():
while True:
row = int(input('请输入行号(1-3):'))
col = int(input('请输入列号(1-3):'))
if row < 1 or row > 3 or col < 1 or col > 3:
print('输入有误,请重新输入!')
elif board[row - 1][col - 1] != ' ':
print('该位置已经有棋子了,请重新输入!')
else:
board[row - 1][col - 1] = 'X'
break
# AI玩家落子
def ai_player():
while True:
row = random.randint(1, 3)
col = random.randint(1, 3)
if board[row - 1][col - 1] == ' ':
board[row - 1][col - 1] = 'O'
break
# 主函数
def main():
print('欢迎来到人工智能PK棋盘游戏!')
print_board()
while True:
human_player()
print_board()
if check_win('X'):
print('恭喜你获胜了!')
break
if ' ' not in [cell for row in board for cell in row]:
print('平局!')
break
ai_player()
print_board()
if check_win('O'):
print('很遗憾,你输了!')
break
# 运行主函数
if __name__ == '__main__':
main()
中级程序员
by: 小guo 发表于:2023-06-09 19:38:26 顶(2) | 踩(0) 回复
回复评论