我正在尝试制作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!
当我再次将其插入功能时,它没有用。我不知道我在做什么错。谁能告诉我如何解决这个问题?
答案 0 :(得分:0)
我只是快速浏览了一下这段代码,并用更简单的代码替换了所有让我头疼的东西,这些代码看起来像原始代码试图做的那样。 (这肯定可以进一步简化,但我只是想尽力而为,以使其运行。)似乎可以正常工作,重写那些代码比调试它们要快得多。 / p>
board = [[None for a in range(7)] for i in range(8)]
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[column][6-i] is not None:
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 not self.column_full:
if column <= 7 and column > 0:
board[column][6-self.column_num] = 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):
values = {board[b][d] for b in range(c, c+4)}
if len(values) == 1 and values.pop() is not None:
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() # prints "You won!" now