简体   繁体   English

从文本文件读取行并在数组中绘图

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

I'm trying to create a Battleship-like program except with bones placed inside a backyard instead. 我正在尝试创建类似战舰的程序,只是将骨头放置在后院内。 The user will have to guess the row and column location of the bones (just like in battleship). 用户将不得不猜测骨头的行和列位置(就像在战舰上一样)。

I want the program to read the lines of code from a text file and using these values to plot them on my grid (without modifying the text file). 我希望程序从文本文件中读取代码行,并使用这些值在我的网格上绘制它们(而无需修改文本文件)。 I'm not sure how to go about it though. 我不确定如何去做。

Here's what the text file consists: 文本文件包含以下内容:

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

Line 1 contains the width (12) and the height (12) of the grid, the number of bones (4) and the length of our bones (4). 第1行包含网格的宽度(12)和高度(12),骨骼数量(4)和骨骼长度(4)。 Lines 2 to 5 contain the location of our 4 bones in the following format: 第2到5行包含以下格式的4条骨骼的位置:

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

So far, I have the basic structure of what it's supposed to look like but I'm missing some core functions. 到目前为止,我已经了解了它的基本结构,但缺少了一些核心功能。

I want to know how to read the game data from the text file and use it in my program. 我想知道如何从文本文件中读取游戏数据并在程序中使用它。

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()]

Not sure if this is how to use it correctly^. 不知道这是如何正确使用它^。 Below is what I've started working on! 以下是我开始从事的工作!

#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!")

At the start of the program, all bones should now be buried and cannot be seen by the player. 在程序开始时,所有骨头现在都应该被埋没,并且玩家无法看到。 Then, as the game executes, the player is asked to guess where the bones are buried by entering the row number and the column number of a cell in the backyard. 然后,随着游戏的执行,要求玩家通过输入后院中一个单元的行号和列号来猜测骨头被埋在哪里。 If a bone section is indeed buried at this cell, this section of the bone displays a “ B ” in this cell. 如果确实在此单元格中掩埋了骨骼部分,则该部分骨骼在此单元格中显示“ B”。

Here is a sample of what the program does: 以下是该程序的示例:

在此处输入图片说明

You can do it this way: 您可以这样操作:

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

If then you print getData('FBI.txt') this returns: 如果然后您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]])

In order to read your game settings from the file, your getData() function needs to return the data it has read in. When reading from a file, it is best to use Python's with command which ensures the file is always correctly closed after use. 为了从文件中读取游戏设置,您的getData()函数需要返回已读取的数据。从文件中读取数据时,最好使用Python的with命令,以确保使用后始终正确关闭文件。

gameData then holds a list of lists, one for each row in your text file. 然后, gameData保留一个列表列表,文本文件中的每一行一个。 The first row (row 0) holds your parameters, and the remaining rows, the bone locations. 第一行(第0行)保存您的参数,其余行保存骨骼位置。 These can all be assigned to your variables as follows: 这些都可以分配给您的变量,如下所示:

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:]

So using your sample text file, your variables will hold the following values: 因此,使用示例文本文件,您的变量将包含以下值:

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']]

You will then need to handle this data correctly. 然后,您将需要正确处理此数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM