If a box in the grid contains a certain class, then JavaScript should be

I've set up a grid featuring a player, represented by a yellow box, along with obstacles denoted by black boxes marked with the .ob class. I want to prevent the player from moving into these obstacle squares when the 'UP' button is clicked.

One idea I had was to check if the next square has the .ob class and block movement in that direction. Do you have any other suggestions?

let moveCounter = 0;
var grid = document.getElementById("grid-box");

for (var i = 1; i <= 50; i++) {
  var square = document.createElement("div");
  square.className = 'square';
  square.id = 'square' + i;
  grid.appendChild(square);
}

var obstacles = [];

while (obstacles.length < 20) {
  var randomIndex = parseInt(49 * Math.random());
  if (obstacles.indexOf(randomIndex) === -1) {
    obstacles.push(randomIndex);

    var drawObstacle = document.getElementById('square' + randomIndex);
    $(drawObstacle).addClass("ob")
  }
}
var playerTwo = [];

while (playerTwo.length < 1) {
  var randomIndex = parseInt(49 * Math.random());

  if (playerTwo.indexOf(randomIndex) === -1) {
    playerTwo.push(randomIndex);

    var drawPtwo = document.getElementById('square' + randomIndex);
    $(drawPtwo).addClass("p-1")
  }
};

$('#button_up').on('click', function() {
  moveCounter += 1;

  $pOne = $('.p-1')
  var id = $pOne.attr('id')
  var idNumber = +id.slice(6);
  var idMove = idNumber - 10
  var idUpMove = 'square' + idMove;
  $pOne.removeClass('p-1');
  $('#' + idUpMove).addClass('p-1');
});
#grid-box {
  width: 400px;
  height: 400px;
  margin: 0 auto;
  font-size: 0;
  position: relative;
}

#grid-box > div.square {
  font-size: 1rem;
  vertical-align: top;
  display: inline-block;
  width: 10%;
  height: 10%;
  box-sizing: border-box;
  border: 1px solid #000;
}

.p-1 {
  background-color: yellow;
}

.ob {
  background-color: black;
}
<div id="grid-box"></div>
<div class="move">
  <button id="button_up">UP</button><br>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

Check out the code on jsFiddle

Answer №1

Below is the code snippet recommended for use:

$('#button_up').on('click', function() {
  moveCounter += 1;

  $pOne = $('.p-1')
  var id = $pOne.attr('id')
  var idNumber = +id.slice(6);
  var idMove = idNumber - 10
  var idUpMove = 'square' + idMove;
  if($('#' + idUpMove).hasClass('ob')){
      return false;
  }
  $pOne.removeClass('p-1');
  $('#' + idUpMove).addClass('p-1');
});

The code checks whether the next selected class contains the ".ob" class. If it does, the process is halted; if not, the process continues.

if($('#' + idUpMove).hasClass('ob')){
      return false;
  }

Visit this Fiddle link

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

How to pause a loop temporarily before proceeding with the next iteration

I am facing a challenge where I want to trigger two events simultaneously, but only one event should be allowed to continue at a time. If an event is already in progress, I need the ability to forcefully stop it and allow the other event to take control. S ...

"Trouble with server communication: data array not being passed to hbs

