/*
	Game.js
	Version 1.0
	Has the game logic behind Cows N Bulls game.
*/
window.onload = initGame();
var guessCount;
var randomString;
var maxAttempts;

// Initialize Game.
function initGame(){
	guessCount = 0;
	maxAttempts = 20;
	var dictionary = "abed abet able ably abos abri abut abye abys aced aces ache achy acid acme acne acre acts acyl adit ados adze aeon aero aery aged ager ages agin agio agly agon ague ahem ahoy aide aids ails aims ains airn airs airt airy aits akin albs alec alef ales alif alit alky alme alms aloe alow alps also alto alts alum ambo amen amid amie amin amir amis amok amps amus amyl ands anes anew anil anis ankh ante anti ants anus aped aper apes apex apod apse arbs arch arco arcs ares arfs arid aril arks arms army arse arts arty arum arvo aryl asci ashy ates atom atop auks auld aunt auto aver aves avid avos avow awed awes awls awns awny awol awry axed axel axes axil axis axle axon ayes ayin azon bach back bade bads bags baht bail bait bake bald bale balk balm bals bams band bane bang bani bank bans baps bard bare barf bark barm barn bars base bash bask bast bate bath bats baud bawd bawl bays bead beak beam bean bear beat beau beck beds bedu begs bels belt bema bend bens bent berg berm best beta beth bets bevy beys bhut bias bice bide bids bier bigs bike bile bilk bima bind bine bins bint bios bird birk birl bise bisk bite bits bize blae blah blam blat blaw bled blet blew blin blip bloc blot blow blue blur boar boas boat bock bode bods body bogs bogy boil bola bold bole bolt bond bone bong bonk bony bops bora bore born bort bosh bosk bota both bots bout bowl bows boxy boys brad brae brag bran bras brat braw bray bred bren brew brie brig brim brin brio bris brit bros brow brut buck buds bugs buhl buhr bulk bumf bump bums bund bung bunk buns bunt buoy bura burd burg burl burn burp burs bury bush busk bust busy bute buts buys byes byre byrl byte cabs cade cadi cads cafe cage cagy caid cain cake caky calf calk calm calo calx came camp cams cane cans cant cape caph capo caps carb card care cark carl carn carp cars cart case cash cask cast cate cats caul cave cavy caws cays cedi ceil cels celt cent ceps cero chad cham chao chap char chat chaw chay chef chew chez chia chid chin chip chis chit chon chop chow chub chug chum ciao cine cion cire cist cite city clad clag clam clan clap claw clay clef clew clip clod clog clon clop clot cloy club clue coal coat coax cobs coda code cods coed coft cogs coif coil coin coir coke cola cold cole cols colt coly coma comb come comp cone coni conk cons cony cope cops copy cord core corf cork corm corn cory cosh cost cosy cote cots coup cove cowl cows cowy coxa coys cozy crab crag cram crap craw crew crib cris crop crow crud crus crux cube cubs cuds cued cues cuif cuke culm cult cunt cups curb curd cure curf curl curn curs curt cusk cusp cute cuts cwms cyan cyma cyme cyst czar dabs dace daft dago dags dahl dahs dais daks dale dals dame damn damp dams dang dank daps darb dare dark darn dart dash date dato daub daut davy dawk dawn daws dawt days daze deaf deal dean dear debs debt deck deco defi deft defy deil delf deli dels demo demy dens dent deny derm desk deva devs dews dewy dexy deys dhak dhal dhow dial dibs dice dick diel dies diet digs dike dime dims dine ding dink dins dint diol dips dipt dire dirk dirl dirt disc dish disk dita dite dits ditz diva dive djin doat doby dock docs doer does doge dogs dogy doit dole dols dolt dome doms dona done dong dons dopa dope dopy dore dork dorm dorp dors dory dose dost dote doth dots doty doum dour doux dove down dows doxy doze dozy drab drag dram drat draw dray dreg drek drew drib drip drop drub drug drum drys dual dubs duce duci duck duct duel dues duet dugs duit duke duly duma dumb dump dune dung dunk duns dunt duos dupe dups dura dure durn duro dusk dust duty dyer dyes dyke dyne each earl earn ears east easy eath eats eaux ebon echo ecru ecus edgy edhs edit efts egad egal egis egos elan elds elhi elks elms elmy emfs emic emir emit emus emyd ends engs enol enow envy eons epha epic epos eras ergo ergs erns eros erst espy etas etch eths etic etna etui euro evil exam exit exon expo eyas eyra face fact fade fado fads fags fail fain fair fake falx fame fane fang fano fans fard fare farl farm faro fart fash fast fate fats faun faux fave fawn fays faze feal fear feat feck feds fehs felt fems fend fens feod fern feta fets feud feus fiar fiat fibs fice fico fido fids figs fila file film filo fils find fine fink fino fins fire firm firn firs fisc fish fist fits five fixt flab flag flak flam flan flap flat flaw flax flay flea fled flew flex fley flic flip flit floc floe flog flop flow flub flue flus flux foal foam fobs foci foes fogs fogy fohn foil foin fold folk fond fons font fops fora forb ford fore fork form fort foul four fowl foxy foys fozy frae frag frap frat fray fret frig frit friz froe frog from frow frug fubs fuci fuds fuel fugs fuji fume fumy fund funk funs furl furs fury fuse futz fuze fyce fyke gabs gaby gadi gads gaed gaen gaes gain gait gale gals gamb game gamp gams gamy gane gaol gape gaps gapy garb gars gash gasp gast gate gats gaud gaum gaun gaur gave gawk gawp gays gaze gear geck geds geld gels gelt gems gens gent genu germ gest geta gets geum ghat ghis gibe gibs gids gied gien gies gift gild gilt gimp gink gins gips gird girl girn giro girt gist gits give glad gled glen gley glia glib glim glob glom glop glow glue glum glut gnar gnat gnaw gnus goad goal goas goat gobs goby gods goer goes gold golf gone gore gorp gory gosh gout gowd gowk gown goys grab grad gram gran grat gray grew grey grid grim grin grip grit grot grow grub grue grum guan guar guck gude guid gulf gulp guls gums gunk guns gush gust guts guvs guys gybe gyms gyps gyre gyri gyro gyve habu hack hade hadj haed haem haen haes haet haft hags haik hail hair haji hake hale half halm halo halt hame hams hand hang hank hant haps hard hare hark harl harm harp hart hasp hast hate hats haul haut have hawk haws hays haze hazy head heal heap hear heat heck heft heil heir held helm helo help hemp hems hens hent herb herd herl herm hern hero hers hest hets hewn hews hick hide hied hies hike hila hilt hind hins hint hips hire hisn hist hits hive hoar hoax hobs hock hods hoed hoer hoes hogs hoke hold hole holk holm holp hols holt holy home homy hone hong honk hons hope hops hora horn hose host hots hour hove howe howf howk howl hows hoya hoys hubs huck hued hues huge hugs huic hula hulk hump hums hung hunk huns hunt hurl hurt husk huts hwan hyla hymn hype hypo hyps hyte iamb ibex iced ices ichs icky icon idea idem ides idle idly idol idyl iglu ikat ikon ilea ilex ilka ilks imps inby inch info inks inky inly inro into ions iota ired ires irks iron isba isle itch item izar jabs jack jade jags jail jake jamb jams jane jape jarl jars jato jauk jaup jaws jays jean jehu jeon jerk jest jets jeux jews jiao jibe jibs jigs jilt jimp jink jins jinx jism jive jobs jock joes joey jogs john join joke joky jole jolt josh jota jots jouk jowl jows joys juba jube judo juga jugs juke jump junk jupe jura jury just jute juts kabs kadi kaes kafs kagu kaif kail kain kale kame kami kane kaon kaph karn kart kats kayo kays kbar keas kefs kegs keir kelp kemp keno kens kent kepi keps kept kerb kerf kern keto keys khaf khan khat khet khis kibe kids kief kier kifs kiln kilo kilt kina kind kine king kino kins kips kirn kirs kist kite kith kits kiva knap knar knew knit knob knop knot know knur koan koas kobs koel kohl kola koph kops kore kors kris kudo kues kvas kyar kyat kyte labs lace lack lacs lacy lade lads lady lags laic laid lain lair lake lakh laky lamb lame lamp lams land lane lang lank laps lard lari lark lars lase lash last late lath lati lats laud lave lavs lawn laws lays laze lazy lead leaf leak lean leap lear leas lech left legs lehr leis leks leku lend leno lens lent lept lest lets leud leva levo levy lewd leys liar libs lice lich lick lido lids lied lief lien lier lies lieu life lift like lima limb lime limn limo limp limy line ling link lino lins lint liny lion lips lira lire lisp list lite lits litu live load loaf loam loan lobe lobs loca loch loci lock lode loft loge logs logy loin lone long lope lops lord lore lorn lory lose lost lota loth loti lots loud loup lour lout love lowe lown lows lube luce luck lude lues luge lugs lump lums luna lune lung lunk lunt luny lure lurk lush lust lute lutz luvs luxe lwei lyes lynx lyre lyse mabe mace mach mack macs made mads maes mage magi mags maid mail main mair make mako male malt mane mano mans many maps marc mare mark marl mars mart mash mask mast mate math mats maud maul maun maut mawn maws maxi mayo mays maze mazy mead meal mean meat meld mels melt mend meno menu meou meow merk merl mesa mesh meta meth mewl mews mhos mibs mica mice mick mids mien migs mike mild mile milk milo mils milt mina mind mine mink mint minx mire mirk mirs miry mise miso mist mite mity mixt moan moas moat mobs mock mocs mode modi mods mogs moil moke mola mold mole mols molt moly monk mons mony mope mops mopy mora more morn mors mort mosk most mote moth mots moue move mown mows moxa much muck muds mugs mule muni muns muon mura mure murk muse mush musk must mute muts myna myth nabe nabs nags naif nail name naoi naos nape naps narc nard nark nary nave navy nays nazi neap near neat nebs neck neif nema nerd nest nets neuk neum nevi news newt next nibs nice nick nide nigh nils nims nipa nips nite nits nixe nixy nobs nock node nodi nods noel noes nogs noil noir noma nome noms nope nori norm nose nosh nosy nota note nous nova nows nowt nubs nude nuke numb nurd nurl nuts oafs oaks oars oast oath oats obes obey obia obis obit ocas odea odes odic odyl ofay ogam ogle ogre ohed ohia ohms oils oily oink okas okay okeh okes okra olds oldy olea oles omen omer omit once ones only onus onyx opah opal oped open opes opts opus orad oral orbs orby orca orcs ores orgy orle orts oryx osar otic ouch ouds ouph ours oust outs oval oven over ovum owed owes owls owns owse oxen oxes oxid oxim oyer oyes oyez pace pack pacs pact padi pads page paid paik pail pain pair pale palm pals paly pams pane pang pans pant pard pare park pars part pase pash past pate path pats paty pave pawl pawn paws pays peag peak peal pean pear peas peat pech peck pecs peds pegs pehs pein pelf pelt pend pens pent peon peri perk perm pert peso pest pets pews pfui phat phew phis phiz phon phot phut pial pian pias pica pice pick pics pied pier pies pigs pika pike pile pily pima pina pine ping pink pins pint piny pion pirn pish piso pita pith pits pity pixy plan plat play plea pleb pled plew plie plod plot plow ploy plug plum plus pock pods poem poet pogy pois poke poky pole pols poly pome poms pond pone pong pons pony pore pork port pose posh post posy pots pouf pour pout pows pram prao prat prau pray prex prey prez prig prim proa prod prof prog prom pros prow pubs puce puck puds pugh pugs puja puke pula pule puli puls puma puna pung punk puns punt puny pure puri purl purs push puts putz pyas pyes pyic pyin pyre qaid qats qoph quad quag quai quay quey quid quin quip quit quiz quod race rack racy rads raft rage ragi rags raid rail rain rake raki rale rami ramp rams rand rang rani rank rant rape raps rapt rase rash rasp rate rath rato rats rave raws rays raze read real ream reap rebs reck recs redo reds refs reft regs reif rein reis rely rems rend rent repo reps resh rest rets revs rhea rhos rhus rial rias ribs rice rich rick ride rids riel rife rifs rift rigs rile rime rims rimy rind ring rink rins riot ripe rips rise risk rite ritz rive road roam roan robe robs rock rocs rode rods roes roil role rolf romp roms rope ropy rose rosy rota rote roti rotl rots roue roup rout roux rove rows rube rubs ruby ruck rude rued rues ruga rugs ruin rule ruly rump rums rune rung runs runt ruse rush rusk rust ruth ruts ryas ryes ryke rynd ryot sabe sack sade sadi safe sage sago sagy said sail sain sake saki sale salp salt same samp sand sane sang sank sard sari sark sate sati saul save sawn scab scad scag scam scan scar scat scop scot scow scry scud scum scup scut seal seam sear seat sect sego seif self semi send sent sept sera serf seta sewn sext sexy shad shag sham shat shaw shay shea shed shew shim shin ship shit shiv shmo shod shoe shog shop shot show shri shul shun shut sial sice sick side sift sigh sign sike sild silk silo silt sima simp sine sing sinh sink sipe sire site sith size sizy skag skat skeg skep skew skid skim skin skip skit skua slab slag slam slap slat slaw slay sled slew slid slim slip slit slob sloe slog slop slot slow slub slue slug slum slur slut smew smit smog smug smut snag snap snaw sned snib snip snit snob snog snot snow snub snug snye soak soap soar sock soda sofa soft soil soja soke sola sold sole soli soma some sone song soph sora sorb sord sore sori sorn sort soth souk soul soup sour sown soya spae span spar spat spay spaz spec sped spew spic spik spin spit spiv spot spry spud spue spun spur stab stag star staw stay stem step stew stey stir stoa stob stop stow stub stud stum stun stye suba such suck sued suer suet sugh suit sulk sumo sump sung sunk supe sura surd sure surf swab swag swam swan swap swat sway swig swim swob swop swot swum sybo syce syke syli sync syne syph tabs tabu tace tach tack taco tads tael tags tahr tail tain take talc tale tali talk tame tamp tams tang tank tans taos tape taps tare tarn taro tarp tars task taus tavs taws taxi teak teal team tear teas teds tegs tela tels temp tend tens tepa term tern tews thae than thaw them then thew they thin thio thir this thou thro thru thud thug thus tick tics tide tidy tied tier ties tike tile tils time tine ting tins tiny tips tire tirl tiro tivy toad toby tods tody toea toed toes tofu toga togs toil toke tola told tole tolu tomb tome toms tone tong tons tony tope toph topi tops tora torc tore tori torn tors tory tosh tour town tows towy toys trad tram trap tray tref trek trey trig trim trio trip trod trop trow troy true trug tsar tuba tube tubs tuck tufa tugs tuis tule tump tuna tune tung tuns tups turd turf turk turn tush tusk twae twas twig twin twos tyer tyes tyke tyne type typo tyre tyro tzar udos ughs ugly ukes ulan ulna ulva umbo umps unai unbe unci unco unde undo undy unit unto upas upby updo upon urbs urds urea urge uric urns ursa used user utas uvea vacs vagi vail vain vair vale vamp vane vang vans vars vary vase vast vats vatu vaus vaws veal veil vein vela veld vena vend vent vera verb vert very vest veto vets vext vial vibe vice vide vied vier vies view viga vigs vile vims vina vine vino viny viol virl visa vise vita voes void vole volt vote vows vrow vugh vugs wabs wack wade wadi wads wady waes waft wage wags waif wail wain wair wait wake wale walk waly wame wand wane wans want wany waps ward ware wark warm warn warp wars wart wary wash wasp wast wats wauk waul waur wave wavy waxy ways weak weal wean wear webs weds weft weir weka weld welt wend wens went wept wert west wets wham whap what when whet whey whid whig whim whin whip whir whit whiz whoa whom whop whys wich wick wide wife wigs wild wile wilt wily wimp wind wine wing wink wino wins winy wipe wire wiry wise wish wisp wist wite with wits wive woad woes wogs woke woks wold wolf womb wonk wons wont wops word wore work worm worn wort wost wots wove wrap wren writ wych wyes wyle wynd wyns wyte xyst yack yagi yaks yald yams yang yank yaps yard yare yarn yaud yaup yawl yawn yawp yaws yeah yean year yeas yech yeld yelk yelp yens yerk yeti yeuk yews yids yins yipe yips yird ylem yobs yock yodh yods yoga yogh yogi yoke yoks yolk yond yoni yore your yowe yowl yows yuan yuca yuch yuck yuga yuks yule yups yurt ywis zags zany zaps zarf zeal zebu zeds zein zeks zerk zero zest zeta zigs zinc zing zins zips zits zoea zoic zone zonk zori zyme";
	var words = dictionary.split(" ");
	var randomNum = Math.ceil(words.length*Math.random());
	randomString = words[randomNum];
	$("table").find("tr:gt(0)").remove();
}

