Skip to content

Instantly share code, notes, and snippets.

@andhieka
Created June 4, 2020 08:15
Show Gist options
  • Save andhieka/a159862d024e0bcd769df0620ce3f8c6 to your computer and use it in GitHub Desktop.
Save andhieka/a159862d024e0bcd769df0620ce3f8c6 to your computer and use it in GitHub Desktop.
MysteryGame - Refactored
import 'dart:io';
abstract class GameState {
String getPrompt();
void process(String input, MysteryGame game);
}
//#region Concrete states
class TheKitchenGameState extends GameState {
static const List<String> KITCHEN_ACTION_LIST = [
'chop',
'chop',
'chop',
'chop',
'chop',
'fry',
'serve',
];
int completedKitchenActionIndex = 0;
@override
String getPrompt() {
if (completedKitchenActionIndex == 0) {
return 'Welcome to The Kitchen. Do your actions without mistake!';
}
}
@override
void process(String input, MysteryGame game) {
if (input == KITCHEN_ACTION_LIST[completedKitchenActionIndex]) {
completedKitchenActionIndex++;
if (completedKitchenActionIndex == KITCHEN_ACTION_LIST.length) {
game.state = SuccessGameState();
}
} else {
game.state = DeadGameState();
}
}
}
class StartGameState extends GameState {
@override
String getPrompt() {
return 'Type ready to start the game';
}
@override
void process(String input, MysteryGame game) {
if (input == 'ready') {
game.state = TheKitchenGameState();
}
}
}
class SuccessGameState extends GameState {
@override
String getPrompt() {
return 'Congratulations! You are successful 🎉';
}
@override
void process(String input, MysteryGame game) {
if (input == 'RIP') {
game.state = DeadGameState();
}
}
}
class DeadGameState extends GameState {
@override
String getPrompt() {
return 'You are dead. Like this game? Feel free to retry.';
}
@override
void process(String input, MysteryGame game) {
if (input == 'retry') {
game.state = StartGameState();
}
}
}
//#endregion
class MysteryGame {
GameState state;
MysteryGame() {
state = StartGameState();
}
String getPrompt() {
return state.getPrompt();
}
void process(String input) {
return state.process(input, this);
}
}
void main() {
print('MysteryMaze v1.0');
print('---');
MysteryGame game = MysteryGame();
while (true) {
if (game.getPrompt() != null) {
print(game.getPrompt());
}
String input = stdin.readLineSync();
if (input == 'exit') {
break;
} else {
game.process(input);
}
}
print('Good bye! Come MysteryMaze again soon!');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment