Enums in Classes
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 44 of 65.
An enum can be declared inside a class, next to its variables. The options then belong to that class:
# weapon.gd
class_name Weapon
extends RefCounted
enum Kind { SWORD, BOW, STAFF }
var kind: Kind
func _init(weapon_kind: Kind) -> void:
kind = weapon_kind
func is_ranged() -> bool:
return kind == Kind.BOW or kind == Kind.STAFFInside weapon.gd the enum is Kind. Every other file writes the class name first, Weapon.Kind.BOW, in values, in type annotations and in match patterns:
# blacksmith.gd
class_name Blacksmith
extends RefCounted
static func repair_cost(kind: Weapon.Kind) -> int:
match kind:
Weapon.Kind.SWORD:
return 20
Weapon.Kind.BOW:
return 15
return 30The options are still numbers: Weapon.new(Weapon.Kind.BOW).kind prints 1. The enum itself works like a dictionary from names to numbers:
print(Weapon.Kind.keys()) # ["SWORD", "BOW", "STAFF"]
print(Weapon.Kind.find_key(1)) # BOW
print(Weapon.Kind["STAFF"]) # 2
print(Weapon.Kind.size()) # 3
for kind in Weapon.Kind.values():
print(Weapon.Kind.find_key(kind), ": ", Blacksmith.repair_cost(kind))The loop prints SWORD: 20, BOW: 15 and STAFF: 30. GDScript does not check that a number is one of the options: Weapon.new(7) creates a weapon whose kind is 7. Pass the named options and the code stays correct.
An enum that describes one class belongs inside that class, so a reader sees where Kind comes from in Weapon.Kind.BOW.
Challenge
EasySort potions with an enum that lives in the Potion class.
- In
potion.gd, declareenum Kind { HEAL, MANA, POISON }and givekindthe typeKind. Potion.from_text(text, strength)is a static function that turns"MANA"intoKind.MANAand returns a new potion.describe()returnsHEAL potion: +20 HP,MANA potion: +15 MPorPOISON potion: -5 HP, using the name of the kind and the strength.- In
belt.gd,summary()returns one line per kind, in the enum's order:HEAL: 2 (35 total), with the number of potions of that kind and, in parentheses, the sum of their strength. Kinds with no potions still get a line.
The supplied code reads how many potions follow (HEAL 20), adds each to the belt, prints its description and then the summary. For HEAL 20, POISON 5, HEAL 15 it prints:
Added HEAL potion: +20 HP
Added POISON potion: -5 HP
Added HEAL potion: +15 HP
HEAL: 2 (35 total)
MANA: 0 (0 total)
POISON: 1 (5 total)Your code goes in potion.gd and belt.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 belt := Belt.new()
var count := int(OS.read_string_from_stdin())
for i in count:
var parts := OS.read_string_from_stdin().split(" ")
var potion := Potion.from_text(parts[0], int(parts[1]))
belt.add(potion)
print("Added ", potion.describe())
for line in belt.summary():
print(line)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self KeywordMethodsPropertiesConstructor (_init)Recap - Simple Calculator4Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator2Class Properties
Instance vs Static VariablesStatic FunctionsProperty SettersProperty GettersPrivate by ConventionRecap - Bank Account Manager5Encapsulation
Public and Private MembersValidation with SettersInformation HidingRead-Only PropertiesRecap - Student Records System8Advanced OOP Concepts
Composition vs InheritanceInner ClassesNodes as ComponentsRefCounted vs NodeEnums in Classes11Project: Library Management
Project OverviewBook and User Classes3Inheritance
Basic InheritanceThe super KeywordMethod OverridingInheritance ChainsType Checks with isRecap - Employee Hierarchy6Special Methods
Virtual Methods IntroductionThe _to_string MethodCustom IteratorsRecap - Custom List9Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy PatternPractice on your own: Online GDScript compiler