简体   繁体   中英

How do I shift a number to empty space based on user input?

This code is a simulation of Game of 15 puzzle. The output should be:

在此处输入图片说明

I'm currently at the stage trying to do a switch statement in order to move a number to the empty space according to user input. Here's what I have attempted. Thank you.

import java.util.ArrayList;
import java.util.Scanner;

public class Game {
public static void main(String[] args) {
int rowNum=4;
int colNum=4;
int[][] gameboard = new int[rowNum][colNum];
ArrayList<Integer> used = new ArrayList<Integer>();
int emptySlot = (int) (1 + Math.random() * 16);

for(int row = 0; row < rowNum; row++) {
    for(int col = 0; col < colNum; col++) {
        if(row*gameboard.length + col == emptySlot) {
            System.out.print("    ");
            continue; //skip empty slot
        }
        int number;
        while(used.contains(number = (int) (1 +      Math.random() * 15)));
        used.add(number);
        gameboard[row][col] = number;
        System.out.printf("%-4d",gameboard[row][col]);
      }
    System.out.println();
    }

    System.out.println();
    System.out.print("Enter a move: (l)eft, (u)p,    (r)ight, (d)own, or (exit):");
    Scanner sc = new Scanner(System.in);
    int px=0;
    int py=0;
    String move = sc.nextLine(); 
    switch (move) {
    case "l": 
        px -= 1;
        break; 
    case "u": 
        py +=1;
        break; 
    case "r": 
        px += 1;
        break; 
    case "d": 
        py -=1;
        break; 
    case "exit":

        break;

    }
    sc.close();
    }   

 }

This is a game as it seems, you should add a game loop, i recommend you read this to understand fully what a game loop is: game loop

Secondly i would recommend using "0" as an empty slot on your puzzle, that makes things way easier, locating the 0 and changing it place with your switch statement with its neighbors on your list.

Unfortunately your question opinion based, which is in contrast with stackoverflow policy, I hope that answered all there was.

You need to put the user options within a loop as well if the desired outcome can't be achieved in a single move. I changed the gameboard type to String for shorter display code. I'm moving the empty space, rather than a number next to it - but that's just a detail.

public class ShiftGame
{
    public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    final int rowNum = 4,
              colNum = 4;
    int row = 0, 
        col = 0,
        number = 0;
    String[][] gameboard = new String[rowNum][colNum];
    ArrayList<Integer> used = new ArrayList<Integer>();

    int emptySlot = (int) (1 + Math.random() * 16);
    int py = emptySlot / 4,                                                                 // Empty row
        px = emptySlot % 4,                                                                 // Empty col
        oldpy,                                                                              // For old row num
        oldpx;                                                                              // For old col num
    String move = "x",
           copy;

    for (row = 0; row < rowNum; row++)                                                      // Generate & display starting number table ...
    {
        for (col = 0; col < colNum; col++)
        {
            if (row * rowNum + col != emptySlot)
            {
                while (used.contains(number = (int) (1 + Math.random() * 15)));
                used.add(number);
                gameboard[row][col] = "" + number;
            }
            else 
                gameboard[row][col] = "    ";
            System.out.printf("%-4s", gameboard[row][col]);
        }
        System.out.printf("\n");
    }
                                                                // ... overwriting the empty slot

    System.out.println();
    while(!move.equals("e"))                                                                // Cycle game loop till user ends it ...
    {
        System.out.print("Enter a move: l(eft), u(p), r(ight), d(own), or e(xit):");
        oldpx = px;
        oldpy = py;
        move = sc.nextLine();
        switch (move)                                                                       // Change vacancy position ...              
        {
            case "l": 
                if (px != 0)
                    px -= 1;
                else
                    System.out.println("\nAlready at leftmost edge - can't move empty slot left!");
                break;

            case "u": 
                if (py != 0)
                    py -= 1;
                else
                    System.out.println("\nAlready at top edge - can't move empty slot up!");
                break;

            case "r": 
                if (px != 3)
                    px += 1;
                else
                    System.out.println("\nAlready at rightmost edge - can't move empty slot right!");
                break;

            case "d": 
                if (py != 3)
                    py += 1;
                else
                    System.out.println("\nAlready at bottom edge - can't move empty slot down!");
                break;

            case "e":
                break;

            default: System.out.println("You have entered an invalid claracter. "
                    + "\nOnly (l)eft, (u)p, (r)ight, (d)own, or (e)xit) are valid entries.");
        }

        if (!move.equals("e"))                                                              // Interchange new & old positions ...
        {
            copy = gameboard[py][px]; 
            gameboard[oldpy][oldpx] = copy;
            gameboard[py][px] = "    ";
            System.out.println();
            for(row = 0; row < rowNum; row++)                                               // ... and display new table
            {
                for(col = 0; col < colNum; col++)
                    System.out.printf("%-4s", gameboard[row][col]);
                System.out.printf("\n");
            }
        }

    }
    System.out.printf("\n\nGame over. Good Day !");                                         // Close game.
    sc.close();
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM