Tic-tac-toe是一款非常受欢迎的游戏,所以让我们使用Python实现一个自动的Tic-tac-toe游戏。
游戏由程序自动播放,因此不需要用户输入。不过,开发自动游戏会很有趣。让我们看看如何做到这一点。
numpy
和random
Python库用于构建这个游戏。代码不是要求用户在电路板上放置标记,而是随机选择电路板上的一个位置并放置标记。除非玩家获胜,否则它将在每次转弯后显示
棋盘。如果游戏得到平局,则返回-1。
# Tic-Tac-Toe Program using
# random number in Python
# importing all necessary libraries
import
numpy as np
import
random
from
time import
sleep
# Creates an empty board
def
create_board():
return(np.array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]))
# Check for empty places on board
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)
# Select a random place for the player
def
random_place(board, player):
selection =
possibilities(board)
current_loc =
random.choice(selection)
board[current_loc] =
player
return(board)
# Checks whether the player has three
# of their marks in a horizontal row
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)








暂无数据