TicTacToe游戏代码

时间:2016-12-10 04:35:38

标签: python

我试图编写计算机随机播放的Tic Tac Toe。但我得到的输出是不现实的。

我的意思是有时我得到这个例子:

X X X

O O O

X O X

实际上是不可能的。我的问题是:我怎样才能避免这种情况?

这是我的代码:

import random

a = random.randrange(0,2)
if a==0:
    a = 'O'
else:
    a = 'X'

b = random.randrange(0,2)
if b==0:
    b = 'O'
else:
    b = 'X'

c = random.randrange(0,2)
if c==0:
    c = 'O'
else:
    c = 'X'

d = random.randrange(0,2)
if d==0:
    d = 'O'
else:
    d = 'X'

e = random.randrange(0,2)
if e==0:
    e = 'O'
else:
    e = 'X'

f = random.randrange(0,2)
if f==0:
    f = 'O'
else:
    f = 'X'

g = random.randrange(0,2)
if g==0:
    g = 'O'
else:
    g = 'X'

h = random.randrange(0,2)
if h==0:
    h = 'O'
else:
    h = 'X'

i = random.randrange(0,2)
if i==0:
    i = 'O'
else:
    i = 'X'


Win_Combination = (
    (a, b, c), (d, e, f), (g, h, i),   #Win Horizontal
     (a, d, g), (b, e, h), (c, f, i),  #Win vertical
     (a, e, i), (c, e, g))             #Win diagonal


print(a, b, c)
print(d, e, f)
print(g, h, i)
print()

if a == b and b ==  c:
    print ('Win')
    exit 
elif d == e and e == f:
    print ('Win')
    exit
elif g == h and h == i:
    print ('Win')
    exit
elif a == d and d == g: 
    print ('Win')
    exit
elif b == e and e == h:
    print ('Win')
    exit
elif c == f and f == i:
    print ('Win')
    exit
elif a == e and e == i:
    print ('Win')
    exit
elif c == e and e == g:
    print ('Win')
    exit

1 个答案:

答案 0 :(得分:0)

虽然这没有任何强大的移动选择,并且遵循随机位置选择,但下面的代码应该使用numpy和random来满足游戏要求。

import numpy as np
import random
import pandas as pd

def convertarray(arr):
    """
    Convert numpy array into desired format of X's and O's
    :param arr: numpy array
    :return: convert matrix
    """
    df = pd.DataFrame(arr).replace({1.0: 'X', 2.0: 'O', 0: ''}, inplace=False)
    return df


########################
# Set Game Variables

# Set game board
a = np.zeros([3,3])

# Set values
X = 1
O = 2

# all available remaining positions on the board
positions = list(range(0,9))
turn = [X,O]

# store string representation of board pieces for game over
turndict = {1: 'X', 2: 'O'}

quitgame = 1
#########################

while quitgame != 10:

    # if no available positions left, quit game
    if len(positions) == 0:
        quitgame = 10
        break

    # choose random position
    tmppos = random.choice(positions)

    # remove available position
    positions.remove(tmppos)

    # assign value of position to board
    a = a.reshape([9,1])
    a[tmppos] = turn[0]
    a = a.reshape([3,3])

    # slide over rows and columns to determine if winner present
    toview = range(0,3)
    for index in toview:
        # sum the column values
        column = np.sum(a[:,index])
        # sum the row values
        row = np.sum(a[index, :])
        # if remainder of division of 3 is zero and no non zero elements occur
        # game is over
        if row % 3 == 0 and np.count_nonzero(a[index,:]) == 3:
            print('Game over, {} wins!'.format(turndict[turn[0]]))
            print(convertarray(a))
            quitgame = 10
            break
        elif column % 3 == 0 and np.count_nonzero(a[:, index]) == 3:
            print('Game over, {} wins!'.format(turndict[turn[0]]))
            print(convertarray(a))
            quitgame = 10
            break


    # see if diagonals win
    if a.trace() % 3 == 0 and np.count_nonzero(a.diagonal()) == 3:
        print('Game over, {} wins!'.format(turndict[turn[0]]))
        print(convertarray(a))
        quitgame = 10
        break
    elif np.fliplr(a).trace() % 3 == 0 and np.count_nonzero(np.fliplr(a).diagonal()) == 3:
        print('Game over, {} wins!'.format(turndict[turn[0]]))
        print(convertarray(a))
        quitgame = 10
        break

    # reverse order of turn and repeat
    turn = list(reversed(turn))

如果你真的想用游戏逻辑做一些巧妙的事情,你可以训练一个简单的分类器来选择下一个最好的动作。有一些培训数据可以让您接近正确的设置https://archive.ics.uci.edu/ml/datasets/Tic-Tac-Toe+Endgame,并研究在多个分类器中使用此方法的准确性http://www.ijiet.org/papers/314-k010.pdf