当我尝试在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自己的教程。
答案 0 :(得分:1)
您尚未调用该方法。
s.Starter()
答案 1 :(得分:1)
您实际上并没有在最后一行调用Starter
方法,只是引用它。这样做:
s.Starter()
称之为。
答案 2 :(得分:1)
调用Starter函数,如
s.Starter()
并且可能存在逻辑错误。下面的while循环将始终为true。
def Starter(self):
while True:
try:
i = int(input(''))
except TypeError:
print 'Not a Number, Try Again.'
continue
答案 3 :(得分: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()