2016-04-11 119 views
0

我正在用Python調用一個函數winning來寫一個tic tac腳趾遊戲,我在幾個不同的地方打電話。當我從winning_human函數調用它時,它似乎工作正常,但是當我將它用於計算機(「AI」)時,它在所有情況下都會返回false,我真的無法弄清楚原因。有任何想法嗎?嵌套功能不工作 - 井字遊戲

import pprint 

class Game(object): 

    def __init__(self, player, board): 
     self.player = player   
     self.board = board 

    def print_board(self): 
     print(self.board[1]+ '|' + self.board[2]+ '|' + self.board[3]) 
     print('-----') 
     print(self.board[4]+ '|' + self.board[5]+ '|' + self.board[6]) 
     print('-----') 
     print(self.board[7]+ '|' + self.board[8]+ '|' + self.board[9]) 

    def play(self,board): 
     self.print_board() 
     print('specify your move (1,2,3,4,5,6,7,8,9)') 
     self.move = int(input()) 
     valid_moves = [1,2,3,4,5,6,7,8,9] 
     if self.move not in valid_moves: 
      print('you did not specify a valid move, please try again!') 
      self.play(self.board) 
     if self.board[self.move] != ' ': 
      print ('you can not play that space, it is taken') 
      self.play(self.board)   
     self.board[self.move]='X' 
     self.print_board() 
     self.winning_human('X', self.board) 


    def winning(self, player, board): 
     return ((self.board[1]==self.player and self.board[2]==self.player and self.board[3]==self.player)or   
     (self.board[4]==self.player and self.board[5]==self.player and self.board[6]==self.player)or 
     (self.board[7]==self.player and self.board[8]==self.player and self.board[9]==self.player)or   
     (self.board[1]==self.player and self.board[4]==self.player and self.board[7]==self.player)or  
     (self.board[2]==self.player and self.board[5]==self.player and self.board[8]==self.player)or 
     (self.board[3]==self.player and self.board[6]==self.player and self.board[9]==self.player)or 
     (self.board[1]==self.player and self.board[5]==self.player and self.board[9]==self.player)or 
     (self.board[3]==self.player and self.board[5]==self.player and self.board[7]==self.player)) 

    def winning_human(self, player, board): 
     if self.winning('X', self.board): 
      True 
      print('you won') 
     else: 
      print('the game shall cont (winning human funct).') 
      self.comp_play('O', self.board) 

    def comp_play(self, player, board): 
     for i in range(1,10): 
      if self.board[i] == ' ': 
       self.board[i] = 'O' 
       if self.winning('O',self.board): 
        self.end_game(self) 
       else: 
        self.board[i] = ' ' 

     #check if player can win in next move, block if so 
     #check if middle is free 
     #check if corner is free  


    def end_game(self): 
     self.print_board() 
     print('Thanks for playing, the computer beat you')   

    theBoard = {1:' ', 2:'O', 3:'O', 4: ' ', 5:'X', 6: 'X', 7:' ', 8:' ', 9:' '} 
    g=Game('X', theBoard) 
    g.play(theBoard) 

回答

0

你通過播放器來檢查(XO)到winning方法,但後來這個方法裏面,你只能使用self.player(這始終是X)。

+0

謝謝你是對的! –