In my GET route, I have the following: app.get(("/employee/:id"), (req, res) => { data.getEmployeeByNum(req.params.id).then((data) => { res.render("employee", {employee: data}); }).catch(function(reason) { res.render("employe ...

Unable to set the height for ul/div elements

I'm struggling to make my navbar appear when I click the "menu button". The div seems to be present in the code, but with a height of 0. Here's the relevant section of the code causing the issue. Any suggestions on how I can resolve this? var ...

Enhancing live query functionality and providing a substitute for DOMNodeInserted specifically tailored for

I have searched multiple times on various platforms for a solution to my specific issue, but have not found one that fits my unique circumstances. My goal is to replace outdated code such as livequery and DOMNodeInserted. See examples below. I am current ...

Is it possible to have both Node.js and browser code in the same file using webpack, while ensuring that only the browser code is accessible and the Node.js code remains hidden?

I need to work with a file that contains both Node.js and browser code. It's crucial that the Node.js code remains hidden when running in the browser environment. Is it possible for Webpack to exclude specific sections of the code based on the enviro ...

Customizing blockquote styling in QuillJS with a unique class

Currently, I am exploring a method to include a custom class when the user selects the blockquote toolbar button. When the blockquote is clicked, it generates the following element: <blockquote class="ql-align-justify">this is my quoted tex ...

Leveraging backstretch.js in combination with blur.js (or equivalent)

Query Update I provided a response to the query below, however, I am experiencing some lag and a noticeable stepped transition between images. Can anyone offer advice on how to optimize this issue? Perhaps it would be better to go back to using a static ...

Utilize viewport activation to determine browser width

Is there a way to dynamically add the viewport-meta tag only for devices with screen widths larger than 680px? If the screen is smaller than 680px, then the responsive style file should be enabled instead. I attempted to achieve this by placing the follow ...

Can anyone help me with fixing the error message 'Cannot assign to read-only property 'exports' of the object' in React?

Recently, I decided to delve into the world of React and started building a simple app from scratch. However, I have run into an issue that is throwing the following error: Uncaught TypeError: Cannot assign to read-only property 'exports' of o ...

Problem with ng-repeat and custom directive in the header row

I'm currently in the process of transitioning our thead generation to a directive. However, I've noticed that when using this directive, the headers lose their styling and become clustered on the left side. Can anyone provide some assistance on w ...

Unlocking the Power of Session Variables in AngularJS using Ui-router

Currently, I am utilizing Angular to manage routes. On the server side, Passport is being used so that I can access the user session variable req.user in my views. However, when dealing with a route rendered by ui-router, my req.user ends up being undefine ...

import component dynamically from object in Next.js

Currently, I have a collection of components that I am aiming to dynamically import using next/dynamic. I'm curious if this is achievable. Here's the object in interest: // IconComponents.tsx import { Tick, Star } from 'components ...

JavaScript counter unexpectedly resetting to zero instead of the specified value

After gathering feedback from voters: My current issue revolves around a Java counter I created. Ideally, the numbers should start at 0 and increment to the specified number upon page load. You can see an example of this functionality here: https://codepe ...

Slider handle for Material UI in React component reaches the range value

In my application, I am using a range slider component from material-UI. The main page displays a data table with the fields: id, name, current price, new price. The current price for each item is fixed, but the new price will be determined based on the s ...

Center elements both vertically and horizontally by utilizing Bootstrap flexbox

Having delved into the documentation of Bootstrap 4 Flex, I am facing difficulties in making the "align-item-center" property function as desired. Despite trying various examples found online, I am unable to alter the vertical alignment of elements. This s ...

Ways to center vertically aligned buttons within cards in a React application with Material-UI

I've encountered an issue with my ReactJS project using material-ui. I created 3 cards, each with a paragraph of varying lengths. This caused the buttons to be misaligned vertically in each card, as the position differs due to paragraph size differenc ...

display the $scope as undefined in an angular application

Below is my code snippet: var exchange = angular.module('app', []); exchange.controller('ExchangeController', ExchangeController); function ExchangeController($scope, $http) { $scope.items = []; $http ...

The Material UI export of 'useInsertionEffect' (imported as 'useInsertionEffect$1') was not located within the 'react' library while utilizing the Appbar component

https://i.sstatic.net/twJwh.png 1: https://i.sstatic.net/Y2Zdo.png**strong text**https://i.sstatic.net/twJwh.png While attempting to implement the Appbar component from Material UI, I encountered an unexpected error. ...

Is it possible for Typescript to resolve a json file?

Is it possible to import a JSON file without specifying the extension in typescript? For instance, if I have a file named file.json, and this is my TypeScript code: import jsonData from './file'. However, I am encountering an error: [ts] Cannot ...

When attempting to import vue.js within a JavaScript file in a Django application, an error of 'Uncaught SyntaxError: Cannot use import statement outside a module' is encountered

Currently, I am delving into incorporating vue.js into a live django project and have come across a stumbling block. After setting up npm in the venv environment and installing the vue package, my next step is to create a Vue object within a js file using ...