Question

In: Computer Science

I cant get this to compile in java idk if im making the wrong file or...

I cant get this to compile in java idk if im making the wrong file or what but this si the code I was given I would like stsep by step java instuctions and which compiler to use to execute this code

  • import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Random;

    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;

    // We are going to create a Game of 15 Puzzle with Java 8 and Swing
    // If you have some questions, feel free to ue comments ;)
    public class GameOfFifteen extends JPanel { // our grid will be drawn in a dedicated Panel
      
    // Size of our Game of Fifteen instance
    private int size;
    // Number of tiles
    private int nbTiles;
    // Grid UI Dimension
    private int dimension;
    // Foreground Color
    private static final Color FOREGROUND_COLOR = new Color(239, 83, 80); // we use arbitrary color
    // Random object to shuffle tiles
    private static final Random RANDOM = new Random();
    // Storing the tiles in a 1D Array of integers
    private int[] tiles;
    // Size of tile on UI
    private int tileSize;
    // Position of the blank tile
    private int blankPos;
    // Margin for the grid on the frame
    private int margin;
    // Grid UI Size
    private int gridSize;
    private boolean gameOver; // true if game over, false otherwise
      
    public GameOfFifteen(int size, int dim, int mar) {
    this.size = size;
    dimension = dim;
    margin = mar;
      
    // init tiles
    nbTiles = size * size - 1; // -1 because we don't count blank tile
    tiles = new int[size * size];
      
    // calculate grid size and tile size
    gridSize = (dim - 2 * margin);
    tileSize = gridSize / size;
      
    setPreferredSize(new Dimension(dimension, dimension + margin));
    setBackground(Color.WHITE);
    setForeground(FOREGROUND_COLOR);
    setFont(new Font("SansSerif", Font.BOLD, 60));
      
    gameOver = true;
      
    addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
    // used to let users to interact on the grid by clicking
    // it's time to implement interaction with users to move tiles to solve the game !
    if (gameOver) {
    newGame();
    } else {
    // get position of the click
    int ex = e.getX() - margin;
    int ey = e.getY() - margin;
      
    // click in the grid ?
    if (ex < 0 || ex > gridSize || ey < 0 || ey > gridSize)
    return;
      
    // get position in the grid
    int c1 = ex / tileSize;
    int r1 = ey / tileSize;
      
    // get position of the blank cell
    int c2 = blankPos % size;
    int r2 = blankPos / size;
      
    // we convert in the 1D coord
    int clickPos = r1 * size + c1;
      
    int dir = 0;
      
    // we search direction for multiple tile moves at once
    if (c1 == c2 && Math.abs(r1 - r2) > 0)
    dir = (r1 - r2) > 0 ? size : -size;
    else if (r1 == r2 && Math.abs(c1 - c2) > 0)
    dir = (c1 - c2) > 0 ? 1 : -1;
      
    if (dir != 0) {
    // we move tiles in the direction
    do {
    int newBlankPos = blankPos + dir;
    tiles[blankPos] = tiles[newBlankPos];
    blankPos = newBlankPos;
    } while(blankPos != clickPos);
      
    tiles[blankPos] = 0;
    }
      
    // we check if game is solved
    gameOver = isSolved();
    }
      
    // we repaint panel
    repaint();
    }
    });
      
    newGame();
    }
      
    private void newGame() {
    do {
    reset(); // reset in intial state
    shuffle(); // shuffle
    } while(!isSolvable()); // make it until grid be solvable
      
    gameOver = false;
    }
      
    private void reset() {
    for (int i = 0; i < tiles.length; i++) {
    tiles[i] = (i + 1) % tiles.length;
    }
      
    // we set blank cell at the last
    blankPos = tiles.length - 1;
    }
      
    private void shuffle() {
    // don't include the blank tile in the shuffle, leave in the solved position
    int n = nbTiles;
      
    while (n > 1) {
    int r = RANDOM.nextInt(n--);
    int tmp = tiles[r];
    tiles[r] = tiles[n];
    tiles[n] = tmp;
    }
    }
      
    // Only half permutations o the puzzle are solvable
    // Whenever a tile is preceded by a tile with higher value it counts
    // as an inversion. In our case, with the blank tile in the solved position,
    // the number of inversions must be even for the puzzle to be solvable
    private boolean isSolvable() {
    int countInversions = 0;
      
    for (int i = 0; i < nbTiles; i++) {
    for (int j = 0; j < i; j++) {
    if (tiles[j] > tiles[i])
    countInversions++;
    }
    }
      
    return countInversions % 2 == 0;
    }
      
    private boolean isSolved() {
    if (tiles[tiles.length - 1] != 0) // if blank tile is not in the solved position ==> not solved
    return false;
      
    for (int i = nbTiles - 1; i >= 0; i--) {
    if (tiles[i] != i + 1)
    return false;
    }
      
    return true;
    }
      
    private void drawGrid(Graphics2D g) {
    for (int i = 0; i < tiles.length; i++) {
    // we convert 1D coords to 2D coords given the size of the 2D Array
    int r = i / size;
    int c = i % size;
    // we convert in coords on the UI
    int x = margin + c * tileSize;
    int y = margin + r * tileSize;
      
    // check special case for blank tile
    if(tiles[i] == 0) {
    if (gameOver) {
    g.setColor(FOREGROUND_COLOR);
    drawCenteredString(g, "\u2713", x, y);
    }
      
    continue;
    }
      
    // for other tiles
    g.setColor(getForeground());
    g.fillRoundRect(x, y, tileSize, tileSize, 25, 25);
    g.setColor(Color.BLACK);
    g.drawRoundRect(x, y, tileSize, tileSize, 25, 25);
    g.setColor(Color.WHITE);
      
    drawCenteredString(g, String.valueOf(tiles[i]), x , y);
    }
    }
      
    private void drawStartMessage(Graphics2D g) {
    if (gameOver) {
    g.setFont(getFont().deriveFont(Font.BOLD, 18));
    g.setColor(FOREGROUND_COLOR);
    String s = "Click to start new game";
    g.drawString(s, (getWidth() - g.getFontMetrics().stringWidth(s)) / 2,
    getHeight() - margin);
    }
    }
      
    private void drawCenteredString(Graphics2D g, String s, int x, int y) {
    // center string s for the given tile (x,y)
    FontMetrics fm = g.getFontMetrics();
    int asc = fm.getAscent();
    int desc = fm.getDescent();
    g.drawString(s, x + (tileSize - fm.stringWidth(s)) / 2,
    y + (asc + (tileSize - (asc + desc)) / 2));
    }
      
    @Override
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2D = (Graphics2D) g;
    g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    drawGrid(g2D);
    drawStartMessage(g2D);
    }
      
    public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setTitle("Game of Fifteen");
    frame.setResizable(false);
    frame.add(new GameOfFifteen(4, 550, 30), BorderLayout.CENTER);
    frame.pack();
    // center on the screen
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    });
    }

      
    }

