Jump to content

Reading words form a txt file


Sigrit

Recommended Posts

Hello!

 

I'm trying to make a word game in HTML, using javascript and css. I took 1000 different words and put them on a txt file. Every time game starts I want to take only one word (randomly) and mix it's letters. I got stuck with reading these words separately from this txt file. I thought about using javascript, but I'm not sure how to take only one word from this file. Does anyone know how to do this the easiest way? I'm not so good at programming (yet).

 

Thanks!

Link to comment
Share on other sites

Assuming you already have obtained the contents of the file in a string, you can use split() to break it into an array.

 

Now, generate a number using Math.random() to get a random number between 0 and the length of the array.

 

Use that the get an element of the array which will contain one of the strings that were in the text file.

 

Quick example:

var str = "word1 word2 word3";var arr = str.split(" ");var num = Math.floor(Math.random() * arr.length);alert(arr[num]) // This will show one random word from the set of words.
Link to comment
Share on other sites

Foxy has it...

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Game</title><style></style><script>window.onerror = function(m, u, l){alert('Javascript Error: '+m+'nURL: '+u+'nLine Number: '+l);return true;}</script><script src='wordstringfile.js'></script><script>var word = '';//global variablewindow.onload = init;function init(){document.getElementById('btn1').onclick = game;document.getElementById('btn2').onclick = test;}function game(){var arr = str.split(" ");var out = document.getElementById('out');var num = Math.floor(Math.random() * arr.length);word = arr[num];// This will choose one random word from the set of words.var mixed = mixup(word);out.innerHTML = mixed;}function mixup(word1){var word2 = '';var old = word1.split('');var j;while (word2.length < word1.length){j = Math.floor(Math.random() * word1.length);if (old[j] != null){word2 += old[j];old[j] = null;}}return word2;}function test(){var guess = document.getElementById('inp').value.trim();//alert('['+ guess +']['+ word +']');if (guess < word || guess > word){alert('No, sorry');}else{alert('Yes that is correct!')}}</script></head><body><h1>Word Game</h1><input type="button" id="btn1" value="Next Word"/><div id="out"></div><input type="text" id="inp" placeholder="Enter solution"/><input type="button" id="btn2" value="Enter"/></body></html>

wordstringfile.js is...

var str = "word1 word2 word3 word4 word5 word6 word7 word8"; 
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...