-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStateMachineExample.c
More file actions
113 lines (105 loc) · 3.17 KB
/
StateMachineExample.c
File metadata and controls
113 lines (105 loc) · 3.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include "StateMachineExample.h"
void* top(StateMachine *sm, Event e)
{
switch (e.type)
{
case EVENT_ENTRY:
printf("ENTRY in state: %s\n", __func__);
// Allocate statemachine data
sm->data = malloc(sizeof(StateMachineData));
return NULL;
case EVENT_INIT:
printf("INIT in state: %s\n", __func__);
transitionTo(sm, playerAlive);
return NULL;
case EVENT_EXIT:
printf("EXIT in state: %s\n", __func__);
// Deallocate statemachine data
free(sm->data);
return NULL;
case EVENT_PLAYER_DEAD:
transitionTo(sm, playerDead);
return NULL;
case EVENT_MOUSE_POSITION:
MousePosition *mp = (MousePosition*)e.data;
printf("Mouse position: x: %d, y: %d\n", mp->x, mp->y);
sm->data->mousePosition = (MousePosition){mp->x, mp->y};
free(e.data); // We the catcher of the event is responsible for freeing the data when its done with it
return NULL;
default:
if (e.type != EVENT_NULL) ("!!!Uncaught event %d in state: %s\n", e.type, __func__);
break;
}
return NULL;
}
void* playerAlive(StateMachine *sm, Event e)
{
switch (e.type)
{
case EVENT_ENTRY:
printf("ENTRY in state: %s\n", __func__);
return NULL;
case EVENT_EXIT:
printf("EXIT in state: %s\n", __func__);
return NULL;
case EVENT_LEFT_ARROW_DOWN:
transitionTo(sm, playerMovingLeft);
return NULL;
case EVENT_RIGHT_ARROW_DOWN:
transitionTo(sm, playerMovingRight);
return NULL;
}
return top;
}
void* playerMovingLeft(StateMachine *sm, Event e)
{
switch (e.type)
{
case EVENT_ENTRY:
printf("ENTRY in state: %s\n", __func__);
// Code that starts moving the player left
return NULL;
case EVENT_EXIT:
printf("EXIT in state: %s\n", __func__);
// Code that stops moving the player left
return NULL;
case EVENT_LEFT_ARROW_UP:
transitionTo(sm, playerAlive);
return NULL;
}
return playerAlive;
}
void* playerMovingRight(StateMachine *sm, Event e)
{
switch (e.type)
{
case EVENT_ENTRY:
printf("ENTRY in state: %s\n", __func__);
// Code that starts moving the player right
return NULL;
case EVENT_EXIT:
printf("EXIT in state: %s\n", __func__);
// Code that stops moving the player right
return NULL;
case EVENT_RIGHT_ARROW_UP:
transitionTo(sm, playerAlive);
return NULL;
}
return playerAlive;
}
void* playerDead(StateMachine *sm, Event e)
{
switch (e.type)
{
case EVENT_ENTRY:
printf("ENTRY in state: %s\n", __func__);
return NULL;
case EVENT_EXIT:
printf("EXIT in state: %s\n", __func__);
return NULL;
case EVENT_RESPAWN:
transitionTo(sm, playerAlive);
return NULL;
}
return top;
}