2016-11-18 47 views
0

我是新來編碼,我試圖編碼基於代碼學院設計的蟒蛇戰艦遊戲。如何顯示和更新變量?

幾乎所有的工作,但板顯示...它打印1第一次,但它不更新,我真的不知道該怎麼辦... 有人可以幫我嗎? (這裏是我的代碼!:))

import random 

def board_ini(): 
    board = [] 
    for x in range(0,5): 
     board.append(["O"] * 5) 
    for row in board: 
     print(" ".join(row)) 
    return board 


def random_row(board): 
    rr = random.randint(0, len(board) - 1) 
    return rr 

def random_col(board): 
    rc = random.randint(0, len(board[0]) - 1) 
    return rc 



def Battleship(): 

    print ("\nLet's play Battleship!\n") 
    print ("You are going to guess coordinate. You can type integers between 0 and 4.\n") 
    print ("You have a total of 4 tries!\n",end ="" "Good luck!!\n") 
    theboard = board_ini() 
    ship_row = random_row(theboard) 
    ship_col = random_col(theboard) 
    print(ship_row) 
    print(ship_col)#debugging 

    for turn in range(1,5): 
     try: 
      guess_row = int(input("Guess Row:")) #let the user try again? 
     except Exception as e: 
      print (e.args) 
     try: 
      guess_col = int(input("Guess Col:")) #let the user try again? 
     except Exception as e: 
      print (e.args) 

     if guess_row == ship_row and guess_col == ship_col: 
      print ("\nCongratulations! You sunk my battleship!") 
      break 
     else: 
      if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4): 
       print ("Oops, that's not even in the ocean.") 
      elif(theboard[guess_row][guess_col] == "X"): 
       print ("You guessed that one already.") 
       turn = turn - 1 #would be nice if it did not count as a turn (turn function ?) 
      else: 
       print ("You missed my battleship!") 
       theboard[guess_row][guess_col] = "X" 

      if turn == 4: 
       print ("\nDefeat, Game over!!") 
       print ("My Ship was in: %s,%s" % (ship_row,ship_col)) 
     turn += 1 
     print ("Turn: %s" % turn) #prints turn 5(it should not) 
     theboard #the board is not displaying correctly (should display the coordinate (X) after each turn but here it does not display at all) 

def Game(): 
    i = True 
    while i == True: 

     Battleship() 

     r = input("Do you want to rematch (Y/N)?") 
     if r == "Y": 
      r.lower() 
      " ".join(r) 
      i = True 
     else: 
      i = False 
      print ("Thank you! Game over") 

Game() 

非常感謝你們!

+0

我已經運行這段代碼。它看起來像工作正常。 – Nurjan

回答

0

您只在board_ini函數中打印該板。我想你想的兩條線

for row in board: 
    print(" ".join(row)) 

複製到的結束for循環在你Battleship功能(但改變boardtheboard)。或者甚至更好,把它放在它自己的print_board函數中。

您還有一個turn的問題。在循環體的末尾做turn += 1沒有任何效果。 for循環已經「排隊」了turn應該採用的所有值,並在每次迭代開始時用新的值覆蓋turn

如果您需要在迭代期間更改循環計數器,則應該考慮使用while循環代替。

+0

非常感謝您迄今順利運作:) –