Menu
CoddyTech

Recap - Health System

Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 39 of 65.

challenge icon

Challenge

Easy

Build a health system in which the health component announces every change and a health bar reacts to it.

Health (health.gd) stores max_hp and hp (both start at the value given to the constructor) and declares three signals: damaged(amount, hp), healed(amount, hp) and died.

  • take_damage(amount) lowers hp, never below 0, and emits damaged with the HP actually lost and the new hp. When hp reaches 0, it also emits died.
  • heal(amount) raises hp, never above max_hp, and emits healed with the HP actually restored and the new hp. Healing at full health emits nothing.
  • Once hp is 0, both methods do nothing.

HealthBar (health_bar.gd) has watch(health), which connects all three signals to its own methods. They print -8 HP [12/20], +5 HP [17/20] and Game over. The bar stores the maximum HP it needs as a number; do not keep a reference to the Health object.

The supplied code reads the maximum HP and how many commands follow (damage 8, heal 5), then prints the final HP. For a maximum of 20 and damage 8, heal 5, heal 10, damage 30, heal 5 it prints:

-8 HP [12/20]
+5 HP [17/20]
+3 HP [20/20]
-20 HP [0/20]
Game over
Final HP: 0

Your code goes in health.gd and health_bar.gd. main.gd holds the supplied input/output code and cannot be edited.

Try it yourself

extends Node

func _ready():
	# Supplied input/output code: keep it as it is
	var health := Health.new(int(OS.read_string_from_stdin()))
	var bar := HealthBar.new()
	bar.watch(health)
	var count := int(OS.read_string_from_stdin())
	for i in count:
		var parts := OS.read_string_from_stdin().split(" ")
		if parts[0] == "damage":
			health.take_damage(int(parts[1]))
		elif parts[0] == "heal":
			health.heal(int(parts[1]))
	print("Final HP: ", health.hp)

All lessons in Object Oriented Programming

Practice on your own: Online GDScript compiler