【发布时间】:2020-08-24 10:32:30
【问题描述】:
我正在尝试制作 Connect 4 游戏。这是我的代码:
board = {}
for i in range(1,8):
board[f'{i}_column'] = {}
for a in range(1,7):
board[f'{i}_column'][f'{i}x{a}_position'] = 'Empty'
class Checker:
def __init__(self,color):
self.color = color
def find_column_amount(self,column):
self.column_num = 0
self.column_full = False
for i in range(0,6):
if board[f'{column}_column'][f'{column}x{6-i}_position'] != 'Empty':
self.column_num += 1
else:
pass
if self.column_num >= 6:
self.column_full = True
def place(self,column):
self.find_column_amount(column)
if self.column_full == False:
if column <= 7 and column > 0:
board[f'{column}_column'][f'{column}x{6-self.column_num}_position'] = self.color.title()
else:
print('You\'re out of the range!')
else:
print(f'Column {column} is full!\nTry another one!')
def check_win(self):
for d in range(1,7):
for c in range(1,5):
for b in range(c,c+4):
vars()[f'value_{b-c+1}'] = board[f'{b}_column'][f'{b}x{d}_position']
if value_1 == value_2 == value_3 == value_4 and (value_1 and value_2 and value_3 and value_4) != 'Empty':
self.win()
def win(self):
print('You won!')
为了看看它是否有效,我运行了这个:
p1 = Checker('red')
p1.place(1)
p1.place(2)
p1.place(3)
p1.place(4)
p1.check_win()
我尝试了这段代码,但没有成功。错误的部分是 check_win 函数。我在函数外测试了代码,并将 self.win() 更改为 print('You won!') 并且成功了。
for d in range(1,7):
for c in range(1,5):
for b in range(c,c+4):
vars()[f'value_{b-c+1}'] = board[f'{b}_column'][f'{b}x{d}_position']
if value_1 == value_2 == value_3 == value_4 and (value_1 and value_2 and value_3 and value_4) != 'Empty':
print('You won!')
结果是这样的:
You won!
当我再次将其插入该功能时,它不起作用。我不知道我做错了什么。谁能告诉我如何解决这个问题?
【问题讨论】:
-
这:
(value_1 and value_2 and value_3 and value_4) != 'Empty不是您将多个变量与一个值进行比较的方式。 -
动态生成的字典键和
vars()是一种非常复杂的二维数组存储方式。我将四处走动,并猜测那里的某些东西引起了问题。