-
Notifications
You must be signed in to change notification settings - Fork 78
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #173 from dojoengine/enums
add enum section
- Loading branch information
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
## Enum | ||
|
||
Enums are very useful in game design, as they simplify the creation of clean, complex logic. | ||
|
||
You can define an enum as follows: | ||
|
||
```rust,ignore | ||
// This enum simply defines the states of a game. | ||
#[derive(Serde, Copy, Drop, Introspect, PartialEq, Print)] | ||
enum GameStatus { | ||
NotStarted: (), | ||
Lobby: (), | ||
InProgress: (), | ||
Finished: (), | ||
} | ||
// We define an into trait | ||
impl GameStatusFelt252 of Into<GameStatus, felt252> { | ||
fn into(self: GameStatus) -> felt252 { | ||
match self { | ||
GameStatus::NotStarted => 0, | ||
GameStatus::Lobby => 1, | ||
GameStatus::InProgress => 2, | ||
GameStatus::Finished => 3, | ||
} | ||
} | ||
} | ||
``` | ||
|
||
Then within a trait you can create something like this: | ||
|
||
```rust,ignore | ||
#[derive(Model, Copy, Drop, Serde)] | ||
struct Game { | ||
#[key] | ||
game_id: u32, | ||
status: GameStatus, | ||
} | ||
#[generate_trait] | ||
impl GameImpl of GameTrait { | ||
fn assert_in_progress(self: Game) { | ||
assert(self.status == GameStatus::InProgress, "Game not started"); | ||
} | ||
fn assert_lobby(self: Game) { | ||
assert(self.status == GameStatus::Lobby, "Game not in lobby"); | ||
} | ||
fn assert_not_started(self: Game) { | ||
assert(self.status == GameStatus::NotStarted, "Game already started"); | ||
} | ||
} | ||
``` | ||
|
||
> Read more about Cairo enums [here](https://book.cairo-lang.org/ch06-00-enums-and-pattern-matching.html) |