用python编写一个字符界面的五子棋人机对战程序,游戏难度中等
时间: 2024-05-14 16:17:24 浏览: 140
好的,我可以帮你实现一个基于Python的字符界面五子棋人机对战程序,难度中等。下面是代码实现:
```
import random
def draw_board(board):
print(' 1 2 3 4 5 6 7')
print(' +-+-+-+-+-+-+-+')
for i in range(7):
print(str(i+1)+'|'+board[i][0]+'|'+board[i][1]+'|'+board[i][2]+'|'+board[i][3]+'|'+board[i][4]+'|'+board[i][5]+'|'+board[i][6]+'|')
print(' +-+-+-+-+-+-+-+')
def make_move(board, row, col, player):
if board[row][col] == ' ':
board[row][col] = player
return True
else:
return False
def is_winner(board, player):
for i in range(7):
for j in range(3):
if board[i][j] == player and board[i][j+1] == player and board[i][j+2] == player and board[i][j+3] == player:
return True
for i in range(4):
for j in range(7):
if board[i][j] == player and board[i+1][j] == player and board[i+2][j] == player and board[i+3][j] == player:
return True
for i in range(4):
for j in range(3):
if board[i][j] == player and board[i+1][j+1] == player and board[i+2][j+2] == player and board[i+3][j+3] == player:
return True
for i in range(4):
for j in range(3, 7):
if board[i][j] == player and board[i+1][j-1] == player and board[i+2][j-2] == player and board[i+3][j-3] == player:
return True
return False
def get_computer_move(board, computer_player):
for i in range(7):
for j in range(7):
if board[i][j] == ' ':
board[i][j] = computer_player
if is_winner(board, computer_player):
return (i, j)
else:
board[i][j] = ' '
for i in range(7):
for j in range(7):
if board[i][j] == ' ':
board[i][j] = 'X' if computer_player == 'O' else 'O'
if is_winner(board, 'X' if computer_player == 'O' else 'O'):
return (i, j)
else:
board[i][j] = ' '
return (random.randint(0, 6), random.randint(0, 6))
board = [[' ']*7 for i in range(7)]
player = 'X'
computer_player = 'O'
while True:
draw_board(board)
if player == 'X':
while True:
row = int(input('Enter row: '))-1
col = int(input('Enter column: '))-1
if make_move(board, row, col, player):
break
else:
print('Invalid move, try again.')
if is_winner(board, player):
print('You win!')
break
player = 'O'
else:
row, col = get_computer_move(board, computer_player)
make_move(board, row, col, computer_player)
if is_winner(board, computer_player):
print('You lose!')
break
player = 'X'
```
这个程序实现了基本的五子棋人机对战,你可以通过输入行和列来下棋,电脑会自动进行落子并判断胜负。
阅读全文