Designing Games with Matrix Elements

Greetings to the StackOverflow Community!

Currently, I am working on developing a JavaScript version of the well-known game Pentago as a personal side project before resuming my studies in the fall. However, I have hit a roadblock and need some guidance on how to proceed further with this project.

Initial Strategy

Initially, I decided to create four matrices and store them in a list, with each matrix representing a section of the Pentago board. However, implementing this approach posed several challenges when it came to iterating over the matrices and checking for a winning scenario where a row of five game tokens is placed.

Revising My Approach

Seeking an alternative perspective, I was advised to use a single matrix instead of four. While this simplifies certain aspects, rotating each section becomes slightly more complex, albeit manageable.

The Problem at Hand...

My main concern revolves around determining whether a player has won the game upon placing a token in a specific position. Here’s what I believe I understand:

  • The function to determine the game's conclusion triggers after a player rotates a quadrant.

  • Subsequently, identifying the player who placed the last token enables focusing solely on their tokens for consideration.

  • I need to traverse the matrix starting from the location of the last token placed and check for adjacent tokens recursively until a sequence of five tokens is found diagonally, horizontally, or vertically.

Below is the code I have developed for this game so far. Any assistance would be greatly valued as I'm stuck at this particular juncture! Thanks in advance!


Current Code Progress

https://github.com/jakenewby/pentagojs/tree/master/www/app

