从文本文件中读取行并在数组中打印

2024-10-04 03:21:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个类似战舰的程序,只是把骨头放在后院里。用户必须猜测骨骼的行和列位置(就像在战舰中一样)。你知道吗

我希望程序从文本文件中读取代码行,并使用这些值在我的网格中绘制它们(不修改文本文件)。不过,我不知道该怎么办。你知道吗

以下是文本文件的组成:

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”。你知道吗

以下是该程序的示例:

enter image description here


Tags: andofthetoinyouforcolumn
2条回答

你可以这样做:

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

然后需要正确处理这些数据。你知道吗

相关问题 更多 >