Solutions

Expert Solution

/*

//Note:--> The > JDK 1.8 does not support the command prompt. So you need to use any IDE like Eclipse, IntelliJ idea etc.

or install the old version of jdk like JDK1.8

and follow the steps  

This code is running correctly. So there is no problem with code.

If you haven't install JDK

First of all, install it (Search JDK on search engine)

after the installation gets complete.

if you are using command prompt to run this program

follow the following steps

(1) go to Control Panel

(2) Select the System icon

(3)

Select the Advance system settings

(4)

Now select the environment variables

(5)

Click New in the user variables section.

(6)

the variable value is the path of the directory where your JDK is installed.

By default location is given above in pic.

(7) and press OK.

To check it, Go to the command prompt (type cmd in the search box ) or you can use the run command (Win key +R)

Type javac in cmd .

Now go to the file location where you saved your GameOfFifteen.java file. using CD command

as I have saved it in E:\

//Now use the following commands to compile and run your program

*/

//Output

//If you need any help regarding this solution ............ please leave a comment ........ thanks


Related Solutions

I get an error when im trying to run this java program, I would appreciate if...
I get an error when im trying to run this java program, I would appreciate if someone helped me asap, I will make sure to leave a good review. thank you in advance! java class Node public class Node { private char item; private Node next; Object getNext; public Node(){    item = ' '; next = null; } public Node(char newItem) { setItem(newItem); next = null; } public Node(char newItem, Node newNext){ setItem(newItem); setNext(newNext); } public void setItem(char newItem){...
What I have bolded is what is wrong with this function and cant figure out what...
What I have bolded is what is wrong with this function and cant figure out what needs to bee done to get the second position of this comma?Need help building this function to do what the specifications say to do import introcs def second_in_list(s): """ Returns: the second item in comma-separated list    The final result should not have any whitespace around the edges.    Example: second_in_list('apple, banana, orange') returns 'banana' Example: second_in_list(' do , re , me , fa...
I cant not seem to get this right. I have tried and tried can I please...
I cant not seem to get this right. I have tried and tried can I please get help. Thank you! Writing a Modular Program in Java Summary In this lab, you add the input and output statements to a partially completed Java program. When completed, the user should be able to enter a year, a month, and a day to determine if the date is valid. Valid years are those that are greater than 0, valid months include the values...
I'm not sure i understand sending parameters and reference and i think im doing it wrong....
I'm not sure i understand sending parameters and reference and i think im doing it wrong. In this code i'm trying to enter notas (grades) by user input into the exArrays, getting the promedio (average) and printing it on screen. I've searched a lot of videos but they don't help. The lenguage is C++ void entrarNotas(int ex1Array[], int ex2Array[], int ex3Array[], int sizeSalon, char notaPara, float promedioPara) {    cout << "Entrar cuantos estudiantes hay en el salon" << "...
"You will need to compile each Java source file (provided below) separately, in its own file...
"You will need to compile each Java source file (provided below) separately, in its own file since they are public classes, to create a .class file for each, ideally keeping them all in the same directory." My class is asking me to do this and i am not understanding how to do it. I use JGRASP for all of my coding and i can't find a tutorial on how to do it. I just need a step by step tutorial...
Get the file “HW4Short.java”. Compile it and look at its bytecode. [TO DO:] Write a step-by-step...
Get the file “HW4Short.java”. Compile it and look at its bytecode. [TO DO:] Write a step-by-step description of the bytecode, imitating the style of my explanation in problem 1. Explantionin promblem1: 0 iconst_0 push constant 0 onto the stack 1 istore_1 pop stack and store in location 1 (sum = 0) 2 iconst_0 push constant 0 onto the stack 3 istore_2 pop stack and store in location 2 (i = 0) 4 iload_2 push contents of location 2 onto stack...
Im trying to get a GUI interface in java where there is four text fields for...
Im trying to get a GUI interface in java where there is four text fields for the first name, last name, department, and phone number of employee in a program. Then also have a radio button below for Gender (Male/Female/Other) and a list for the Title (Mr./Ms./Mrs./Dr./Col./Prof.). At the very bottom of the frame there has to be buttons for printing, submitting and exiting but for whatever reason when I tried it nothing appears in the frame regardless of what...
For my economy class I need to annswer these questions but I just dont get/cant find...
For my economy class I need to annswer these questions but I just dont get/cant find the right inf. The Presentville – Futureville case: 1. Explain what motivated each group to make the decisions they made.
(Please show the formulas you used in excel i cant get the right numbers :// if...
(Please show the formulas you used in excel i cant get the right numbers :// if you could post one with numbers then show the formulas that would be awesome!!) NOK Plastics is considering the acquisition of a new plastic injection-molding machine to make a line of plastic fittings. The cost of the machine and dies is $125,000. Shipping and installation is another $8,000. NOK estimates it will need a $10,000 investment in net working capital initially, which will be...
Hey yall, Im working on a quiz I completed. I really need to get a 100...
Hey yall, Im working on a quiz I completed. I really need to get a 100 I worked all the problems out and i was wondering if one of yall would mind checking it for me. If i missed one if yall could tell me how to get the correct answer? 1.The intermolecular forces present in CH3NH2 include which of the following? I. dipole-dipole II. ion-dipole III. dispersion IV. hydrogen bonding ANS: I, III, and IV 2. A liquid boils...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT