Menu
CoddyTech

Properties

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

The variables a class declares are its properties (also called member variables): the data every object carries. Declare them at the top of the class, each with a type and a starting value:

# player.gd
class_name Player
extends RefCounted

var player_name: String = "Hero"
var level: int = 1
var hp: float = 100.0
var inventory: Array[String] = []

A property declared without a value starts at the default of its type: 0 for int, "" for String, false for bool and an empty array for Array[String].

Outside the class you read and change a property with a dot. Inside the class's methods you use its name:

var p := Player.new()
p.level += 1
p.inventory.append("sword")
print(p.level) # 2
print(p.inventory) # ["sword"]

Every object gets its own copy of each property, arrays included: the [] creates a new empty array for each player, so another player's inventory stays empty.

The type is checked: p.level = "max" is an error reported before the program runs, because level holds an int.

challenge icon

Challenge

Easy

Complete the class Player in player.gd. Declare these properties:

  • player_name, a String that starts as "Hero"
  • level, an int that starts at 1
  • hp, an int that starts at 100
  • inventory, an Array[String] that starts empty

Then complete the method describe(). It returns NAME (level LEVEL, HP hp): ITEMS, where ITEMS is the inventory joined with ", ", or no items when the inventory is empty.

The supplied code reads a name for one player, then how many commands follow, then the commands: hit AMOUNT, item NAME or level. It changes the player's properties directly and finally prints describe() for that player and for a second player it never changed. For Ada and the commands hit 30, item sword, level and item shield it prints:

Ada (level 2, 70 hp): sword, shield
Hero (level 1, 100 hp): no items

Your code goes in player.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 hero := Player.new()
	hero.player_name = OS.read_string_from_stdin()
	var guest := Player.new()
	var count := int(OS.read_string_from_stdin())
	for i in count:
		var parts := OS.read_string_from_stdin().split(" ")
		match parts[0]:
			"hit":
				hero.hp -= int(parts[1])
			"item":
				hero.inventory.append(parts[1])
			"level":
				hero.level += 1
	print(hero.describe())
	print(guest.describe())
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online GDScript compiler