Last active
November 29, 2019 07:33
-
-
Save amirulabu/387c1d955f1d127a7f617392320c90bc to your computer and use it in GitHub Desktop.
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
// trying to translate c++ codes to dart | |
// c++ source: | |
// http://gameprogrammingpatterns.com/command.html#undo-and-redo | |
void main() { | |
print("Starting game\n"); | |
Unit unit = Unit(x: 0, y: 0); | |
InputHandler inputHandler = InputHandler(unit: unit); | |
Command command; | |
print("Press button up"); | |
inputHandler.pressed = Button.BUTTON_UP; | |
inputHandler.handleInput() | |
..execute(); | |
print("Press button up"); | |
inputHandler.pressed = Button.BUTTON_UP; | |
inputHandler.handleInput() | |
..execute(); | |
print("Press button down"); | |
inputHandler.pressed = Button.BUTTON_DOWN; | |
inputHandler.handleInput() | |
..execute(); | |
print("Lets undo"); | |
command.undo(); | |
} | |
class Unit { | |
int x; | |
int y; | |
Unit({this.x, this.y}); | |
void moveTo(int xNew, int yNew) { | |
x = xNew; | |
y = yNew; | |
} | |
} | |
abstract class Command { | |
void execute(); | |
void undo(); | |
} | |
class MoveUnitCommand extends Command { | |
int x; | |
int y; | |
int xBefore; | |
int yBefore; | |
Unit unit; | |
MoveUnitCommand({this.unit, this.x, this.y}); | |
void execute() { | |
xBefore = unit.x; | |
yBefore = unit.y; | |
print("position: $x, $y\n"); | |
unit.moveTo(x, y); | |
} | |
void undo() { | |
print("position: $xBefore, $yBefore\n"); | |
unit.moveTo(xBefore, yBefore); | |
} | |
} | |
enum Button { | |
BUTTON_UP, | |
BUTTON_DOWN, | |
BUTTON_UNDO, | |
NULL, | |
} | |
class InputHandler { | |
Unit unit; | |
Button pressed; | |
InputHandler({this.unit}); | |
Command handleInput() { | |
if (isPressed(Button.BUTTON_UP)) { | |
int destY = unit.y + 1; | |
return MoveUnitCommand(unit: unit, x: unit.x, y: destY); | |
} | |
if (isPressed(Button.BUTTON_DOWN)) { | |
int destY = unit.y - 1; | |
return MoveUnitCommand(unit: unit, x: unit.x, y: destY); | |
} | |
// Nothing pressed, so do nothing. | |
return null; | |
} | |
bool isPressed(Button button) { | |
return button == pressed ? true : false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment