Skip to content

Instantly share code, notes, and snippets.

@Mercerenies
Created January 9, 2020 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mercerenies/26831fb608abf2876ebdaede3285da63 to your computer and use it in GitHub Desktop.
Save Mercerenies/26831fb608abf2876ebdaede3285da63 to your computer and use it in GitHub Desktop.
%% -*- Prolog -*-
% A very simple "toothpicks" game in Prolog. Two players take turns
% drawing one, two, or three toothpicks from a stack. If you take the
% last one, then you lose. I made this late one night, mainly to prove
% to myself that game programming is actually possible in Prolog.
:-
use_module(library(readutil)).
player(player1).
player(player2).
other_player(player1, player2).
other_player(player2, player1).
game_state(game_state(Toothpicks, Turn_Player)) :-
integer(Toothpicks),
player(Turn_Player).
starting_state(N, game_state(N, player1)).
state_player(game_state(_, Turn_Player), Turn_Player).
state_toothpicks(game_state(Toothpicks, _), Toothpicks).
next_player(game_state(T, Player0), game_state(T, Player1)) :-
other_player(Player0, Player1).
remove_toothpicks(game_state(Toothpicks0, P), game_state(Toothpicks1, P), N) :-
Toothpicks1 is max(Toothpicks0 - N, 0).
read_number(Amount) :-
current_input(Stdin),
read_line_to_string(Stdin, String),
(number_string(Amount, String), Amount >= 1, Amount =< 3) ; read_number(Amount),
!.
ask_for_player_input(State, Amount) :-
state_player(State, Turn_Player),
state_toothpicks(State, Toothpicks),
writef("%w, it is your turn. There are %w toothpicks. How many would you like to take (up to 3?)\n", [Turn_Player, Toothpicks]),
read_number(Amount).
play_turn(State0, State2) :-
ask_for_player_input(State0, Amount),
remove_toothpicks(State0, State1, Amount),
next_player(State1, State2),
!.
end_of_game(State) :-
state_toothpicks(State, Toothpicks),
Toothpicks =:= 0.
play_game(State0, Winner) :-
end_of_game(State0) ->
state_player(State0, Winner) ;
(
play_turn(State0, State1),
play_game(State1, Winner)
).
:-
starting_state(15, State),
play_game(State, Winner),
writef("%w wins! Congratulations!\n", [Winner]),
halt.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment