Skip to content

Instantly share code, notes, and snippets.

@amirulabu
Created November 29, 2019 03:05
Show Gist options
  • Save amirulabu/956fb1729a726a8767607141a821c4f0 to your computer and use it in GitHub Desktop.
Save amirulabu/956fb1729a726a8767607141a821c4f0 to your computer and use it in GitHub Desktop.
trying to translate c++ codes to dart from here http://gameprogrammingpatterns.com/command.html#configuring-input
// trying to translate c++ codes to dart
// http://gameprogrammingpatterns.com/command.html#configuring-input
void main() {
print("Starting game\n");
JumpCommand jumpCommand = JumpCommand();
FireCommand fireCommand = FireCommand();
WalkCommand walkCommand = WalkCommand();
BlockCommand blockCommand = BlockCommand();
InputHandler inputHandler = InputHandler(
buttonX: jumpCommand,
buttonY: fireCommand,
buttonA: walkCommand,
buttonB: blockCommand,
);
print("Press button A");
inputHandler.pressed = Button.BUTTON_A;
inputHandler.handleInput();
print("Press button X");
inputHandler.pressed = Button.BUTTON_X;
inputHandler.handleInput();
print("Press button Y");
inputHandler.pressed = Button.BUTTON_Y;
inputHandler.handleInput();
}
abstract class Command {
void execute();
}
class JumpCommand extends Command {
void execute() {
print("Lets jump!\n");
}
}
class FireCommand extends Command {
void execute() {
print("Fire!!!\n");
}
}
class WalkCommand extends Command {
void execute() {
print("Walking\n");
}
}
class BlockCommand extends Command {
void execute() {
print("Blocking...\n");
}
}
enum Button {
BUTTON_X,
BUTTON_Y,
BUTTON_A,
BUTTON_B,
NULL,
}
class InputHandler {
Command buttonX;
Command buttonY;
Command buttonA;
Command buttonB;
Button pressed;
InputHandler({
this.buttonX,
this.buttonY,
this.buttonA,
this.buttonB,
});
void handleInput() {
if (isPressed(Button.BUTTON_X)) return buttonX.execute();
if (isPressed(Button.BUTTON_Y)) return buttonY.execute();
if (isPressed(Button.BUTTON_A)) return buttonA.execute();
if (isPressed(Button.BUTTON_B)) return buttonB.execute();
// 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