2

当我尝试在 IDLE 中运行我的程序时(我目前正在使用的文本编辑器,notepad ++ 说缩进错误,我不知道为什么)它只执行 中的代码__init__,这表明它已被创建为一个对象. 但是在那之后的那一行我尝试使用 main 方法并且它没有做任何事情。我也将其更改为不同的方法,但这也不起作用。这是我的程序:

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

调用 Starter 函数,如

s.Starter()

并且可能存在逻辑错误下面的while循环将始终为真。

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

出于兴趣,这里是一个重写的版本。我使用了一些更高级的构造 -@classmethod@property' 魔术方法' 像__str__and __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 回答