2016-12-10 2 views
0

Я пытаюсь закодировать Tic Tac Toe, где компьютер играет случайным образом с самим собой. Но результат, который я получаю, нереалистичен.TicTacToe код игры

Я имею в виду, иногда я получаю это, например:

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

Вы выбираете содержимое каждой ячейки независимо. Вам придется реализовать алгоритм обработки логики игры. – TigerhawkT3

+0

Я не понял, что вы имеете в виду? –

+3

Я имею в виду, что вы не моделируете покерный матч, бросая колоду на пол. – TigerhawkT3

ответ

0

Хотя это не имеет надежный выбор двигаться, и следует выбирать случайное положение, ниже код должен соответствовать требованиям игры, используя NumPy и вкось.

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

+0

для position.remove (tmppos) В нем говорится: объект «range» не имеет атрибута «remove». Что это значит? –

+0

Попробуйте отредактированный код со списком (диапазон (0,9)) – datawrestler

+0

Я знаю, что это не совсем связано, но здесь идет твиттер, совместимый с Tic Tac Toe;) main() {int a, b; char c [] = ". .. \ n ... \ n ... ", * d; h: scanf ("% d% d ", &a,&b); a = b + 4 * a; if (c [a] == '.') { c [a] = 88; d = strchr (c, 46); d? * d = 79: 0;} puts (c); goto h;} – mko

Смежные вопросы