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

The text box and buttons are not properly aligned

https://i.stack.imgur.com/lxeKw.png I am puzzled by the misalignment of my buttons and text box. <div class="form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12" for="Pic">Picture/File</label> <div class="col ...

HTML: Unable to align text in the center using the <div> tag

Working on a website for our Roblox group I've been attempting to center this text (and the button below), but it just doesn't look right... Check out this image Although it technically "centers", something still seems off. I've searched h ...

Utilizing the calc() function to determine height dimensions

I created a very simple layout with 5 divs, which can be viewed here: http://jsfiddle.net/8tSk6/. In this layout, I want the div with the ID "kubka" to have a height of 100% - 100px (height: calc(100% - 100px);). However, I am running into issues as it i ...

What is the best way to create floating text that appears when clicked, similar to the mechanics

https://i.stack.imgur.com/nRKG1.jpg Upon clicking the "big cookie" in my game, a popup appears displaying the number of cookies earned (like +276.341 septillion in this image). The popup slowly moves upward and then fades out. I successfully incorporated ...

What is the best way to position the list element to align with the top of a div container?

To see a live example, visit this link. My goal is to create a line that separates two li elements within a nested ul. However, the line ends up taking the width of the container ul instead of the div containing the entire structure. In the provided examp ...

The default remote proxy is of an unknown version, but the attempt to connect to 10.169.230.222 on port 5558 has failed due to a connection timeout

Attempting to start the selenium grid with a VM as the hub An issue is showing up in the grid console: localhost:4444/grid/console. This is the syntax I used in the command prompt of the node machine: java -jar C:\Users\Downloads\selenium ...

Tips for aligning inputs vertically and stretching them horizontally with bootstrap flex only

For a practice exercise, I want to achieve vertical left alignment and horizontal stretching of input fields using only Bootstrap Flex (or CSS3 flexbox), without relying on Bootstrap Grid or CSS3 grid layout. Here is the code snippet (also available on co ...

Tips for confining a float within a div with fluctuating space

I have a scenario where I have multiple divs ('group') containing text, and there is a floated div ('toggle') in the bottom corner. The current code works well if the text length in 'group' is consistent, but the position of t ...

Challenges in using Selenium and Java to interact with shadow DOM anchor tags

Currently, I am in the process of learning how to use selenium for automating tasks. A recent challenge I faced involved attempting to automate a click on a hyperlink within the developer.salesforce.com website. Upon running the code I had written for th ...

What is the proper way to encode image URLs for use in CSS?

For the div element in my code, I want to allow users to input a URL that will be applied as a CSS background image, like this: background-image: url("/* user specified URL here*/") I'm concerned about security. How can I properly escape the URL to ...

Vertical alignment with flexbox not functioning properly in Internet Explorer 11

I am attempting to use flex to center an icon within two divs. Below is the code snippet: .div-1 { width: 50px; height: 50px; display: flex; border-radius: 50%; background-color: #228B22; } .div-2 { margin: auto; } i { color: #ffffff; } &l ...

Tips for adjusting the size of Bootstrap 5 card to fit various image sizes responsively

I am facing an issue where I have four images of different sizes placed in 4 cards in a row. Due to the varying heights of the images, the cards appear untidy. I am looking for a way to fix this problem while ensuring that the layout remains responsive. Be ...

Require an additional button to dynamically load more content and shift all existing elements further down the page

I am looking to implement a "load more" button for an Instagram feed on my website. My current approach involves increasing the height of a specific section while moving the rest of the page down. This is what I have tried: <script> $(document.ready ...

I am currently facing a challenge with Bootstrap, as I am trying to design a webpage for small devices using a 1:4:1 format, but I am struggling to get it right

column 1 and column 3(left and right cols) have successfully passed the test case, but not column 2 (the middle one) that I have commented on in the code. Please help. Thank you. The problem has certain conditions that would have been easier to understa ...

Internet Explorer is failing to display images

Hey there! I'm having an issue with my product listing where the images are not showing up in Internet Explorer, even though it works fine in all other browsers. Here is the code snippet for the image container: Image container: <div class="image ...

Assistance with changing styles

Hey there, I could really use some assistance. I've created a style switcher, but I'm struggling to figure out how to replace the stylesheet properly. Currently, my code empties the <head> element when what I really need is for it to simply ...

The layout designed with CSS Grid features two static sidebars, but unfortunately, the main content is not aligning

After deciding to experiment with CSS-grid, I encountered a frustrating roadblock. My goal was to create two fixed navigation bars on the left and right sides, with the main content in the center that would be scrollable. <div class="grid"> < ...

Ways to ensure that a test case fails when the values do not match

I am faced with a situation where I have to modify an Employee's name, and when I hit the Cancel button, the Employee's name field should revert back to its original value. My task is to confirm whether the Cancel button is functioning correctly. ...

Stacking elements in perfect alignment

Seeking assistance with React/MUI as a newcomer. I am utilizing a Stack of TextFields, which are resizing effectively based on screen width. <Stack direction="row" sx={{ margin: "16px" }} > ...

Focus on styling a single theader element within a jQuery Data Table with CSS

Struggling to work with a dynamic Jquery Data Table that has 10 table headers. I am having difficulty adding a class or an Id in the code to the specific th element with the title 'Unused'. In my .css file, I attempted: [title~= Unused] { ba ...