// Check user input.
function checkGuess(){
	if(document.getElementById("txtUserGuess").value.length != 4){
		alert("Please enter a 4 letter word.");
		clearGuess();
		return;
	}
	
	var userValue = document.getElementById("txtUserGuess").value.toLowerCase();
	
	guessCount += 1;
	
	// Exceeded Max attempts.
	if(guessCount == maxAttempts){
		alert("You exceeded the maximum try allowed. My guess was: " + randomString);
		initGame();
		clearGuess();
		return;
	}
	
	// Bull'e eyes.
	if(userValue == randomString){
		alert("You hit the bull's eye.");
		initGame();
		clearGuess();
		return;
	}
		
	var noOfCows = 0;
	var noOfBulls = 0;
	
	// Check for no of cows and no of bulls.
	for(i = 0; i < userValue.length; i++){		
		if(userValue.charAt(i) == randomString.charAt(i)){
			noOfBulls += 1;
		}
		else {
			for(j = 0; j < randomString.length; j++)
			{
				if(userValue.charAt(i) == randomString.charAt(j)){
					noOfCows += 1;
				}
			}
		}
	}

	// Append user guess to the table.
	var tableRow = '<tr><td>' + userValue +  '</td><td>' + noOfCows + '</td><td>' + noOfBulls + '</td></tr>';	
	$("table").append(tableRow);
}

// Clear the input field.
function clearGuess(){
	document.getElementById("txtUserGuess").value = "";
}