Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 1.54 KB | None | 0 0
  1. choose_word(Word) :-
  2.     findall(X, w(X), List),
  3.     length(List, Len),
  4.     random(0, Len, Index),
  5.     nth0(Index, List, Word).
  6.  
  7. create_stars(0,'').
  8. create_stars(N,Str) :-
  9.     M is N-1,
  10.     create_stars(M,Str2),
  11.     string_concat('*',Str2,Str), !.
  12.    
  13. init_play() :-
  14.     choose_word(Word),
  15.     string_length(Word,N),
  16.     create_stars(N,Stars),
  17.     play(Word,Stars,0).
  18.    
  19. play(RightWord, GuessedWord, Tries) :-
  20.     writeln(''),
  21.     TriesNext is Tries+1,
  22.     write('Please guess the word: '), writeln(GuessedWord),
  23.     write('Please guess a letter: '),
  24.     get_single_char(C), char_code(Guess,C),
  25.     atom_chars(RightWord, WordCharacters),
  26.     findall(Ind, nth0(Ind,WordCharacters,Guess), Indices),
  27.     replace_str(GuessedWord, Indices, Guess, NewGuessedWord),
  28.     (RightWord=NewGuessedWord ->
  29.         end_game(TriesNext);
  30.         play(RightWord, NewGuessedWord, TriesNext)), !.
  31.    
  32. replace_str(Str, Ind, Guess, RetStr) :-
  33.     atom_chars(Str, StrChars),
  34.     length(StrChars, Len),
  35.     LastIndex is Len-1,
  36.     replace_list(StrChars, Ind, Guess, LastIndex, RetList),
  37.     atom_chars(RetStr,RetList).
  38.  
  39. replace_list(_, _, _, -1, []).
  40. replace_list(CharList, Indices, Guess, Index, RetList) :-
  41.      nth0(Index,CharList,Char),
  42.      Index2 is Index-1,
  43.      replace_list(CharList, Indices, Guess, Index2, RetList2),
  44.      (member(Index,Indices) ->
  45.          append(RetList2,[Guess],RetList) ;
  46.          append(RetList2,[Char],RetList )), !.
  47.          
  48. end_game(Tries) :-
  49.      writeln(''), write('You needed '), write(Tries),  write(' tries.').
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement