2012-06-10 38 views
2

当我尝试在IDLE中运行我的程序(我现在使用的文本编辑器,记事本++表示缩进错误,我不知道为什么),它只会执行__init__中的代码,该代码显示它已创建变成一个物体。但之后的行我尝试使用主要的方法,并没有做任何事情。我也改变了一种不同的方法,但也没有奏效。这里是我的程序:(Python)当我在我的类定义之后调用它时,为什么我的方法对象不会执行?

import sys 

class Main: 
    def __init__(self): 
     WinX = False 
     WinO = False 
     Turn = 'X' 
     LastTurn = 'X' 
     a, b, c, d, e, f, g, h, i = ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' 
     PosList = [] 
     PosList.append(a) 
     PosList.append(b) 
     PosList.append(c) 
     PosList.append(d) 
     PosList.append(e) 
     PosList.append(f) 
     PosList.append(g) 
     PosList.append(h) 
     PosList.append(i) 
     self.board = '+---+---+---+\n| ' + PosList[0] +' | '+ PosList[1] +' | '+ PosList[2] +' |\n+---+---+---+\n| '+ PosList[3] +' | '+ PosList[4] +' | '+ PosList[5] +' |\n+---+---+---+\n| '+ PosList[6] +' | '+ PosList[7] +' | '+ PosList[8] +' |\n+---+---+---+' 
     print self.board 

    def UpdateTurn(self): 
     if LastTurn == 'X': 
      Turn == 'O' 
     elif LastTurn == 'O': 
      Turn == 'X' 
     LastTurn = Turn 

    def WinChecker(self): 
     if a and b and c == 'X' or a and d and g == 'X' or a and e and i == 'X' or g and e and c == 'X' or g and h and i == 'X' or c and f and i == 'X': 
      WinX = True 
     if a and b and c == 'O' or a and d and g == 'O' or a and e and i == 'O' or g and e and c == 'O' or g and h and i == 'O' or c and f and i == 'O': 
      WinO = True 

    def UpdateBoard(self): 
     print self.board 

    def Starter(self): 
     while True: 
      try: 
       i = int(input('')) 
      except TypeError: 
       print 'Not a Number, Try Again.' 
       continue 
     i -= 1 
     PosList[i] = Turn 
     self.UpdateBoard 
     self.WinChecker 
     if Winx == True: 
      print 'X Wins!' 
      sys.exit() 
     elif Wino == True: 
      print 'O Wins!' 
      sys.exit() 
     self.UpdateTurn 

s = Main() 
s.Starter 

我只是(4天)完成了python自己的教程。

+1

Python中的方法用括号调用。使用s.Starter()来执行该方法。 – Tisho

+0

这里还有另一个问题。你永远不会跳出输入循环。 – Keith

+0

直到他们给出了有效的答案之前,我从来没有跳出过输入循环。那么,那就是我反正想的。好吧,只是尝试过,你是对的,需要解决这个问题......其实我只是忘了缩进函数的其余部分。我需要在下一次注意。尽管感谢您的回答,但它帮助我通过代码来查找。 – Rees

回答

1

通话入门之类的函数

s.Starter() 

而且也有可能是一个逻辑上的错误下面的while循环将总是如此。

def Starter(self): 
     while True: 
      try: 
       i = int(input('')) 
      except TypeError: 
       print 'Not a Number, Try Again.' 
       continue 
1

您还没有调用该方法。

s.Starter() 
1

你实际上并没有要求在最后一行Starter方法,只是引用它。代之以:

s.Starter() 

这就是它。

0

感兴趣的是,这是一个改写的版本。我已经使用了一些更高级的构造 - @classmethod@property以及“神奇方法”,如__str____repr__。希望你觉得它有用!

def getInt(prompt='', lo=None, hi=None): 
    """ 
    Get integer value from user 

    If lo is given, value must be >= lo 
    If hi is given, value must be <= hi 
    """ 
    while True: 
     try: 
      val = int(raw_input(prompt)) 

      if lo is not None and val < lo: 
       print("Must be at least {}".format(lo)) 
      elif hi is not None and val > hi: 
       print("Must be no more than {}".format(hi)) 
      else: 
       return val 
     except ValueError: 
      print("Must be an integer!") 

class TicTacToe(object): 
    players = ('X', 'O')  # player characters 
    blank = ' '     # no-player character 
    wins = (     # lines that give a win 
     (0,1,2), 
     (3,4,5), 
     (6,7,8), 
     (0,3,6), 
     (1,4,7), 
     (2,5,8), 
     (0,4,8), 
     (2,4,6) 
    ) 
    board_string = '\n'.join([ # format string 
     "", 
     "+---+---+---+", 
     "| {} | {} | {} |", 
     "+---+---+---+", 
     "| {} | {} | {} |", 
     "+---+---+---+", 
     "| {} | {} | {} |", 
     "+---+---+---+" 
    ]) 

    @classmethod 
    def ch(cls, state): 
     """ 
     Given the state of a board square (None or turn number) 
     return the output character (blank or corresponding player char) 
     """ 
     if state is None: 
      return cls.blank 
     else: 
      return cls.players[state % len(cls.players)] 

    def __init__(self, bd=None): 
     """ 
     Set up a game of TicTacToe 

     If board is specified, resume playing (assume board state is valid), 
     otherwise set up a new game 
     """ 
     if bd is None: 
      # default constructor - new game 
      self.turn = 0 
      self.board = [None for i in range(9)] 
     elif hasattr(bd, "board"):  # this is 'duck typing' 
      # copy constructor 
      self.turn = sum(1 for sq in bd if sq is not None) 
      self.board = bd.board[:] 
     else: 
      # given board state, resume game 
      self.turn = sum(1 for sq in bd if sq is not None) 
      self.board = list(bd) 

    @property 
    def board_chars(self): 
     """ 
     Return the output characters corresponding to the current board state 
     """ 
     getch = type(self).ch 
     return [getch(sq) for sq in self.board] 

    @property 
    def winner(self): 
     """ 
     If the game has been won, return winner char, else None 
     """ 
     bd = self.board_chars 
     cls = type(self) 
     for win in cls.wins: 
      c0, c1, c2 = (bd[sq] for sq in win) 
      if c0 != cls.blank and c0 == c1 and c0 == c2: 
       return c0 
     return None 

    def __str__(self): 
     """ 
     Return a string representation of the board state 
     """ 
     cls = type(self) 
     return cls.board_string.format(*self.board_chars) 

    def __repr__(self): 
     """ 
     Return a string representation of the object 
     """ 
     cls = type(self) 
     return "{}({})".format(cls.__name__, self.board) 

    def do_move(self): 
     """ 
     Get next player's move 
     """ 
     cls = type(self) 
     next_player = cls.ch(self.turn) 
     while True: 
      pos = getInt("Player {} next move? ".format(next_player), 1, 9) - 1 
      if self.board[pos] is None: 
       self.board[pos] = self.turn 
       self.turn += 1 
       break 
      else: 
       print("That square is already taken") 

    def play(self): 
     print("Welcome to Tic Tac Toe. Board squares are numbered 1-9 left-to-right, top-to-bottom.") 
     while True: 
      print(self)  # show the board - calls self.__str__ 
      w = self.winner 
      if w is None: 
       self.do_move() 
      else: 
       print("{} is the winner!".format(w)) 
       break 

def main(): 
    TicTacToe().play() 

if __name__=="__main__": 
    main() 
相关问题