How can you make godot read from a file, take a random line and assign it to a variable?

ibouvousaimeibouvousaime Posts: 2Member
edited September 2016 in Programming
Is trying to make my godot game take some words in a text file I have (every word is on its own line and every line only one word), the file has 400 lines/words, so how would I go into making godot read that file and take one random word from it ?
I managed to get that with java before but I dont find a way to do it with gdscript,

Tags :


  • 1000h1000h Posts: 133Member
    edited August 2016 Answer ✓
    EDITED: In order to find a specific char, use the string class, which you can use to find spaces with .match() and in turn allow you find beginning and end of words

    Hello! I can answer this question for you, although I have not tested, this is generally it

    var file_path = 'res://file.txt' #have the file path

    var file = #new file class on which you will call file class methods,file.READ)  #the file is now opened in the background

    var line_counter = 0 #an integer to count the lines

    while !eof_reached(): #this loops through each line until the file end is reached
    line_counter+=1 #as its doing so, before getting the next line, it adds a counter
    file.get_line() #sets the file read cursor to the next line #this is now outside of the former loop.  after the loop, reset the cursor position

    var random_last_line = randi() % line_counter # integer generated that is equal to line 0, to a random line counted

    var store_line = '' #the varialbe that will store the line is an empty string for now

    for i in range(0,random_last_line):
    store_line = file.get_line() #randomly get a line, which is now set to store_line string variable

  • ibouvousaimeibouvousaime Posts: 2Member
    Thanks a lot! it helped me get the result I wanted :)
  • 1000h1000h Posts: 133Member
    Cool, I've edited it a few times so I don't know which version you saw, but in short, File class and String class
  • HoragallesHoragalles Posts: 6Member

    How do you get it to store on a different line each time its called?

Sign In or Register to comment.