python写五子棋人机对战,不要用到pygame
时间: 2023-10-08 11:06:52 浏览: 264
好的,我可以给您提供一个简单的五子棋人机对战的代码,不用pygame。
```python
import random
# 画棋盘
def draw_board(board):
for i in range(len(board)):
for j in range(len(board[i])):
print(board[i][j], end='')
print()
# 判断是否胜利
def is_win(board, player):
# 判断横向是否有五个子相连
for i in range(len(board)):
for j in range(len(board[i])-4):
if board[i][j] == player and board[i][j+1] == player and board[i][j+2] == player and board[i][j+3] == player and board[i][j+4] == player:
return True
# 判断竖向是否有五个子相连
for i in range(len(board)-4):
for j in range(len(board[i])):
if board[i][j] == player and board[i+1][j] == player and board[i+2][j] == player and board[i+3][j] == player and board[i+4][j] == player:
return True
# 判断斜向是否有五个子相连
for i in range(len(board)-4):
for j in range(len(board[i])-4):
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 and board[i+4][j+4] == player:
return True
for i in range(4, len(board)):
for j in range(len(board[i])-4):
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 and board[i-4][j+4] == player:
return True
return False
# 电脑下棋
def computer_move(board, computer):
empty_spaces = []
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == ' ':
empty_spaces.append((i, j))
if len(empty_spaces) == 0:
return False
else:
row, col = random.choice(empty_spaces)
board[row][col] = computer
return True
# 黑棋先手,白棋后手
def main():
board = []
for i in range(15):
board.append([' ']*15)
player = 'X'
computer = 'O'
while True:
draw_board(board)
if player == 'X':
row = int(input('请输入行号(1~15):')) - 1
col = int(input('请输入列号(1~15):')) - 1
if board[row][col] == ' ':
board[row][col] = player
if is_win(board, player):
print('你赢了!')
draw_board(board)
break
player, computer = computer, player
else:
print('该位置已经有棋子,请换一个位置!')
else:
if computer_move(board, computer):
if is_win(board, computer):
print('电脑赢了!')
draw_board(board)
break
player, computer = computer, player
if __name__ == '__main__':
main()
```
这个代码只是一个简单的实现,如果需要更完善的功能可以自己进行添加。
阅读全文