Wordiff

From Rosetta Code
Wordiff is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Wordiff is an original game in which contestants take turns spelling new dictionary words that only differ from the last by a change in one letter.

The change can be either:

  1. a deletion of one letter;
  2. addition of one letter;
  3. or change in one letter.

Note:

  • All words must be in the dictionary.
  • No word in a game can be repeated.
  • The first word must be three or four letters long.
Task

Create a program to aid in the playing of the game by:

  • Asking for contestants names.
  • Choosing an initial random three or four letter word from the dictionary.
  • Asking each contestant in their turn for a wordiff word.
  • Checking the wordiff word is:
  • in the dictionary,
  • not a repetition of past words,
  • and differs from the last appropriately.
Optional stretch goal

Add timing.

  • Allow players to set a maximum playing time for the game.
  • An internal timer accumulates how long each user takes to respond in their turns.
  • Play is halted if the maximum playing time is exceeded on a players input.
  • That last player must have entered a wordiff or loses.
  • If the game is timed-out, the loser is the person who took the longest `average` time to answer in their rounds.

Nim

Translation of: Python

<lang Nim>import httpclient, sequtils, sets, strutils, sugar from unicode import capitalize

const

 DictFname = "unixdict.txt"
 DictUrl1 = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"    # ~25K words
 DictUrl2 = "https://raw.githubusercontent.com/dwyl/english-words/master/words.txt"  # ~470K words


type Dictionary = HashSet[string]


proc loadDictionary(fname = DictFname): Dictionary =

 ## Return appropriate words from a dictionary file.
 for word in fname.lines():
   if word.len >= 3 and word.allCharsInSet(Letters): result.incl word.toLowerAscii


proc loadWebDictionary(url: string): Dictionary =

 ## Return appropriate words from a dictionary web page.
 let client = newHttpClient()
 for word in client.getContent(url).splitLines():
   if word.len >= 3 and word.allCharsInSet(Letters): result.incl word.toLowerAscii


proc getPlayers(): seq[string] =

 ## Return inputted ordered list of contestant names.
 try:
   stdout.write "Space separated list of contestants: "
   stdout.flushFile()
   result = stdin.readLine().splitWhitespace().map(capitalize)
   if result.len == 0:
     quit "Empty list of names. Quitting.", QuitFailure
 except EOFError:
   echo()
   quit "Encountered end of file. Quitting.", QuitFailure


proc isWordiffRemoval(word, prev: string; comment = true): bool =

 ## Is "word" derived from "prev" by removing one letter?
 for i in 0..prev.high:
   if word == prev[0..<i] & prev[i+1..^1]: return true
 if comment: echo "Word is not derived from previous by removal of one letter."
 result = false


proc isWordiffInsertion(word, prev: string; comment = true): bool =

 ## Is "word" derived from "prev" by adding one letter?
 for i in 0..word.high:
   if prev == word[0..<i] & word[i+1..^1]: return true
 if comment: echo "Word is not derived from previous by insertion of one letter."
 return false


proc isWordiffChange(word, prev: string; comment = true): bool =

 ## Is "word" derived from "prev" by changing exactly one letter?
 var diffcount = 0
 for i in 0..word.high:
   diffcount += ord(word[i] != prev[i])
 if diffcount != 1:
   if comment:
     echo "More or less than exactly one character changed."
   return false
 result = true


proc isWordiff(word: string; wordiffs: seq[string]; dict: Dictionary; comment = true): bool =

 ## Is "word" a valid wordiff from "wordiffs[^1]"?
 if word notin dict:
   if comment:
     echo "That word is not in my dictionary."
     return false
 if word in wordiffs:
   if comment:
     echo "That word was already used."
     return false
 result = if word.len < wordiffs[^1].len: word.isWordiffRemoval(wordiffs[^1], comment)
          elif word.len > wordiffs[^1].len: word.isWordiffInsertion(wordiffs[^1], comment)
          else: word.isWordiffChange(wordiffs[^1], comment)


proc couldHaveGot(wordiffs: seq[string]; dict: Dictionary): seq[string] =

 for word in dict - wordiffs.toHashSet:
   if word.isWordiff(wordiffs, dict, comment = false):
     result.add word


