4
\$\begingroup\$

I want to make a typing game where users have to type the words displayed on the screen. But I don't know how to generate meaningful English words not gibberish.

What technique can I use to achieve this?

\$\endgroup\$
  • 2
    \$\begingroup\$ Have a file with a lot of real English words \$\endgroup\$ – Cedric Martens Jul 15 '17 at 15:57
2
\$\begingroup\$

There's no built-in way in Java, but there's 2 ways you can do this.

The first way takes more time but requires pretty much no storage space. You can use an HTTP GET request and use an online random word service (like this one) to get a random word. This method requires internet connection.

The other way is lot faster, but uses more memory and storage space. You need to create a file with a dictionary of words, load it on start (if it's small enough) and get a random word from it. You can also make it change the words based on grammar rules (eat + ing -> eating, provoke + ing -> provoking).

The best would be to use both solutions and rely on the dictionary when there's no internet connection.

\$\endgroup\$
  • \$\begingroup\$ If you're concerned about storage space, you could encode your dictionary as a finite state acceptor, and generate words by taking a (possibly weighted) random walk through its accepted pathways. This will naturally encode common word beginnings and endings like "ing" with reduced redundancy compared to a full dictionary, without needing to explicitly code a set of spelling rules & exceptions into your system. It won't compress as much as a zip, but you can use it while it's still compressed, which is a neat trick \$\endgroup\$ – DMGregory Jul 15 '17 at 23:16
  • 2
    \$\begingroup\$ The online method sounds like a terrible idea, since it wouldn't work when offline. \$\endgroup\$ – Aaron Franke Jul 19 '17 at 6:58
  • \$\begingroup\$ @AaronFranke I even wrote that in the answer, and provided a solution for this problem. \$\endgroup\$ – Bálint Jul 19 '17 at 9:14
  • \$\begingroup\$ The average word length in English is 5 letters. That means a dictionary of 10,000 words would take up a colossal 60k (including a null terminator) plus some space for an index. To put that in perspective the banner graphic at the top of this page is twice that size. The days when we needed to worry about a file that size are long gone. Even a dictionary of 100,000 words, or a selection of different dictionaries are not going to bring it up to a storage level worth concern. \$\endgroup\$ – Jack Aidley Jul 31 '17 at 20:19
2
\$\begingroup\$

One way is to make a file with a lot of random words and pull words from random positions. That way you could have different difficulties, such as easy words, medium words, and difficult words. Here's an example, which just prints one word at a time(randomized) that the user must type. Make sure to create the txt file and call it words.txt. Also put it on your desktop:

import java.io.*;
import java.util.*;

public class TypingTest {
    private static Random rand = new Random();
    private static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        String fileName = "/Users/Tommy/Desktop/words.txt";
        File wordList = new File(fileName);
        List<String> words = new ArrayList<>();
        Scanner reader = null;

        try {
            reader = new Scanner(wordList);
        } catch (FileNotFoundException e) {
            System.out.println("file \"" + fileName + "\" not found");
            System.exit(0);
        }

        while(reader.hasNextLine()) {
            String word = reader.nextLine();
            words.add(word);
        }

        String result = playGame(words);
        System.out.println("Your score: " + result);
    }

    public static String playGame(List<String> words) {
        int wordNum = words.size();
        String attempt;
        int place;
        int correct = 0;

        for(int i = 0; i < 10; i++) {
            place = rand.nextInt(wordNum);
            String s = words.get(place);
            System.out.println(s);
            attempt = input.next();
            if (attempt.equals(s)) {
                words.remove(s);
                wordNum = words.size();
                correct++;
            }
        }
        return Integer.toString(correct) + "/" + 10;
    }
}

Here's a list of 500 random words you can use

