Working with json file

extends Node2D
var player_words = [] # the players words
var introduction = "Welcome to Silly songs!\n\nLets write a strange tune.\nGive me some words and I'll write some prose.\n\n\nLets start with a noun."

var current_story

func _ready():
	set_random_story()
	$Blackboard/StoryText.text = introduction
	$Blackboard/TextBox.grab_focus()
	$Blackboard/TextureButton/ButtonTextOK.text = "Enter"

func set_random_story():
	var songs = get_from_json("songs.json")
	randomize()
	current_story = songs[randi() % songs.size()]

func get_from_json(filename):
	var file = File.new() #the file object
	file.open(filename, File.READ) #Assumes the file exists
	var text = file.get_as_text()
	var data = parse_json(text)
	file.close()
	return data
	

func _on_TextureButton_pressed():
	if is_story_done():
		get_tree().reload_current_scene()
	else:
		_on_TextBox_text_entered($Blackboard/TextBox.get_text())

func _on_TextBox_text_entered(new_text):
	if new_text != "":
		player_words.append(new_text)
		$Blackboard/StoryText.text = new_text
		$Blackboard/TextBox.clear()
		check_player_word_length()

func is_story_done():
	return player_words.size() == current_story.prompt.size()

func prompt_player():
	$Blackboard/StoryText.text = ("Can I have " + current_story.prompt[player_words.size()] + ", please?")

func check_player_word_length():
	if is_story_done():
		tell_story()
	else:
		prompt_player()

func tell_story():
	$Blackboard/StoryText.text = current_story.song % player_words
	end_game()

func end_game():
	$Blackboard/TextBox.queue_free()
	$Blackboard/TextureButton/ButtonTextOK.text = "Again"

Thanks. this is a great lesson. File saving and writing will be very important in the future dev.

Privacy & Terms