when isMainModule:

 import random
 randomize()
 let dict = loadDictionary(DictFname)
 let dict34 = collect(newSeq):
                for word in dict:
                  if word.len in [3, 4]: word
 let start = sample(dict34)
 var wordiffs = @[start]
 let players = getPlayers()
 var iplayer = 0
 var word: string
 while true:
   let name = players[iplayer]
   while true:
     stdout.write "$1, input a wordiff from “$2”: ".format(name, wordiffs[^1])
     stdout.flushFile()
     try:
       word = stdin.readLine().strip()
       if word.len > 0: break
     except EOFError:
       quit "Encountered end of file. Quitting.", QuitFailure
   if word.isWordiff(wordiffs, dict):
     wordiffs.add word
   else:
     echo "You have lost, $#.".format(name)
     let possibleWords = couldHaveGot(wordiffs, dict)
     if possibleWords.len > 0:
       echo "You could have used: ", possibleWords[0..min(possibleWords.high, 20)].join(" ")
     break
   iplayer = (iplayer + 1) mod players.len</lang>
Output:
Space separated list of contestants: Paddy Maggie
Paddy, input a wordiff from “beta”: bet
Maggie, input a wordiff from “bet”: bee
Paddy, input a wordiff from “bee”: tee
Maggie, input a wordiff from “tee”: teen
Paddy, input a wordiff from “teen”: teeny
That word is not in my dictionary.
You have lost, Paddy.
You could have used: then steen tern keen teem teet been seen ten


Python

This is without timing, but ends by showing some wordiffs from the dictionary that could have worked on failure. <lang python># -*- coding: utf-8 -*-

from typing import List, Tuple, Dict, Set from itertools import cycle, islice from collections import Counter import re import random import urllib

dict_fname = 'unixdict.txt' dict_url1 = 'http://wiki.puzzlers.org/pub/wordlists/unixdict.txt' # ~25K words dict_url2 = 'https://raw.githubusercontent.com/dwyl/english-words/master/words.txt' # ~470K words

word_regexp = re.compile(r'^[a-z]{3,}$') # reduce dict words to those of three or more a-z characters.


def load_dictionary(fname: str=dict_fname) -> Set[str]:

   "Return appropriate words from a dictionary file"
   with open(fname) as f:
       return {lcase for lcase in (word.strip().lower() for word in f)
               if word_regexp.match(lcase)}

def load_web_dictionary(url: str) -> Set[str]:

   "Return appropriate words from a dictionary web page"
   words = urllib.request.urlopen(url).read().decode().strip().lower().split()
   return {word for word in words if word_regexp.match(word)}


def get_players() -> List[str]:

   "Return inputted ordered list of contestant names."
   names = input('Space separated list of contestants: ')
   return [n.capitalize() for n in names.strip().split()]

def is_wordiff(wordiffs: List[str], word: str, dic: Set[str], comment=True) -> bool:

   "Is word a valid wordiff from wordiffs[-1] ?"
   if word not in dic:
       if comment: 
           print('That word is not in my dictionary')
       return False
   if word in wordiffs:
       if comment: 
           print('That word was already used.')
       return False
   if len(word) < len(wordiffs[-1]):
       return is_wordiff_removal(word, wordiffs[-1], comment)
   elif len(word) > len(wordiffs[-1]):
       return is_wordiff_insertion(word, wordiffs[-1], comment)
   
   return is_wordiff_change(word, wordiffs[-1], comment)


def is_wordiff_removal(word: str, prev: str, comment=True) -> bool:

   "Is word derived from prev by removing one letter?"
   ...
   ans = word in {prev[:i] + prev[i+1:] for i in range(len(prev))}
   if not ans:
       if comment: 
           print('Word is not derived from previous by removal of one letter.')
   return ans


def is_wordiff_insertion(word: str, prev: str, comment=True) -> bool:

   "Is word derived from prev by adding one letter?"
   diff = Counter(word) - Counter(prev)
   diffcount = sum(diff.values())
   if diffcount != 1:
       if comment: 
           print('More than one character insertion difference.')
       return False
   
   insert = list(diff.keys())[0] 
   ans =  word in {prev[:i] + insert + prev[i:] for i in range(len(prev) + 1)}
   if not ans:
       if comment: 
           print('Word is not derived from previous by insertion of one letter.')
   return ans


def is_wordiff_change(word: str, prev: str, comment=True) -> bool:

   "Is word derived from prev by changing exactly one letter?"
   ...
   diffcount = sum(w != p for w, p in zip(word, prev))
   if diffcount != 1:
       if comment: 
           print('More or less than exactly one character changed.')
       return False
   return True

def could_have_got(wordiffs: List[str], dic: Set[str]):

   return (word for word in (dic - set(wordiffs)) 
           if is_wordiff(wordiffs, word, dic, comment=False))