wait
release
river
important
mark
electric
defective
poke
blue
beef
spring
hurt
orange
happy
zealous
flowery
accurate
brake
title
x-ray
festive
wrathful
scissors
peaceful
finicky
shape
soothe
head
spotted
needless
time
abundant
humdrum
mouth
trot
bounce
thank
avoid
shocking
minor
secret
rabbit
protect
honey
business
worthless
suggest
splendid
drab
safe
gigantic
arrive
drum
hate
dinosaurs
machine
tame
annoy
telephone
curtain
monkey
things
refuse
lunch
wooden
ruin
request
faded
camp
didactic
annoying
finger
acrid
overt
lamp
paste
rejoice
ignorant
exist
madly
doubt
increase
measly
mate
tangy
dislike
bikes
rambunctious
complete
motion
coast
air
obey
burst
nosy
consist
yellow
long
cakes
close
teaching
five
undesirable
squash
border
memorize
fowl
scarecrow
tie
present
well-to-do
meaty
wonderful
pencil
need
advice
wide-eyed
apologize
possible
dreary
skin
kick
stage
tongue
puffy
camp
ski
ghost
quickest
lip
frequent
one
efficient
angry
alleged
suit
notebook
wipe
dream
spark
work
pail
throne
unnatural
pale
brief
pets
ad hoc
overrated
house
rely
messy
pastoral
afternoon
enchanting
tense
army
spotless
button
good
reduce
leather
eye
spotty
growth
alert
statement
overflow
flame
disagree
whispering
lively
healthy
sedate
plant
melt
snatch
combative
grain
spurious
run
fuzzy
hot
large
exotic
woozy
unaccountable
zip
wren
courageous
match
form
comb
shut
pointless
languid
capricious
stop
mammoth
psychedelic
ordinary
cobweb
determined
stereotyped
sordid
arrest
inquisitive
carpenter
small
vivacious
guard
poor
funny
shaky
hilarious
egg
spiders
abounding
humor
sticky
plastic
ratty
productive
agree
fork
temper
prepare
whistle
responsible
drain
eight
nest
slow
loutish
saw
fear
scrub
volatile
moldy
attract
receptive
aberrant
neck
man
store
materialistic
shrug
billowy
driving
travel
fairies
lumpy
assorted
bow
babies
attend
dress
surprise
tranquil
marvelous
illustrious
clam
fact
plate
soft
cover
dad
trousers
cars
superficial
bawdy
drown
envious
wasteful
religion
bells
kick
announce
elastic
trap
smoggy
lively
serious
start
lavish
basin
wrench
lock
picture
hand
rail
delightful
trade
sand
face
tenuous
scream
produce
low
subtract
industrious
pass
station
wash
synonymous
red
wrong
warlike
low
contain
mailbox
liquid
expensive
string
time
open
admit
lettuce
decision
quixotic
towering
copy
better
cake
fluffy
yarn
grease
mountainous
stick
join
icicle
succinct
plastic
pear
acoustic
abrupt
position
spark
yak
bent
crook
kitty
sneaky
use
pollution
mundane
barbarous
delight
flesh
robin
party
milky
round
wretched
pleasant
treatment
winter
hot
available
train
writer
prose
furtive
building
cattle
wealthy
sassy
sponge
face
reflective
bear
wanting
bustling
wiry
tearful
hypnotic
ill
animated
verdant
toad
unlock
long-term
wall
direful
hunt
obtainable
walk
bleach
unarmed
happen
kiss
trick
queen
conscious
mourn
girls
frame
erect
secretary
field
helpful
science
crown
heady
grotesque
dress
degree
cushion
piquant
innate
square
cactus
tricky
company
remarkable
calculate
rinse
crime
push
mind
flagrant
man
permit
theory
thoughtful
crate
yummy
offbeat
paltry
bulb
optimal
stove
chemical
shallow
merciful
sore
abortive
perpetual
zonked
eyes
bore
tired
regret
fit
potato
confuse
childlike
vein
sound
attack
exchange
back
check
damaged
grandmother
division
groovy
throat
office
pin
stare
meddle
shivering
interfere
occur
hole
sugar
test
blind
free
perform
cherries
flavor
stupendous
purpose
extend
risk
fanatical
grubby
beg
romantic
outrageous
swift
bath
room
pocket
front
flower
quicksand
mark
sturdy
resolute
letters
expert
hapless
bloody
blue-eyed
hope
chew
\$\endgroup\$
  • \$\begingroup\$ This is a good way of doing it but I would be inclined to take a number of free texts from online and automate pulling out words from it. This should allow a wider range of words and, by choosing different source texts, you could flavour your word sets and/or provide different language experiences. Some filtering for trivial words would be required. \$\endgroup\$ – Jack Aidley Jul 31 '17 at 11:15
  • \$\begingroup\$ You could also generate your own dictionary textfile from here app.aspell.net/create?defaults=en_US \$\endgroup\$ – RobM Jul 31 '17 at 14:07
  • \$\begingroup\$ @JackAidley That's a great Idea. I'm going to try to do that, and I will edit my post when I do. \$\endgroup\$ – CodingNinja Jul 31 '17 at 17:54
  • \$\begingroup\$ @RobM Thanks for that link! I'm working on it right now. I'll edit my post when I get it. \$\endgroup\$ – CodingNinja Jul 31 '17 at 17:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.