Skip to content

Commit

Permalink
Merge pull request #173 from dojoengine/enums
Browse files Browse the repository at this point in the history
add enum section
  • Loading branch information
ponderingdemocritus authored Jan 5, 2024
2 parents 5c2dd05 + 120bcb6 commit 44399b0
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
- [Events](./cairo/events.md)
- [Authorization](./cairo/authorization.md)
- [Metadata](./cairo/metadata.md)
- [Enum](./cairo/enum.md)
- [Migration](./cairo/migration.md)
- [0.2.0 -> 0.3.0](./cairo/migration/0.3.0.md)
- [ECS in 15 minutes](./cairo/hello-dojo.md)
Expand Down
55 changes: 55 additions & 0 deletions src/cairo/enum.md
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)

0 comments on commit 44399b0

Please sign in to comment.