【发布时间】:2025-11-28 17:40:01
【问题描述】:
我正在编写一个基于文本的井字游戏面向对象的编程游戏,但我在宣布获胜者时遇到了问题
我写了这段代码来检查获胜者
def check_result(self):
for a,b,c in self.win_comb:
if(board.sample[a]==board.sample[b]==board.sample[c]=='X'):
print('You Won')
return True
elif(board.sample[a]==board.sample[b]==board.sample[c]=='0'):
print('You Lost')
return True
if 9==(sum(pos=='X' or pos=='0') for pos in board.sample):
print('Draw')
return True
一开始我用这个
while not board().check_result():
game_play().plyr()
game_play().com()
调用检查获胜者的函数,
但是即使在满足game_play().plyr()条件之后,它仍然会在终止循环之前进入game_play().com(),这是违反游戏规则的。
所以我修改了代码,这样每当玩家获胜时,循环就会终止
while not board().check_result():
game_play().plyr()
if(board().check_result()==True):
break
game_play().com()
但我现在遇到的问题是它会打印两次“你不会”,这是我不想要的
完整代码如下
from random import choice
class board:
sample=['-','-','-','-','-','-','-','-','-']
win_comb=[
(0,1,2),
(3,4,5),
(6,7,8),
(0,3,6),
(1,4,7),
(2,5,8),
(0,4,8),
(2,4,6)
]
def board_layout(self):
print("Welcome that's the board layout")
print(1,'|',2,'|',3)
print(4,'|',5,'|',6)
print(7,'|',8,'|',9)
def show(self):
print()
print(board.sample[0],' | ',board.sample[1],' | ',board.sample[2])
print(board.sample[3],' | ',board.sample[4],' | ',board.sample[5])
print(board.sample[6],' | ',board.sample[7],' | ',board.sample[8])
def check_result(self):
for a,b,c in self.win_comb:
if(board.sample[a]==board.sample[b]==board.sample[c]=='X'):
print('You Won')
return True
elif(board.sample[a]==board.sample[b]==board.sample[c]=='0'):
print('You Lost')
return True
if 9==(sum(pos=='X' or pos=='0') for pos in board.sample):
print('Draw')
return True
class game_play:
choose=[1,2,3,4,5,6,7,8,9]
def __init__(self):
pass
def inp(self):
while True:
try:
self.x=int(input("Input between 0 and 9: "))
if self.x in game_play.choose:
game_play.choose.remove(self.x)
return self.x-1
else:
print('pos unavailable')
continue
except ValueError:
print ('invalid char')
continue
def plyr(self):
board.sample[self.inp()]='X'
def com(self):
try:
self.choice=choice(self.choose)
board.sample[self.choice-1]='0'
self.choose. remove(self.choice)
print('The computer play ', self.choice)
except IndexError:
print()
class game:
def __init__(self):
board().board_layout()
while not board().check_result():
game_play().plyr()
if(board().check_result()==True):
break
game_play().com()
board().show()
else:
board.sample=['-','-','-','-','-','-','-','-','-']
game_play.choose=[1,2,3,4,5,6,7,8,9]
while True:
game()
if input('Play Again [y/n] :') != 'y':
break
【问题讨论】:
标签: python python-3.x oop while-loop break