我想在python 3.7中建立连接四,我们很快陷入困境,我们真的很新,所以这就是原因。我们过分地希望将播放器1和2的1和2放在下面的网格中,但是当我们在同一列中将输入作为播放器1和2时,它不起作用。我很希望有人能帮助我们,因为我们已经坚持了很长时间,在此先感谢您! ps。我们不想使用任何python插件或附加功能,而只能使用常规if,def和while等语句。
ROW_COUNT = 6
COLUMN_COUNT = 7
row6 = [0, 0, 0, 0, 0, 0, 0]
row5 = [0, 0, 0, 0, 0, 0, 0]
row4 = [0, 0, 0, 0, 0, 0, 0]
row3 = [0, 0, 0, 0, 0, 0, 0]
row2 = [0, 0, 0, 0, 0, 0, 0]
row1 = [0, 0, 0, 0, 0, 0, 0]
Board=[row6, row5, row4, row3, row2, row1]
def drop_piece(Board, row, Column, piece):
Board[row][Column] = piece
def is_valid_location(Board, Column):
return Board[0][Column] ==0
def get_next_open_row(Board, Column):
for r in range(ROW_COUNT):
if Board[r][Column]==0:
return r
gameOver = False
turn = 0
while not gameOver:
if turn == 0:
Column = int(input("Player 1, Make your turn(0-6):"))
if is_valid_location(Board ,Column):
row = get_next_open_row(Board, Column)
drop_piece(Board, row, Column, 1)
turn = turn + 1
else:
Column = int(input("Player 2, Make your turn(0-6):"))
if is_valid_location(Board, Column):
row = get_next_open_row(Board, Column)
drop_piece(Board, row, Column, 2)
turn = turn - 1
print(row1)
print(row2)
print(row3)
print(row4)
print(row5)
print(row6)
答案 0 :(得分:0)
这应该使您重新开始,仍然需要编写gameOver
部分。
一个问题是您将显示定义为:
row6 = [0, 0, 0, 0, 0, 0, 0]
row5 = [0, 0, 0, 0, 0, 0, 0]
row4 = [0, 0, 0, 0, 0, 0, 0]
row3 = [0, 0, 0, 0, 0, 0, 0]
row2 = [0, 0, 0, 0, 0, 0, 0]
row1 = [0, 0, 0, 0, 0, 0, 0]
Board=[row6, row5, row4, row3, row2, row1]
但是,使用以下命令打印输出
print(row1) #Prints First
print(row2)
print(row3)
print(row4)
print(row5)
print(row6) #Prints Last
使它在屏幕上显示为:
row1 = [0, 0, 0, 0, 0, 0, 0]
row2 = [0, 0, 0, 0, 0, 0, 0]
row3 = [0, 0, 0, 0, 0, 0, 0]
row4 = [0, 0, 0, 0, 0, 0, 0]
row5 = [0, 0, 0, 0, 0, 0, 0]
row6 = [0, 0, 0, 0, 0, 0, 0]
另一个是您的切换开关很容易损坏:
if turn == 0:
if is_valid_location(Board ,Column):
turn = turn + 1
else:
turn = turn - 1
这意味着回合唯一可以增加的方法是turn
为0并且Column
是有效位置,否则它将继续是玩家2的回合并继续递减。
这是我的代码,现在基于count变量中设置的行和列来动态显示,切换是基于布尔值的,并且仅切换播放器,为用户选择添加了验证,并且打印是循环完成:
ROW_COUNT = 6
COLUMN_COUNT = 7
Board = [] # Define the Board list
# Appends a list of 0s COLUMN_COUNT long, to the Board list, ROW_COUNT amount of times.
for x in range(ROW_COUNT): Board.append(list([0] * COLUMN_COUNT))
def drop_piece(Board, row, Column, piece):
Board[row][Column] = piece
def is_valid_location(Board, Column):
# Checks that the top row for the selected column is 0
return Board[-1][Column] == 0
def get_next_open_row(Board, Column):
for r in range(ROW_COUNT):
if Board[r][Column]==0:
return r
gameOver = False
turn = True
while not gameOver:
# Boolean toggle True = player 1, False = player 2
if turn: player = 1
else: player = 2
Column = int(input("Player " + str(player) +", Make your turn(0-6):"))
if is_valid_location(Board, Column):
row = get_next_open_row(Board, Column)
drop_piece(Board, row, Column, player)
turn = not turn
else: print("Invalid selection")
# prints the reversed Board, since printing needs to be last printed first
for row in reversed(Board):
print(row)