簡體   English   中英

從文本文件讀取行並在數組中繪圖

[英]Reading lines from a text file and plotting in array

我正在嘗試創建類似戰艦的程序,只是將骨頭放置在后院內。 用戶將不得不猜測骨頭的行和列位置(就像在戰艦上一樣)。

我希望程序從文本文件中讀取代碼行,並使用這些值在我的網格上繪制它們(而無需修改文本文件)。 我不確定如何去做。

文本文件包含以下內容:

12 12 4 4
0 7 0 8 0 9 0 10
2 4 3 4 5 4 6 4
0 0 1 0 2 0 3 0
11 11 10 11 9 11 8 11

第1行包含網格的寬度(12)和高度(12),骨骼數量(4)和骨骼長度(4)。 第2到5行包含以下格式的4條骨骼的位置:

<cell1_row> <cell1_col> <cell2_row> <cell2_col> <cell3_row> <cell3_col><cell4_row> <cell4_col>

到目前為止,我已經了解了它的基本結構,但缺少了一些核心功能。

我想知道如何從文本文件中讀取游戲數據並在程序中使用它。

def getData(gameFile):
    """Pulling our bone information from the game text file"""
    file = open (gameFile, 'r')
    gameData = [line.strip('\n').split(' ') for line in file.readlines()]

不知道這是如何正確使用它^。 以下是我開始從事的工作!

#variables
bones = list()
backyardWidth = 12
backyardHeight = 12
numOfBones = 4
boneLength = 4
gameFile = "FBI_the_Game_Data_2.txt"

def createBackyard(aWidth, aHeight):
    """ Create and return an empty "backyard" of aWidth by aHeight."""
    aBackyard = [ [ " . " for i in range(backyardWidth) ] for j inrange(backyardHeight) ]   
    return aBackyard

def displayBackyard(aBackyard, aWidth, aHeight):
    """Creates a backyard with no bones."""
    print("\nThere are 4 bones, each are 4 cells long, buried in this backyard! Can you find them?")
    aString = " "
    for column in range(0, aWidth):
        aString = aString + str(column) + " "
        if len(str(column)) == 1 :
            aString += " "           
    print(aString)
    for row in range(0, aHeight):
       print(unpack(aBackyard, row))

def unpack(aBackyard, row):
    """ Helper function.
        Unpack a particular row of the backyard, i.e., make a string out of it.
    """
    aString = ""
    for i in range(backyardWidth):
        aString += aBackyard[row][i]
    # Add a column (from 1 to aHeight) to the right of a backyard row
    aString = aString + " " + str(row)
    return aString

# main
print("""Welcome to Fast Bone Investigation (FBI) the game.
In this game, we dig out bones from Mrs. Hudson's backyard!""")

# Create backyards     
displayedBackyard = createBackyard(backyardWidth, backyardHeight)

# Display the backyard
app_on = True

while app_on:
    displayBackyard(displayedBackyard, backyardWidth, backyardHeight)

    choice = input(("""\nTo do so, please, enter the row and the column number of a cell in which you suspect a bone is buried
(e.g., 0 3 if you suspect that part of a bone is buried on the first row at the 4th column).
Enter -1 to quit: """))

    # if user enters nothing
    if len( choice ) == 0 :
        print("***You have not entered anything. You need to enter a valid row and the column number!\n")
    elif len( choice ) == 1 :
        print("***You have entered only 1 value. You need to enter a valid row and the column number!\n")
    elif choice == "-1":
        app_on = False
    # if the user enters any alphabet     
    elif choice.isalpha( ):
        print("***You have entered %s. You need to enter a valid row and the column number!\n" %choice)
    elif "." in choice :
        print("***You have entered %s. You need to enter a valid row and the column number!\n" %choice)
    else:
        userGuess = int(choice)
        if userGuess > backyardHeight or backyardWidth or userGuess < 0:
            print("You needed to enter a row and column number of a cell that is within the backyard!\n")

##   Unfinished Beeswax
##      elif choice == 
##            print("****HIT!!!!****")
        else:
            print("****OOPS! MISSED!****")

print("\nWasn't it fun! Bye!")

在程序開始時,所有骨頭現在都應該被埋沒,並且玩家無法看到。 然后,隨着游戲的執行,要求玩家通過輸入后院中一個單元的行號和列號來猜測骨頭被埋在哪里。 如果確實在此單元格中掩埋了骨骼部分,則該部分骨骼在此單元格中顯示“ B”。

以下是該程序的示例:

在此處輸入圖片說明

您可以這樣操作:

def getData(gameFile):
    """Pulling our bone information from the game text file"""
    file = open (gameFile, 'r')
    gameData = [line.strip('\n').split(' ') for line in file.readlines()]
    backyardWidth = int(gameData[0][0])
    backyardHeight = int(gameData[0][1])
    nbBones = int(gameData[0][2])
    boneLength = int(gameData[0][3])
    bones = []
    for i in range(nbBones):
        bones.append([int(gameData[i+1][j]) for j in range(boneLength*2)])
    return backyardWidth, backyardHeight, nbBones, boneLength, bones

如果然后您print getData('FBI.txt')則返回:

(12, 12, 4, 4, 
[[0, 7, 0, 8, 0, 9, 0, 10], [2, 4, 3, 4, 5, 4, 6, 4], [0, 0, 1, 0, 2, 0, 3, 0], [11, 11, 10, 11, 9, 11, 8, 11]])

為了從文件中讀取游戲設置,您的getData()函數需要返回已讀取的數據。從文件中讀取數據時,最好使用Python的with命令,以確保使用后始終正確關閉文件。

然后, gameData保留一個列表列表,文本文件中的每一行一個。 第一行(第0行)保存您的參數,其余行保存骨骼位置。 這些都可以分配給您的變量,如下所示:

def getData(gameFile):
    """Pulling our bone information from the game text file"""

    with open(gameFile) as f_input:
        gameData = [line.strip('\n').split(' ') for line in f_input.readlines()]

    return gameData

gameData = getData("FBI_the_Game_Data_2.txt")

#variables
backyardWidth, backyardHeight, numOfBones, boneLength = gameData[0]
bones = gameData[1:]

因此,使用示例文本文件,您的變量將包含以下值:

backyardWidth = 12
backyardHeight = 12
numOfBones = 4
boneLength = 4

bones = [['0', '7', '0', '8', '0', '9', '0', '10'], ['2', '4', '3', '4', '5', '4', '6', '4'], ['0', '0', '1', '0', '2', '0', '3', '0'], ['11', '11', '10', '11', '9', '11', '8', '11']]

然后,您將需要正確處理此數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM