diff --git a/scissors/scissors_game/Makefile b/scissors/scissors_game/Makefile new file mode 100644 index 00000000..b411d57c --- /dev/null +++ b/scissors/scissors_game/Makefile @@ -0,0 +1,6 @@ +CC=gcc +SOURCES=main.c scissors.c +EXECUTABLE=scissors_game + +all: $(SOURCES) + $(CC) $(SOURCES) -o $(EXECUTABLE) diff --git a/scissors/scissors_game/main.c b/scissors/scissors_game/main.c new file mode 100644 index 00000000..0a5b9e16 --- /dev/null +++ b/scissors/scissors_game/main.c @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: GPL-2.0 +#include +#include +#include "scissors.h" + +static const char * const Game_Elements[] = { + "rock", "paper", "scissors", "unknown"}; + +int main(void) +{ + char input; + int res; + int comp_choise; + + init_scissors(); + do { + printf("Please choose: rock (r) - paper (p) - scissors (s)\n"); + scanf("%1s", &input); + res = char_to_element_index(input); + if (res == UNKNOWN) { + printf("You've chosen something strange!\n"); + continue; + } + comp_choise = play_scissors(); + printf("You choose %s, I choose %s\n", + Game_Elements[res], Game_Elements[comp_choise]); + switch (get_game_result(res, comp_choise)) { + case LOST: + printf("I win: %s beats %s\n", + Game_Elements[comp_choise], Game_Elements[res]); + break; + case WINN: + printf("You win: %s beats %s\n", + Game_Elements[res], Game_Elements[comp_choise]); + break; + case DRAW: + printf("It's draw\n"); + break; + } + } while (1); +} + diff --git a/scissors/scissors_game/scissors.c b/scissors/scissors_game/scissors.c new file mode 100644 index 00000000..d4693c20 --- /dev/null +++ b/scissors/scissors_game/scissors.c @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: GPL-2.0 +#include +#include +#include "scissors.h" + +/* + * Table indicates user's lost or win + * The row index corresponds to user's choise + * The column index corresponds to comp's choice + */ + +static const int game_table[3][3] = { +/* rock paper scissors */ +/* rock*/ DRAW, LOST, WINN, +/* paper*/ WINN, DRAW, LOST, +/* sciss*/ LOST, WINN, DRAW +}; + +int char_to_element_index(char c) +{ + int ans = UNKNOWN; + + switch (c) { + case 'r': + ans = ROCK; + break; + case 'p': + ans = PAPER; + break; + case 's': + ans = SCISSORS; + break; + } + return ans; +} + +void init_scissors(void) +{ + srand(time(NULL)); +} + +int play_scissors(void) +{ + return (rand()%3); +} + +int get_game_result(int user, int comp) +{ + return game_table[user][comp]; +} diff --git a/scissors/scissors_game/scissors.h b/scissors/scissors_game/scissors.h new file mode 100644 index 00000000..9e922147 --- /dev/null +++ b/scissors/scissors_game/scissors.h @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: GPL-2.0 + +#define ROCK 0 +#define PAPER 1 +#define SCISSORS 2 +#define UNKNOWN 3 +#define DRAW 0 +#define LOST 1 +#define WINN 2 + +int char_to_element_index(char c); +void init_scissors(void); +int play_scissors(void); +int get_game_result(int user, int comp);