2

プログラムを IDLE で実行しようとすると (現在使用しているテキスト エディター、メモ帳 ++ でインデント エラーが発生し、理由がわかりません)、 のコードのみが実行され__init__ます。これは、オブジェクトに作成されたことを示しています。 . しかし、その後の行でメインメソッドを使用しようとしましたが、何もしません。また、別の方法に変更しましたが、それもうまくいきませんでした。これが私のプログラムです:

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自身のチュートリアルを終えました。

4

4 に答える 4

1

メソッドを呼び出していません。

s.Starter()
于 2012-06-10T10:05:06.757 に答える
1

Starter最後の行で実際にメソッドを呼び出しているのではなく、参照しているだけです。代わりにこれを行います:

s.Starter()

それはそれを呼び出します。

于 2012-06-10T10:05:51.363 に答える
1

次のようなスターター関数を呼び出します

s.Starter()

また、論理エラーが発生する可能性もあります。以下の while ループは常に true になります。

def Starter(self):
        while True:
            try:
                i = int(input(''))
            except TypeError:
                print 'Not a Number, Try Again.'
                continue
于 2012-06-10T10:06:50.943 に答える
0

興味のために、ここに書き直されたバージョンがあります。私はいくつかのより高度なコンストラクトを使用しました - @classmethodandとand@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()
于 2012-06-10T15:06:44.640 に答える