Searching for words in a Javascript based game

Currently, I am in the process of developing a Word Search Game and one obstacle I am facing is how to display my selected words on the HTML grid that I have created. While someone did assist me with randomly generating the words into rows and columns, the issue is that it places the entire word in a single cell, when what I actually need is for each letter of the word to be distributed randomly among individual cells (hopefully that makes sense).

const myWords = ["LOL", "HEY", "TOYS", "YES", "SIR", "JOY"]; 

for (let i = 0; i < myWords.length; i++) {
    const randomIndex = length => Math.floor(Math.random() * length);
    const table = document.querySelector('table');
    const randomRow = table.rows[randomIndex(myWords.length)];
    const randomCell = randomRow.cells[randomIndex(myWords.length)];
    const randomWord = myWords[Math.floor(Math.random() * myWords.length)];
    randomCell.innerText = randomWord;   
}

I had initially planned on having the words aligned horizontally, vertically, and diagonally but my efforts to find a solution on platforms like Stack Overflow and Github have been fruitless. Is there anyone out there who can provide some guidance?

Answer №1

Welcome, The code is fully complete and operational, Credits to lizhineng

/**
 * Generates a random integer between min and max
 *
 * @param {Number} min
 * @param {Number} max
 * @return {Number}
 */
if (typeof Math.rangeInt != 'function') {
  Math.rangeInt = function(min, max){
    if (max == undefined) {
        max = min;
        min = 0;
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
}

/**
 * Merges two objects
 *
 * @param {Object} o1 Object 1
 * @param {Object} o2 Object 2
 * @return {Object}
 */
if (typeof Object.merge != 'function') {
  Object.merge = function(o1, o2) {
    for (var i in o1) {
      o2[i] = o1[i];
    }
    return o2;
  }
}
(function(){
  'use strict';

  // Extend the element method
  Element.prototype.wordSearch = function(settings) {
    return new WordSearch(this, settings);
  }

  /**
   * Word search
   *
   * @param {Element} wrapWl the game's wrap element
   * @param {Array} settings
   * constructor
   */
  function WordSearch(wrapEl, settings) {
    this.wrapEl = wrapEl;

    // Add `.ws-area` to wrap element
    this.wrapEl.classList.add('ws-area');

    //Words solved.
    this.solved = 0;

    // Default settings
    var default_settings = {
      'directions': ['W', 'N', 'WN', 'EN'],
      'gridSize': 10,
      'words': ['one', 'two', 'three', 'four', 'five'],
      'wordsList' : [],
      'debug': false
    }
    this.settings = Object.merge(settings, default_settings);

    // Check the words' length if it is overflow the grid
    if (this.parseWords(this.settings.gridSize)) {
      // Add words into the matrix data
      var isWorked = false;

      while (isWorked == false) {
        // initialize the application
        this.initialize();

        isWorked = this.addWords();
      }

      // Fill up the remaining blank items
      if (!this.settings.debug) {
        this.fillUpFools();
      }

      // Draw the matrix into wrap element
      this.drawmatrix();
    }
  }

  ...
  
  })();
//-----------------------------Remove accent for latin/hebrew letters---------------------------------------------------//

// Code for removing accents from Latin and Hebrew characters

...

//------------------------------Search language--------------------------------------------------//

// Function to determine what letters should be injected on the grid based on the first letter

...

// Initialize the game area element and create the word search game instance

... 
...

Answer №2

const list = document.querySelector("#list");
const items = ["CAR", "DOG", "CUP", "FAT", "RUG", "LAP"]; 

let counter = items.length;
while (counter>0) {
  chosenItem = Math.floor(Math.random() * counter);
  counter--;
    [items[counter], items[chosenItem]] = [items[chosenItem], items[counter]];
  var item = items[counter];
  var len = item.length;

  var display = '';
  while(len > 0){
    var randomIndex = Math.floor(Math.random() * len);
    display += item.charAt(randomIndex);
    item = item.substring(0, randomIndex) + item.substring(randomIndex + 1, len);
    len--;
  }
  display += "<br>";
  list.innerHTML += display;
}
<div id="list"></div>

Was this information useful?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The value could not be retrieved because the input name depends on the array index

To determine the name of the input based on the array index, use the following method: <div id="editAboutSantences<%=i%>" class="edit-container"> <div class="input-container"> <label> content: </label> ...

Is it possible to save an HTML5 Canvas screenshot directly onto the page?

After browsing numerous tutorials on saving HTML5 canvas screenshots as images and opening them in new tabs, I'm wondering if there's a way to display the captured screenshot in a pre-set div on the SAME WEBPAGE. Any suggestions or solutions woul ...

A reliable cross-browser solution for CSS sticky positioning

I designed a layout with 1 header and 3 vertical panels. The challenge is to ensure that all the panels can expand or contract horizontally to fill up 100% of the page width collectively, while also taking up 100% of the vertical space below the header (wh ...

Attempting to retrieve JSON data and present it in a grid layout

I have a JSON file with the following data: { "rooms":[ { "id": "1", "name": "living", "Description": "The living room", "backgroundpath":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSrsU8tuZWySrSuRYdz7 ...

Define a new type in Typescript that is equal to another type, but with the added flexibility of having optional

I have 2 categories: category Main = { x: boolean; y: number; z: string } category MainOptions = { x?: boolean; y?: number; z?: string; } In this scenario, MainOptions is designed to include some, none, or all of the attributes that belong to ...

What are the most effective methods for reorganizing and transforming database data?

As I navigate my MySQL database and extract data via PHP on a website, my goal is to represent the data in various visual formats. To accomplish this, I must also manipulate the data (such as creating totals, applying filters, etc.). My current query is w ...

Issue with the final transition of the last image in the Bootstrap carousel

I'm currently in the process of creating my own portfolio website. I've integrated a Carousel feature inspired by Bootstrap's example. However, I've noticed some glitches in the transitions between the first or second slides and the thi ...

Setting the CSS property `position: absolute; bottom: 0`, will move the div to the bottom of the screen rather than the bottom of

I'm currently working on a website where I want to attach a menu-bar to the bottom of the header using #menu { position: absolute; bottom: 0; } Unfortunately, instead of sticking to the bottom of the parent div, the menu-bar is stuck to the ...

Visit the embedded AJAX feature that is failing to show any results

I've been working on this seemingly simple problem for days now, but I'm still stuck. I have the following Go code... package main import ( "fmt" "net/http" "html/template" "database/sql" _"github.com/mattn/go-sqlite3" ...

Ways to run scripts or commands during the installation process of my Electron JS software on different operating systems

I have completed a project using electron js and now I am looking to create a Linux distributable with electron forge make. However, during the installation of this software on a Linux system, users need to execute the following command: sudo sed -i ' ...

Innovative solutions for seamless transformation of HTML designs into Silverlight 3.0

One of my challenges with clients is getting them on board with web applications. However, I am eager to try something new and explore the potential of Silverlight 3.0. It would be great to see if I can transform some of these applications into fully funct ...

Find all paragraphs with the CSS property "background-color" using JQuery

My task involves modifying the CSS of a paragraph tag that has a background color of #aaddff. The code I have written seems to be missing something, as the border is not appearing as expected. Should I use element.style or is there a different approach I ...

Tips for customizing the event target appearance in Angular 2?

After following the steps outlined in this particular blog post (section 3, event binding), I successfully added an event listener to my component class. I can confirm that it responds when the mouse enters and exits. <p class="title" (mouseenter)="unf ...

One easy method to verify a visitor's Facebook login status

Currently, I am in the process of developing a WordPress plugin and looking for an easy way to determine if a page visitor is logged in with Facebook. Upon attempting to use the JavaScript SDK, I encountered the following error: The given URL is not all ...

Unable to retrieve information from server

enter image description here <!DOCTYPE html> <html ng-app="myApp"> <head> <title>ContactApp</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootst ...

Is there a way to enhance the functional purity by creating a single function that subscribes and returns a

I'm currently developing a project that involves receiving humidity data from a raspberry pi sensor connected to a backend. Within my Angular Component, I am aiming to display this data in a functional and pure manner. However, I have some doubts rega ...

Error encountered: Java NullPointerException in Applet

When attempting to embed an applet into an HTML file for a university class demonstration, I consistently encounter a NullPointerException dialog upon execution. What could be causing this issue? <html> <head> <title> My Pacman Gam ...

Struggling to store the selected image as the featured image on Wordpress

Hey there, I'm Nadeem and I'm diving into PHP and WordPress as a beginner. While working on custom plugin development, I've hit a roadblock that's been causing me some trouble. The main issue is that I can't seem to save the Featur ...

Flickering transitions in Phonegap and jQuery Mobile pages

As a beginner in Phonegap/jQuery Mobile, I have encountered a frustrating issue of a white screen appearing during page transitions. Despite trying various solutions found online, such as using -webkit-backface-visibility:hidden;, the problem persists. I ...

The onClick event in React/NextJS is not functioning properly when applied to an external component

One dilemma I am facing involves my main page and a button component that I have created to be reused throughout my project. Strangely, when I add the onClick event to the external component, the click event does not seem to work. However, if I create the ...