📜  使用随机数的自动井字游戏的Python实现

📅  最后修改于: 2020-05-20 06:36:40             🧑  作者: Mango

井字游戏是一款非常受欢迎的游戏,因此让我们使用Python实现一个自动井字游戏。
该程序会自动玩游戏,因此不需要用户输入。尽管如此,开发自动游戏还是很有趣的。让我们看看如何做到这一点。
numpyrandomPython库用于构建此游戏。代码没有要求用户在板上放置标记,而是随机选择板上的位置并放置标记。除非玩家获胜,否则它将在每回合之后显示棋盘。如果游戏平局,则返回-1。

# 井字游戏程序,在Python中使用随机数
# 导入所有必要的库
import numpy as np
import random
from time import sleep
# 创建一个空板
def create_board():
    return(np.array([[0, 0, 0],
                     [0, 0, 0],
                     [0, 0, 0]]))
# 检查船上是否有空地方
def possibilities(board):
    l = []
    for i in range(len(board)):
        for j in range(len(board)):
            if board[i][j] == 0:
                l.append((i, j))
    return(l)
# 为玩家选择一个随机的地方
def random_place(board, player):
    selection = possibilities(board)
    current_loc = random.choice(selection)
    board[current_loc] = player
    return(board)
# 检查玩家水平行中是否有三个标记
def row_win(board, player):
    for x in range(len(board)):
        win = True
        for y in range(len(board)):
            if board[x, y] != player:
                win = False
                continue
        if win == True:
            return(win)
    return(win)
# 检查玩家在垂直行中是否有三个标记
def col_win(board, player):
    for x in range(len(board)):
        win = True
        for y in range(len(board)):
            if board[y][x] != player:
                win = False
                continue
        if win == True:
            return(win)
    return(win)
# 检查玩家是否在对角线上有三个标记
def diag_win(board, player):
    win = True
    for x in range(len(board)):
        if board[x, x] != player:
            win = False
    return(win)
# 评估是赢家还是平局
def evaluate(board):
    winner = 0
    for player in [1, 2]:
        if (row_win(board, player) or
            col_win(board,player) or
            diag_win(board,player)):
            winner = player
    if np.all(board != 0) and winner == 0:
        winner = -1
    return winner
# 开始游戏的主要函数
def play_game():
    board, winner, counter = create_board(), 0, 1
    print(board)
    sleep(2)
    while winner == 0:
        for player in [1, 2]:
            board = random_place(board, player)
            print("Board after " + str(counter) + " move")
            print(board)
            sleep(2)
            counter += 1
            winner = evaluate(board)
            if winner != 0:
                break
    return(winner)
# 测试代码
print("Winner is: " + str(play_game()))

输出:

[[0 0 0]
 [0 0 0]
 [0 0 0]]
Board after 1 move
[[0 0 0]
 [0 0 0]
 [1 0 0]]
Board after 2 move
[[0 0 0]
 [0 2 0]
 [1 0 0]]
Board after 3 move
[[0 1 0]
 [0 2 0]
 [1 0 0]]
Board after 4 move
[[0 1 0]
 [2 2 0]
 [1 0 0]]
Board after 5 move
[[1 1 0]
 [2 2 0]
 [1 0 0]]
Board after 6 move
[[1 1 0]
 [2 2 0]
 [1 2 0]]
Board after 7 move
[[1 1 0]
 [2 2 0]
 [1 2 1]]
Board after 8 move
[[1 1 0]
 [2 2 2]
 [1 2 1]]
Winner is: 2