if __name__ == '__main__':

   dic = load_web_dictionary(dict_url2)
   dic_3_4 = [word for word in dic if len(word) in {3, 4}]
   start = random.choice(dic_3_4)
   wordiffs = [start]
   players = get_players()
   for name in cycle(players):
       word = input(f"{name}: Input a wordiff from {wordiffs[-1]!r}: ").strip()
       if is_wordiff(wordiffs, word, dic):
           wordiffs.append(word)
       else:
           print(f'YOU HAVE LOST {name}!')
           print("Could have used:", 
                 ', '.join(islice(could_have_got(wordiffs, dic), 10)), '...')
           break</lang>
Output:
Space separated list of contestants: Paddy Maggie

Paddy: Input a wordiff from 'sett': sets

Maggie: Input a wordiff from 'sets': bets

Paddy: Input a wordiff from 'bets': buts

Maggie: Input a wordiff from 'buts': bits

Paddy: Input a wordiff from 'bits': bit

Maggie: Input a wordiff from 'bit': bite

Paddy: Input a wordiff from 'bite': biter

Maggie: Input a wordiff from 'biter': bitter

Paddy: Input a wordiff from 'bitter': sitter

Maggie: Input a wordiff from 'sitter': titter

Paddy: Input a wordiff from 'titter': tutter
That word is not in my dictionary
YOU HAVE LOST Paddy!
Could have used: titfer, witter, tittery, totter, titler, kitter, twitter, tilter, gitter, jitter ...

REXX

<lang rexx></lang> output


Wren

Library: Wren-ioutil
Library: Wren-str
Library: Wren-sort

Due to a bug in the System.clock method (basically it gets suspended whilst waiting for user input), it is not currently possible to add timings. <lang ecmascript>import "random" for Random import "/ioutil" for File, Input import "/str" for Str import "/sort" for Find

var rand = Random.new() var words = File.read("unixdict.txt").trim().split("\n")

var player1 = Input.text("Player 1, please enter your name : ", 1) var player2 = Input.text("Player 2, please enter your name : ", 1) if (player2 == player1) player2 = player2 + "2"

var words3or4 = words.where { |w| w.count == 3 || w.count == 4 }.toList var n = words3or4.count var firstWord = words3or4[rand.int(n)] var prevLen = firstWord.count var prevWord = firstWord var used = [] var player = player1 System.print("\nThe first word is %(firstWord)\n") while (true) {

   var word = Str.lower(Input.text("%(player), enter your word : ", 1))
   var len = word.count
   var ok = false
   if (Find.first(words, word) == -1) {
       System.print("Not in dictionary.")
   } else if (used.contains(word)) {
       System.print("Word has been used before.")
   } else if (word == prevWord) {
       System.print("You must change the previous word.")
   } else if (len == prevLen) {
       var changes = 0
       for (i in 0...len) {
           if (word[i] != prevWord[i]) {
               changes = changes + 1
           }
       }
       if (changes > 1) {
           System.print("Only one letter can be changed.")
       } else ok = true
   } else if (len == prevLen + 1) {
       var addition = false
       var temp = word
       for (i in 0...prevLen) {
           if (word[i] != prevWord[i]) {
               addition = true
               temp = Str.delete(temp, i)
               if (temp == prevWord) {
                   ok = true
               }
               break
           }
       }
       if (!addition) ok = true
       if (!ok) System.print("Invalid addition.")
   } else if (len == prevLen - 1) {
       var deletion = false
       var temp = prevWord
       for (i in 0...len) {
           if (word[i] != prevWord[i]) {
               deletion = true
               temp = Str.delete(temp, i)
               if (temp == word) {
                   ok = true
               }
               break
           }
       }
       if (!deletion) ok = true
       if (!ok) System.print("Invalid deletion.")
   } else {
       System.print("Invalid change.")
   }
   if (ok) {
       prevLen = word.count
       prevWord = word
       used.add(word)
       player = (player == player1) ? player2 : player1
   } else {
       System.print("So, sorry %(player), you've lost!")
       return
   }

}</lang>

Output:

Sample game:

Player 1, please enter your name : Paddy
Player 2, please enter your name : Maggie

The first word is pan

Paddy, enter your word : pen
Maggie, enter your word : pin
Paddy, enter your word : pint
Maggie, enter your word : pant
Paddy, enter your word : pane
Maggie, enter your word : pang
Paddy, enter your word : bang
Maggie, enter your word : rang
Paddy, enter your word : sang
Maggie, enter your word : sing
Paddy, enter your word : ling
Not in dictionary.
So, sorry Paddy, you've lost!