My anagram game will only play 5 letter words no matter what the player chooses in the drop down menu

50 Views Asked by At

I am having extreme difficulties in figuring out where my code is wrong in an anagram hunt vue.js app I am creating. At the beginning of the game, the player chooses the word length from a drop down menu. The player should be able to play the anagram game based on the number of letters the player chose. However, it seems that no matter what the player chooses, it defaults to 5 letter words.

Here is the full GamePlay.vue code:

<template>
 <div id="game-container" class="text-center">
    <template v-if="timeLeft === 0">
      <div>
        <h2>Anagram Hunt</h2>
        <h2>Time's Up!</h2>
        <strong class="big">You Got</strong>
        <div class="huge">{{ score }}</div>
        <strong class="big">Anagrams</strong>
        <button
          class="btn btn-primary form-control m-1"
          v-on:click="restart()"
        >
          Play Again
        </button>
        <button
          class="btn btn-secondary form-control m-1"
          v-on:click="config()"
         >
              Back to Start Screen
            </button>
          </div>
        </template>
        <div v-if="timeLeft > 0">
      <div class="row border-bottom" id="scoreboard">
        <div class="col px-3 text-left">
        <GameScore :score="score" />
      </div>
      <div class="col px-3 text-right">
      <GameTimer :timeLeft="timeLeft" />
       </div>
      </div>
      <div :class="equationClass" id="equation">
      <p class="anagram-word">{{ currentWord }} ({{ remainingAnagrams }} left)</p>
        <GameEquation
          :question="currentWord"
          :answer="userInput"
          :answered="answered"
        />
      </div>
      <div class="row" id="buttons">
        <div class="col">
          <input
          type="text"
            v-model="userInput"
            @keyup.enter="checkAnswer"
            :disabled="answered"
            placeholder="type here"
          />
      
        </div>
      </div>
      <div class="completed-anagrams">
        <p v-for="(anagram, index) in completedAnagrams" :key="anagram">
        {{ index + 1 }}. {{ anagram }}</p>
      </div>
    </div>
  </div>
</template>
<script>
import GameScore from './GameScore';
import GameTimer from './GameTimer';
import GameEquation from './GameEquation';
import anagrams from '../helpers/anagrams';

export default {
  name: 'GamePlay',
  components: {
    GameScore,
    GameTimer,
    GameEquation,
  },
  data() {
    return {
      wordLengths: [5, 6, 7, 8],
      wordLength: 5,
      currentWord: '',
      anagrams: [],
      userInput: '',
      answered: false,
      score: 0,
      gameLength: 60,
      timeLeft: 0,
      equationClass: '',
      completedAnagrams: [],
    };
  },
  methods: {
    config() {
      //this.$router.push('/');
    },
    newWord() {
    const wordLength = this.wordLength; // Use the selected word length
    console.log('Word Length:', wordLength);
    const wordArrays = anagrams[wordLength];
    console.log('Word Arrays:', wordArrays);

   if (wordArrays && wordArrays.length > 0) {
    const randomArray = wordArrays[Math.floor(Math.random() * wordArrays.length)];
    console.log('Random Array:', randomArray);

    if (randomArray && randomArray.length > 0) {
      // Filter words to ensure the selected word has the correct length
      const filteredArray = randomArray.filter(word => word.length === wordLength);
      console.log('Filtered Array:', filteredArray);

      if (filteredArray.length > 0) {
        this.currentWord = filteredArray[Math.floor(Math.random() * filteredArray.length)];
        console.log('New word:', this.currentWord);
        this.anagrams = filteredArray.filter(word => word !== this.currentWord);
        console.log('Updated anagrams:', this.anagrams);
        // Reset completedAnagrams
        this.completedAnagrams = [];
      } else {
        console.error('No words with the selected length in the random array.');
      }
    } else {
      console.error('Random array is empty or undefined.');
    }
  } else {
    console.error('Word arrays are empty or undefined for the given word length.');
   }

  // Reset answered status
  this.answered = false;
},
    checkAnswer() {
  // Check if the user input is a valid anagram
  if (this.anagrams.includes(this.userInput)) {
    this.score++;
    this.completedAnagrams.push(this.userInput);
    // Remove the guessed anagram
    this.anagrams = this.anagrams.filter(word => word !== this.userInput);
    // Clear the user input
    this.userInput = '';

    // Check if all anagrams are guessed, then get a new word
    if (this.anagrams.length === 0) {
      this.newWord(); // Add this line to get a new word
      console.log('Getting a new word...');
    }
  }
  this.answered = false; // Set answered to false after checking the answer
},
    startTimer() {
      window.addEventListener('keyup', this.handleKeyUp);
      this.timeLeft = this.gameLength; // This should be initialized with some value
      if (this.timeLeft > 0) {
        this.timer = setInterval(() => {
          this.timeLeft--;
          if (this.timeLeft === 0) {
            clearInterval(this.timer);
            window.removeEventListener('keyup', this.handleKeyUp);
          }
        }, 1000);
      }
    },
    restart() {
      this.score = 0;
      this.startTimer();
      this.newWord();
    },

  },
  mounted() {
    console.log('Word Length:', this.$route.params.wordLength);
    this.newWord();
    this.startTimer();
  },
 computed: {
    remainingAnagrams() {
    return this.anagrams.length;
    },
  },
};
</script>

