2016-11-15 86 views
0

看到从这个网站制作一个cnect-4游戏的想法,所以我决定尝试一下自己使用这里的一些代码和一些我自己拼凑起来的东西,并且不能让这个简单的概念在没有休息之后工作计数并提示用户输入x或o,具体取决于哪个球员正在进行。 我不想使用break,因为这使得我想在以后不可能做到的事情。 代码应该提示用户他们想放置他们的作品的列。如果我使用了一个break语句,但是我不想使用它们,并且在稍后扩展时会使得游戏更难以编码,这一切都可行。 我该如何使这个程序按照现在的方式工作,而没有break语句?我尝试删除break语句,但是在单次输入后使列满。如何在不中断的情况下完成此程序?

def play_spot(column, box, count): 
    column = column - 1 

    for row in reversed(range(len(box))): 
     if box[row][column] == '-' and count % 2 == 0: 
      box[row][column] = 'x' 
      count += 1 
      break 

     if box[row][column] == '-' and count % 2 != 0: 
      box[row][column] = 'o' 
      count += 1 
      break 

    return box, count 


def print_box(box): 
    for row in box: 
     print(''.join(row), end="\n") 
    print() 


def main(): 
    num_rows = int(input("Enter number of rows (5 minimum) :: ")) 
    num_cols = int(input("enter number of columns (5 minimum) :: ")) 
    box = [['-'] * num_cols for _ in range(num_rows)] 
    print_box(box) 
    is_winner = False 
    count = 0 
    while not is_winner: 
     spot = int(input("Enter what column to place piece in :: ")) 
     box, count = play_spot(spot, box, count) 
     print_box(box) 

main() 

我假设对某人姓名的复选标记意味着他们得到了正确答案?所以,如果你帮忙,我想我会给你那个复选标记? :) 注意:目前的代码有效,但我无法按照我想要的方式使用它。如果你想看看我想要的样子,只需调试代码即可。

+2

你能解释一下在其他地方使用'break'会导致什么问题吗? –

+0

从函数中检查'return'(你可以在函数中间执行)并且继续执行for循环....与'break'一起,它们几乎涵盖了你所能做的所有事情:) –

+0

@ScottHunter可能其他的变量应该在条件和'for'循环之后发生......只是猜测:) :) –

回答

1

你可以把你的return声明的副本放在你有每个break,这在技术上解决你的问题,但并不真正改变程序流程。

0

另一种“循环”可能是这样的:

def play_spot(column, box, count): 
    column = column - 1 

    for row in reversed(row for row in box if row[column] == "-") 
     row[column] = 'x' if count % 2 == 0 else 'o' 
     return box, count + 1 
    else: 
     return box, count 

它不是一个真正的循环,你正在做的第一候选人,并使用它,这样你就可以改为做:

def play_spot(column, box, count): 
    column = column - 1 

    try: 
     row = next(reversed(row for row in box if row[column] == "-")) 
     row[column] = 'x' if count % 2 == 0 else 'o' 
     return box, count + 1 
    except StopIteration: 
     return box, count 

如果没有可玩的地方,你有没有考虑过你想要做什么? (这里你直接返回boxcount

相关问题