Defining an Enum
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 38 of 78.
An enum declaration is the keyword enum, a name and the options inside curly braces, separated by commas. The Godot style guide writes the name in PascalCase and the options in CONSTANT_CASE:
enum Direction { NORTH, EAST, SOUTH, WEST }A long enum can put one option per line. A comma after the last option is allowed:
enum Weapon {
SWORD,
BOW,
STAFF,
}You can choose the value of an option with =. An option without a value gets the value of the option before it plus 1:
enum Difficulty { EASY = 1, NORMAL, HARD, NIGHTMARE = 10 }
# EASY = 1, NORMAL = 2, HARD = 3, NIGHTMARE = 10The enum is also a type. A variable declared with it holds one of its options:
var level: Difficulty = Difficulty.HARD
print(level) # 3
print(level * 50) # 150A script can declare several enums, each with its own name. If you leave the name out, as in enum { LEFT, RIGHT }, the options become constants of the script, and you write LEFT without a prefix.
Challenge
EasyThe program reads the base damage of an enemy (a whole number). On harder difficulties the enemy hits harder: the damage is the base damage times the value of the difficulty.
- At the top level of the script, declare an enum named
Difficultywith the optionsEASY(value1),NORMAL,HARDandNIGHTMARE(value10). GiveNORMALandHARDno value of their own, so they count on fromEASY. - Print the damage for each difficulty, one per line, using the enum options in the calculation.
For the input 12, the output is:
EASY: 12
NORMAL: 24
HARD: 36
NIGHTMARE: 120Try it yourself
extends Node
# Declare the Difficulty enum here
func _ready():
var base_damage := int(OS.read_string_from_stdin())
# Print the damage for each difficulty
pass
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler