我是一名Python初学者,目前正在使用类进行Tic-Tac-Toe游戏。实际上,我是故意使用课程来进行练习,即使避免使用它们也是有意义的。
以下是代码的一部分:
import sys
class Build_board():
boardg = []
num_of_rows = 3
num_of_cols = 3
def generate(self):
for x in range(self.num_of_rows):
self.boardg.append(['0' for x in range(self.num_of_cols)])
def print_board(self):
for row in self.boardg:
print(" ".join(row))
class Players(object):
name = ""
score = 0
players_dic = {}
def ask_name(self):
for i in range(2):
self.name = input("What's {plyr} player's name? ".format(plyr="first" if i == 0 else "second"))
self.players_dic["p" + str(i+1) + "_name"] = self.name
self.players_dic["p" + str(i+1) + "_score"] = self.score
class Players_turn(Players): #PROBLEM HERE
def __init__(self, turn):
self.turn = turn
def whos_turn(self):
if self.turn % 2 == 1:
return self.players_dic['p1_name'], '1'
elif self.turn % 2 == 0:
return self.players_dic['p2_name'], '2'
else:
return 'incorrect', '3'
上面的Players'turn()类旨在根据现在的转弯返回应该转弯的玩家。
if __name__ == '__main__':
turn = 0
在此处创建变量。
board = Build_board()
board.generate()
players = Players()
players.ask_name()
pdic = players.players_dic
players_turn = Players_turn(turn)
who_now = players_turn.whos_turn()
def game():
for round in range(3):
while True:
global turn
turn += 1
players_turn = Players_turn(turn)
print("Turn", turn)
if ['0' in list_ for list_ in board.boardg]:
print("It's", players_turn.whos_turn()[0] + "'s turn.")
else:
return False
sys.exit()
game()
在game()函数中,我重新定义变量转弯并且每回合将其增加1,然后创建一个Players_turn()类的实例,以便更改turn变量的值,以便在一个变量中使用'whos_turn()' class可以返回不同的玩家。 我知道有更好的方法可以不使用全局变量。
我的问题是: 有没有其他方法可以在类/类的实例中更改变量值,而无需使用同一类的新实例创建/覆盖它?