看到從這個網站製作一個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()
我假設對某人姓名的複選標記意味着他們得到了正確答案?所以,如果你幫忙,我想我會給你那個複選標記? :) 注意:目前的代碼有效,但我無法按照我想要的方式使用它。如果你想看看我想要的樣子,只需調試代碼即可。
你能解釋一下在其他地方使用'break'會導致什麼問題嗎? –
從函數中檢查'return'(你可以在函數中間執行)並且繼續執行for循環....與'break'一起,它們幾乎涵蓋了你所能做的所有事情:) –
@ScottHunter可能其他的變量應該在條件和'for'循環之後發生......只是猜測:) :) –