Unneeded return is necessary when utilizing recursion and restarting the application

Recently, I successfully recreated the 2048 game in Java, which was a pleasant surprise to me as I didn't expect to create something this "advanced."

During the game, when tiles are moved, a new square/tile/number needs to be generated. To find an available spot for the new tile, my code randomly selects a number between 0 and 15 (tiles are numbered from 0 to 15 using a multidimensional array with 4 columns and 4 rows). If the chosen spot is already occupied, the function recalls itself by returning the existing tile. In cases where the spot is unoccupied, I simply return a number that is not utilized later. Can you help me identify what am I doing wrong?

Another question I have is related to starting a new game. Currently, I reset all variables in the newGame() function. Is there a way to restart the application instead? I couldn't find any information on the website regarding this.

I would also appreciate feedback on whether I followed programming conventions and your overall thoughts on my approach to recreating this game for practice. Thank you for taking the time to review this.

Below is the code snippet:

// Code goes here

Answer №1

Just like in @RyanJ's comment, you can define the function newCell() with a return type of void:

private void newCell() {
    int x = (int)(Math.random() * 4);
    int y = (int)(Math.random() * 4);
    if (cell[x][y] != 0) {
        newCell();
    } else {
        cell[x][y] = twoOrFour();
    }
}

You could achieve the same result using a loop as well:

private void newCell() {
    int x ;
    int y ;
    do {
        x = (int)(Math.random() * 4);
        y = (int)(Math.random() * 4);
    } while (cell[x][y] != 0);
    cell[x][y] = twoOrFour();
}

However, both of these approaches have drawbacks as it may take a long time to find an empty space. In the recursive version, there is also a possibility of running into a StackOverflowException. A more effective solution would be to create a list of empty cells and randomly select one:

private void newCell() {
    List<Integer> availableCells = new ArrayList<>();
    for (int i = 0; i < 16; i++) {
        int x = i / 4 ;
        int y = i % 4 ;
        if (cell[x][y] == 0) {
            availableCells.add(i);
        }
    }
    int nextCell = availableCells.get((int)(Math.random() * availableCells.size()));
    cell[nextCell / 4][nextCell % 4] = twoOrFour();
}

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

Can CSS3 animations be executed sequentially for each child element?

Have you ever tried creating a CSS3 animation in HTML? You can check out an example here. <div class="parent"> <a href="#">First</a> <a href="#">Second</a> <a href="#">Third</a> </div> With the ...

I want to set a single background image for all slides in fullPage.js. How can I achieve this

I am attempting to replicate a similar effect as shown in this example: The demonstration above utilizes the fullPage.js plugin. You may have noticed how the background image remains consistent while navigating through different sections. I have searched ...

Placing a moveable object in a designated spot for dropping at the desired location

I've been attempting to clone and drop a draggable object at the exact position within a droppable area where the drop event takes place. While I have come across examples online that demonstrate appending draggables to droppables, they all tend to re ...

Tips for showcasing HTML as code tailored to certain programming languages

While browsing the web, I stumbled upon a website that had SQL code displayed with specific classes and styles applied to it. For example, table names were colored blue when inspected. Here is a glimpse of what I encountered: I'm curious about how t ...

Aligning a Facebook share button to the center of a webpage

On my webpage, I have the following section: <div style="align:center"> <div id="fb-root"></div> <script src="http://connect.facebook.net/en_US/all.js#appId=217585988283772&amp;xfbml=1"></script> <fb:like hre ...

A div element featuring a border with transparent edges on the top right and bottom left corners

Does anyone know how to code the border for the upper right corner and lower left corner of the box (as shown in the image below)? I would really appreciate some help. Thank you in advance! This is the HTML <div class="carouselle"> <div clas ...

Mobile devices not showing the Navbar bootstrap menu

My header.php works perfectly on desktop, but the navigation bar is not displaying properly on mobile devices. Here is my code: <!DOCTYPE html> <html> <head> <title>International Pvt. Ltd.</title> <meta name="viewpo ...

Designing a nested box layout with bootstrap HTML/CSS styling

Can anyone provide guidance on how to create a HTML/CSS layout similar to the image below? I am specifically struggling with designing the silver "Add corkscrew" box, a white box beneath it, and then another silver box nested within. Any suggestions on ho ...

Aligning table data elements within a division

Currently working on revamping a tech night website for my school. I made some changes to the navbar, switching it from the side to the top. However, I'm struggling to get the table data and menu to center properly within the div. If you'd like ...

Button from Bootstrap extends beyond the page on mobile devices

I am facing an issue with my button. It looks great on desktop, but when I switch to the mobile version, it goes beyond the screen width like in the image below: 1) How can I prevent this from happening with the code provided in my bootply? 2) Also, how ...

Manipulating CSS rules using JavaScript/jQuery

My goal is to create a function that generates a grid based on table data. While the function itself seems to be working, I am encountering an issue where the classes applied are not resulting in any style changes. Below is a snippet of my function: $(doc ...

Styling a Fixed Header in CSS/HTML - Scroll Effect

Is it possible to hide only the upper part of the nav-bar, similar to the behavior in WhatsApp? I am using material-ui for this particular use-case. Currently, my implementation causes the app-bar to extend only when the scroll position is less than 48px, ...

Issue with Font Awesome 5 icons not displaying properly after integrating Bootstrap

Trying to spruce up my buttons by adding some fontawesome icons from bootstrap. The icons I'm using are: fas fa-user fas fa-users They display fine without any styling. However, when I apply the bootstrap button css, the "fa-users" icon appears as ...

Properly Positioning Text within React's Material UI Components

I am encountering a simple issue where I am trying to align '01/01/2020' with 'A00002'. To view my code on CodeSandbox, please visit CLICK HERE <div className={classes.root}> <Typography variant="h6" className={cla ...

Center an absolutely positioned div using CSS

What is the best way to position an absolute div at the center? <div class="photoFrame">minimum width of 600px, positioned absolutely</div> jQuery var screenWidth = $(window).width(); $('.photoFrame').css({'margin-left': ...

@media doesn't seem to be functioning properly when the screen width is below

I've been working on making my website fully responsive, but I've run into an issue where it won't recognize anything below 980px in width. Here is the CSS code I'm using: @media screen and (max-width:1029px){ h1{ font-size ...

Adjust the background color of the dropdown menu

I'm struggling to change the background color of the property address picker dropdown from transparent to white. I've been trying different things but can't seem to get it right. Any suggestions? Additionally, I want to change the cursor to ...

Encounters SessionNotCreatedException error when executing test in Firefox

I am currently utilizing the following versions: Selenium: 3.6.0 Mozilla: 56.0 Gecko Driver: V 0.19.0 Whenever I execute the testng.xml file for Mozilla Firefox, it throws the subsequent exception: Log: org.openqa.selenium.SessionNotCreatedException ...

Which versions of Selenium are recommended for running automated tests with IE11 browser?

I am looking for recommendations on the best versions to use for Selenium automation with IE11 browser on a 64-bit machine. Specifically, I need advice on: Java version Selenium version IE Webdriver version TestNG version ...

"I'm facing an issue with aligning elements in my ReactJS application using CSS Flexbox. Despite setting up a flexbox layout, I am unable to

Despite setting up a flexbox to align my elements, I am struggling with vertical centering on my page. I have made sure to use a container for the page and set brute size with viewport units. Here is my sandbox: https://codesandbox.io/s/rlk3j68pmq. Belo ...