board=[[1,0,8,5,12,16,24],[7,0,6,2,20,4,18],[13,0,9,10,22,23,17],[19,0,11,3,14,15,21]]
def move():
while board[0][6]!= 0 and board[1][6]!=0 and board[2][6]!=0 and board[3][6]!=0:
user_choice= int(raw_input('>'))
for lists in board:
for i in range(len(lists)):
if lists[i]== user_choice-1 and lists[i+1]==0:
lists[i+1]= user_choice
print print_board(board)
for a in board:
for i in range(len(a)):
if a[i]==user_choice:
a[i]=0
print print_board(board)
我正在制作一个用户输入数字(user_choice)的游戏。该程序将找到小于user_choice的数字1。假设用户选择8,游戏将在板上找到数字7,如果7之后的数字是0,则程序交换0和8的位置。
我的代码有效,除非第二个if语句运行输出时撤消第一个if语句
这是user_choice = 8的典型输出:
[[1,0,8,5,12,16,24],[7,8,6,2,20,4,18],[13,0,9,10,22,23,17],[19,0,11,3,14,15,21]]
None
[[1,0,8,5,12,16,24],[7,0,6,2,20,4,18],[13,0,9,10,22,23,17],[19,0,11,3,14,15,21]]
None
[[1,0,0,5,12,16,24],[7,0,6,2,20,4,18],[13,0,9,10,22,23,17],[19,0,11,3,14,15,21]]
第一个输出用7替换了7之后的0 第二个输出似乎显示了初始板 第三个输出用0替换初始板中的8。
我想要一个输出,它将7之后的0替换为8,并用0替换初始值8。
答案 0 :(得分:0)
更改编辑电路板的顺序。首先将任何其他' 8替换为零,然后在7到8之后更改零。
for i in range(len(lists)-1):
if lists[i]== user_choice-1 and lists[i+1]==0:
for a in board:
for j in range(len(a)):
if a[j]==user_choice:
a[j]=0
print print_board(board)
lists[i+1]= user_choice
print print_board(board)
我还使用了不同的变量i和j,并尝试避免使用IndexError
,如果i+1 == len(lists)
此处的操作顺序非常重要。如果你首先将7之后的0替换为8,然后将所有8替换为0,则整体效果是将7之后的0替换为0.不是你想要的
如果您先将其他8s更改为0,然后在7到8后更改零,则整体效果就是您想要的效果。
我认为这里可能仍然存在错误。例如,可以有多个7后跟0吗?如果在主板上有一个7后跟一个8,会发生什么?解决这些错误意味着要仔细考虑你想要计算机做什么,因为它不会为你做思考!
答案 1 :(得分:0)
这不是世界上最优雅的解决方案,但这是我的:
board = [
[1, 0, 8, 5, 12, 16, 24],
[7, 0, 6, 2, 20, 4, 18],
[13, 0, 9, 10, 22, 23, 17],
[19, 0, 11, 3, 14, 15, 21]
]
def print_board():
for row in board:
print " ".join("{:2}".format(x) for x in row)
while any(row[6] for row in board):
print_board()
user_choice = int(raw_input('-> '))
replace_match = False
for i, row in enumerate(board):
pairs = zip(row, row[1:])
for j, pair in enumerate(pairs):
if pair == (user_choice - 1, 0):
board[i][j+1] = user_choice
replace_match = (i, j+1)
print pair
break
else:
if replace_match:
for i, row in enumerate(board):
board[i] = [x if (x != user_choice or (i, j) == replace_match) else 0 for j, x in enumerate(row)]
答案 2 :(得分:0)
如果您将问题分解为更小的功能,我认为您会发现更容易的事情。这是一个简单的例子:
board = [[1,0,8,5,12,16,24],[7,0,6,2,20,4,18],[13,0,9,10,22,23,17],[19,0,11,3,14,15,21]]
# See if item is in lst. If so, return xy location
def in_list(item, lst):
for i in range(0, len(lst)):
for j in range(0, len(lst[i])):
if lst[i][j] == item:
return i, j
return -1,-1
def print_board():
for i in board:
for j in i:
print j, ' ',
print
def game_over():
return board[0][6] == 0 and board[1][6] == 0 and board[2][6] == 0 and board[3][6] == 0
while (False == game_over()):
print_board()
user_choice = int(input("Enter a number: "))
# ux,uy are co-ords of user choice
ux, uy = in_list(user_choice, board)
if (-1 != ux):
# mx,my are co-ords of user choice+1
mx, my = in_list(user_choice - 1, board)
if (-1 != mx):
if (0 == board[mx][my + 1]):
board[ux][ux] = 0
board[mx][my + 1] = user_choice