var game = (function (players){

    var self = {};
    self.numTokensPlaced = 0;

    // initialize the empty pentago board
    self.board = [];
    for(var i=0; i<6; i++)
    {
        self.board[i] = [];
        for(var j=0; j<6; j++) 
        {
          self.board[i][j] = null;
        }
    }

    // rotate one of the quadrants of the board
    self.rotateSection = function (section, direction)
    {
      if(isGameOver())
      {

      }
      else
      {
        if(direction == 'clockwise')
        {
          /*
            var newGrid = [];
            var rowLength = Math.sqrt(section.length);
            newGrid.length = section.length

            for (var i = 0; i < section.length; i++)
    
            .........
        }
        else
        {
          // code for rotation counterclockwise
        }
        switchTurns();
      }
    }

    // place a token on the board given the player id,
    // section, and coordinates where the token is being placed
    self.placeToken = function(playerid, location)
    {
        if (self.board[location[0]][location[1]] != null)
        {
            return location.toString() + ' is already taken';
        }
        else
        {
            // logic for placing token and checking game status
        }
    }

    .......

    return self;
}());


Game Instructions

To play, insert a marble in a quadrant and subsequently rotate one of the quadrants by 90 degrees in either direction. Achieve a line of five marbles either horizontally, vertically, or diagonally to win!

Answer №1

If I were to tackle this with a set board, my approach would involve creating an array to store potential axes:

let axes = [];

// rows
for (let i = 0; i < 6; ++i) {
    axes.push(this.board[i]);
}
// columns
for (let j = 0; j < 6; ++j) {
    let column = [];
    for (let i = 0; i < 6; ++i) {
        column.push(this.board[i][j]);
    }
}
// diagonals
axes.push([this.board[0][1], this.board[1][3], ...])
// and two more are calculated here

By utilizing this array, one can easily navigate through all the axes and identify consecutive fills that belong to a specific player.

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

Using react-big-calendar exclusively for the month view

I need help customizing react-big-calendar to only show the month view and trigger a function when a date is selected. I want to remove all other functionalities related to week, day, agenda, and time display. Essentially, I just want to display the month- ...

Utilizing the spread operator to map an array within another array

Exploring the spread operator inside an array to map values from another array has led to unexpected behavior. When attempting to return 2 objects using map within the array, only the last object is being returned. Below is the code snippet: const cats = [ ...

Troubleshooting: AWS Lambda function fails to add item to DynamoDB table using put and putItem operations

Currently, I am exploring the use of Lambda functions to create a basic database API. The intention is to make direct calls to each Lambda function via its function URL. So far, I have successfully managed to retrieve a database item by its id using Lambd ...

Accessing vector features by clicking in close proximity to, but not directly on, a vector in OpenLayers

I'm working with an Open Street Map that includes vectors (lines) displaying on the roads. Currently, I can only retrieve information about a vector by clicking directly on its pixels. Is there a way to make it so that I can click near the vector (a f ...

Preserve the XHR-generated configuration when the browser is refreshed

My PHP page features a navigation menu with options such as Home, About Us, and Profile. When clicking on the "About Us" link from the home page, it loads an Ajax response displaying the information without reloading the page. However, if the user decide ...

Integrate a loading screen on the website

Check out the awesome animation I created! Can this be used as a preloader on my website? Should I stick to creating a simple .gif or opt for a CSS animation instead? If it’s feasible, how do I go about integrating it into my site? Most tutorials suggest ...

How to pass parameters while updating parent values in VueJS using emit?

Explaining my dilemma with uploading images: In my form, users can upload images using the following code snippet: <input id="visualisation_upload" @change="onThumbnailChanged" name="visualisation_upload" accept="imag ...

A guide to validating a pair of fields within a single object using React hooks and the Yup library

{ label: 'Room', name: 'room', rule: yup.array(yup.object()).required(), renderer: (data: any) => { const { control, register, errors } = useFormContext(); return ( ...

Issue with Firebase Real-time database failing to acknowledge authentication status

I am encountering difficulties when trying to access my real-time databases in Firebase with set rules. I have a total of 3 databases - 1 default and 2 additional ones. The rules for all three are the same: { "rules": { ".read": & ...

Eliminate the excess padding from the Material UI textbox

I've been struggling to eliminate the padding from a textbox, but I'm facing an issue with Material UI. Even after setting padding to 0 for all classes, the padding persists. Could someone provide guidance on how to successfully remove this pad ...

How can you update the options within a select tag depending on the selected index of another select tag using AngularJS?

Consider the following code snippet: $scope.letters = ['A', 'B', 'C', 'D']; $scope.numbers = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]; $scope.selectedLetter = 0; There are two select tags in t ...

Utilizing AngularJS: Establishing a Universal Parent State in UI-Router for Modals and Shared Components

In my code using UI-Router and Bootstrap-ui modal, I have defined the state as shown below. reference var state = { name: 'modala', parent: 'home', onEnter: function($modal, $state) { modalInstance = $modal.open({ ...

Dealing with Javascript exceptions and sending email notifications in Django

I appreciate the traditional method of handling server-side exceptions in Django using Python. I am interested in finding a similar approach for client-side exception handling in JavaScript. So far, I have come across only one option which is DamnIT, but ...

The text content is not in alignment with the server-rendered HTML for translation purposes with i18n

I have successfully implemented i18n in my Next.js project. The folder structure for my locales is as follows: public/locales/en/translation.json and public/locales/fr/translation.json The error I am encountering is: Uncaught Error: Text content does n ...

A guide to retrieving all keys from a JSON object in Javascript

{"data": {"characters":[ {"name":["Harry Potter"],"age":["18"],"gender":["Male"]}, {"name":["Hermione Granger"],"age":["18"],"gender":["Female"]} ]} } In the given JSON data, I am interested in retrieving the keys like name, age, gender for ea ...

Looping through an array of images using JavaScript

Currently, I have a computer science test at school, and the main question is to create a traffic light that changes colors in a loop using arrays. I am facing some challenges with this question, but I believe I am close to solving it. Below is my code sni ...

What is the best way to activate a click event on a dynamically generated input element with the type of 'file'?

I am facing a challenge in dynamically adding an input field of type 'file' to a form. The requirement is to allow the end user to add multiple files to the form, necessitating the use of an array concept. While I am able to inject dynamic elemen ...

Is there a way to apply a setTimeout to a <div> element upon the first click, but not on subsequent clicks?

Check out the fiddle I've created: http://jsfiddle.net/dkarasinski/dj2nqy9c/1/ This is the basic code. I need assistance with a functionality where clicking on a black box opens a black background and then after 500ms a red box appears. I want the ...

JavaScript Time and Date Formatting

I'm pretty new to programming, especially in Javascript. Can someone help me simplify my code? I'm trying to create a dropdown for months and an input field for the year. Is there a more efficient way to make the month select box? Also, how can ...

What's the issue with my ExpressJS req.query not functioning as expected?

My NodeJS repl setup includes an input, button, and h1 element. The goal is to update the HTML inside the h1 element with the value of the input upon button click. Here's a glimpse of my code: index.js: const Database = require("@replit/database ...