This is what my console logs are showing:

Word Length: 8
GamePlay.vue:95 Word Length: 5
GamePlay.vue:97 Word Arrays: (9) [Array(5), Array(4), Array(3), Array(3), Array(3), Array(4), Array(4), Array(3), Array(5)]
GamePlay.vue:101 Random Array: (5) ['caret', 'cater', 'crate', 'trace', 'react']
GamePlay.vue:106 Filtered Array: (5) ['caret', 'cater', 'crate', 'trace', 'react']
GamePlay.

Here is the anagrams.js code:

const anagrams = {
    5: [
      [
        "abets",
        "baste",
        "betas",
        "beast",
        "beats"
      ],
      [
        "acres",
        "cares",
        "races",
        "scare"
      ],
      [
        "alert",
        "alter",
        "later"
      ],
      [
        "angel",
        "angle",
        "glean"
      ],
      [
        "baker",
        "brake",
        "break"
      ],
      [
        "bared",
        "beard",
        "bread",
        "debar"
      ],
      [
        "dater",
        "rated",
        "trade",
        "tread"
      ],
      [
        "below",
        "bowel",
        "elbow"
      ],
      [
        "caret",
        "cater",
        "crate",
        "trace",
        "react"
      ]
    ],
    6: [
      [
        "arrest",
        "rarest",
        "raster",
        "raters",
        "starer"
      ],
      [
        "carets",
        "caters",
        "caster",
        "crates",
        "reacts",
        "recast",
        "traces"
      ],
      [
        "canter",
        "nectar",
        "recant",
        "trance"
      ],
      [
        "danger",
        "gander",
        "garden",
        "ranged"
      ],
      [
        "daters",
        "trades",
        "treads",
        "stared"
      ]
    ],
    7: [
      [
        "allergy",
        "gallery",
        "largely",
        "regally"
      ],
      [
        "aspired",
        "despair",
        "diapers",
        "praised"
      ],
      [
        "claimed",
        "decimal",
        "declaim",
        "medical"
      ],
      [
        "dearths",
        "hardest",
        "hatreds",
        "threads",
        "trashed"
      ],
      [
        "detains",
        "instead",
        "sainted",
        "stained"
      ]
    ],
    8: [
      [
        "parroted",
        "predator",
        "prorated",
        "teardrop"
      ],
      [
        "repaints",
        "painters",
        "pantries",
        "pertains"
      ],
      [
        "restrain",
        "retrains",
        "strainer",
        "terrains",
        "trainers"
      ],
      [
        "construe",
        "counters",
        "recounts",
        "trounces"
      ]
    ]
  };

  export default anagrams;

I have tried to modify the code so that it would select a word from the filtered array based on the chosen word length. I don't know if there is a discrepancy in the initial value of this.wordLength or how it's being updated. I cannot see it and need different sets of eyes to try and see where I went wrong. Your help is greatly appreciated!

0

There are 0 best solutions below