如何显示和更新变量?

时间:2016-11-18 11:09:37

标签: python-3.x variables

我是编码新手,我正在尝试基于代码学院设计在python中编写战舰游戏。

几乎所有东西都可以工作但是电路板显示......它首次打印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()

非常感谢!

1 个答案:

答案 0 :(得分:0)

您只在board_ini功能中打印电路板。我想你要复制两行

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

Battleship函数的for循环结束时(但将board更改为theboard)。或者甚至更好,将它放在自己的print_board函数中。

turn也遇到问题。在循环体末端执行turn += 1无效。 for循环已经“排队”了turn应该采用的所有值,并在每次迭代开始时用新的覆盖turn

如果需要在迭代期间更改循环计数器,则应考虑使用while循环。