2015-11-27 3 views
0

Я пытаюсь создать программу типа «Броненосец», за исключением костей, помещенных внутри заднего двора. Пользователь должен угадать расположение строк и столбцов костей (точно так же, как в линкоре).Чтение строк из текстового файла и построение графика в массиве

Я хочу, чтобы программа считывала строки кода из текстового файла и использовала эти значения для их построения на моей сетке (без изменения текстового файла). Я не уверен, как это сделать.

Вот что состоит текстовый файл:

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

+0

Возможный дубликат [Как читать числа в текстовом файле с помощью python?] (Http://stackoverflow.com/questions/21285684/how-to-read-numbers-in-text-file-using-python) – Falko

ответ

0

Вы можете сделать это следующим образом:

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

Чтобы прочитать настройки своей игры с file, ваша функция 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']] 

Затем вам нужно будет правильно обрабатывать эти данные ,

Смежные вопросы