I'm currently developing a fun 'hangman' game for my wife's history course. As part of this project, I've constructed a class that generates the 'gameWord' in both string and array formats.
As an additional feature within this class, I aim to create another array that is visible to the player and changes based on their input. This array should display a '*' for each letter and a '_' for each space.
I've experimented with using regex in if or switch statements while looping through the gameWord array but haven't had much success so far. Here's one of my initial attempts:
class GameWord {
constructor(word) {
if ( word.length <= 3 )
return console.error('Error: Your word must be at least three letters long');
this.word = word.replace(/[^a-zA-Z\s]/g, '');
this.wordUserView = this.word.toProperCase( );
this.wordSet = this.wordUserView.split('');
const len = this.wordSet.length;
var i = 0;
this.wordSetHidden = [];
for ( ; i <= len; i++) {
if (this.wordSet[i] == /[a-zA-Z]/g) {
this.wordSetHidden.push("*");
}
};
}
};
And here's another example of something I've attempted:
var reAlpha = /[a-zA-Z]/;
var reSpace = /\s/;
var arr = ["W", "i", "n", "s", "t", "o", "n", " ", "1", 2, 0];
var newArr = [];
for ( var i = 0; i < arr.length; i++ ) {
switch (arr) {
case reAlpha.match:
newArr.push(arr[i] = "*");
case reSpace.match:
newArr.push(arr[i] = "_");
break;
default: console.log("No matches")
};
}
When working on these solutions, I keep encountering the "No matches" result because direct comparisons are not being made to the elements in the array. However, trying something like element.match(arr) results in an error stating that match isn't a function, likely because it's interpreting the element as an object rather than a string?
While I'm aware that CSS can be used to hide individual letters, I prefer having the game logic handled on the backend to prevent students from easily viewing the answers by modifying the CSS.
Thank you!