dimanche 29 mars 2015

Java Side-Scrolling Game - Image Duplicating

Here is the the whole program


I am having trouble with the image just multiplying on the screen. It moves, but each movement just creates a new image.


Here are the instructions:


Complete the handleKeyPress method. Write the following line of code in the handleKeyPress method to check for a key press:


int key = grid.checkLastKeyPressed();


If the user pressed the up arrow (key == 38), move the user's image up one row (unless the user is already in the top row). Likewise, if the user pressed the down arrow (key == 40), move the user's image down one row (unless the user is already in the bottom row). Either way, make sure to update userRow.


Movement of the image can be accomplished by changing the value of userRow.


Study how the initial image is displayed in the game constructor, then Set the current image location to null


Update userRow to the new location and, Set the image in the new value of userRow.


You should be able to move the user image up and down, and you should be prevented from moving the image off the screen.


Game file



package Game;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JOptionPane;


public class Game
{
private Grid grid; //holds the grid used to store and display images
private int userRow; //keep track of which row the user-controlled image appears in
private int msElapsed; //keep track of the total amount of milliseconds that have elapsed since the start of the game
private int timesGet;//keep track of total number of times the user has gotten the things they're supposed to get in the game
private int timesAvoid;//keeps track o the total number of times the user has been hit by the things they're supposed to avoid
// Image rwby8bit;


public Game()
{
grid = new Grid(10, 20);
userRow = 0;
msElapsed = 0;
timesGet = 0;
timesAvoid = 0;
updateTitle();
grid.setImage(new Location(userRow, 0), "rwby8bit.gif");


}
// public void graphicComponent(Graphics g)
// {
//
// g.drawImage(rwby8bit, userRow, userRow, grid);
// }

public void play()
{
while (!isGameOver())
{
grid.pause(100);
handleKeyPress();
if (msElapsed % 300 == 0)
{
scrollLeft();
populateRightEdge();
}
updateTitle();
msElapsed += 100;
}
}

public void handleKeyPress()
{

int key = grid.checkLastKeyPressed();
//grid.getImage(null, "rwby8bit.gif");
// grid.setImage(null, "rwby8bit.gif");

if (key == 38)
{
if (userRow != 0)
{
userRow-=1;
grid.getImage(null);
grid.setImage(new Location(userRow, 0), "rwby8bit.gif");
}
else if (userRow == 0)
{
userRow-=0;
Component frame = null;
JOptionPane.showMessageDialog(frame,"Movement cannot exceed the field!");

}
}
else if (key == 40)
{
if (userRow == 10)
{
userRow+=0;
Component frame = null;
JOptionPane.showMessageDialog(frame,"Movement cannot exceed the field!");
}
else
{
userRow+=1;
//grid.setImage(null, "rwby8bit.gif");
grid.getImage(null);
grid.setImage(new Location(userRow, 0), "rwby8bit.gif");
}
}






}



public void populateRightEdge()
{
}

public void scrollLeft()
{
}

public void handleCollision(Location loc)
{
}

public int getScore()
{
return 0;
}

public void updateTitle()
{
grid.setTitle("Game: " + getScore());
}

public boolean isGameOver()
{
return false;
}

public static void test()
{
Game game = new Game();
game.play();
}

public static void main(String[] args)
{
test();
}
}


Grid file



package Game;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
import javax.swing.*;

public class Grid extends JComponent implements KeyListener, MouseListener
{
private Cell[][] cells;
private JFrame frame;
private int lastKeyPressed;
private Location lastLocationClicked;
private Color lineColor;

public Grid(int numRows, int numCols)
{
init(numRows, numCols);
}

public Grid(String imageFileName)
{
BufferedImage image = loadImage(imageFileName);
init(image.getHeight(), image.getWidth());
showImage(image);
setTitle(imageFileName);
}

private BufferedImage loadImage(String imageFileName)
{
URL url = getClass().getResource(imageFileName);
if (url == null)
throw new RuntimeException("cannot find file: " + imageFileName);
try
{
return ImageIO.read(url);
}
catch(IOException e)
{
throw new RuntimeException("unable to read from file: " + imageFileName);
}
}

public int getNumRows()
{
return cells.length;
}

public int getNumCols()
{
return cells[0].length;
}

private void init(int numRows, int numCols)
{
lastKeyPressed = -1;
lastLocationClicked = null;
lineColor = null;

cells = new Cell[numRows][numCols];
for (int row = 0; row < numRows; row++)
{
for (int col = 0; col < numCols; col++)
cells[row][col] = new Cell();
}

frame = new JFrame("Grid");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addKeyListener(this);

int cellSize = Math.max(Math.min(500 / getNumRows(), 500 / getNumCols()), 1);
setPreferredSize(new Dimension(cellSize * numCols, cellSize * numRows));
addMouseListener(this);
frame.getContentPane().add(this);

frame.pack();
frame.setVisible(true);
}

private void showImage(BufferedImage image)
{
for (int row = 0; row < getNumRows(); row++)
{
for (int col = 0; col < getNumCols(); col++)
{
int x = col * image.getWidth() / getNumCols();
int y = row * image.getHeight() / getNumRows();
int c = image.getRGB(x, y);
int red = (c & 0x00ff0000) >> 16;
int green = (c & 0x0000ff00) >> 8;
int blue = c & 0x000000ff;
cells[row][col].setColor(new Color(red, green, blue));
}
}
repaint();
}

private int getCellSize()
{
int cellWidth = getWidth() / getNumCols();
int cellHeight = getHeight() / getNumRows();
return Math.min(cellWidth, cellHeight);
}

public void keyPressed(KeyEvent e)
{
lastKeyPressed = e.getKeyCode();
}

public void keyReleased(KeyEvent e)
{
//ignored
}

public void keyTyped(KeyEvent e)
{
//ignored
}

public void mousePressed(MouseEvent e)
{
int cellSize = getCellSize();
int row = e.getY() / cellSize;
if (row < 0 || row >= getNumRows())
return;
int col = e.getX() / cellSize;
if (col < 0 || col >= getNumCols())
return;
lastLocationClicked = new Location(row, col);
}

public void mouseReleased(MouseEvent e)
{
//ignore
}

public void mouseClicked(MouseEvent e)
{
//ignore
}

public void mouseEntered(MouseEvent e)
{
//ignore
}

public void mouseExited(MouseEvent e)
{
//ignore
}

private static java.awt.Color toJavaColor(Color color)
{
return new java.awt.Color(color.getRed(), color.getGreen(), color.getBlue());
}

public void paintComponent(Graphics g)
{
for (int row = 0; row < getNumRows(); row++)
{
for (int col = 0; col < getNumCols(); col++)
{
Location loc = new Location(row, col);
Cell cell = cells[loc.getRow()][loc.getCol()];

Color color = cell.getColor();
g.setColor(toJavaColor(color));
int cellSize = getCellSize();
int x = col * cellSize;
int y = row * cellSize;
g.fillRect(x, y, cellSize, cellSize);

String imageFileName = cell.getImageFileName();
if (imageFileName != null)
{
URL url = getClass().getResource(imageFileName);
if (url == null)
System.out.println("File not found: " + imageFileName);
else
{

Image image = new ImageIcon(url).getImage();
int width = image.getWidth(null);
int height = image.getHeight(null);
int max;
if (width > height)
{
int drawHeight = cellSize * height / width;
g.drawImage(image, x, y + (cellSize - drawHeight) / 2, cellSize, drawHeight, null);
}
else
{
int drawWidth = cellSize * width / height;
g.drawImage(image, x + (cellSize - drawWidth) / 2, y, drawWidth, cellSize, null);
}
}
}

if (lineColor != null)
{
g.setColor(toJavaColor(lineColor));
g.drawRect(x, y, cellSize, cellSize);
}
}
}
}

public void setTitle(String title)
{
frame.setTitle(title);
}

public boolean isValid(Location loc)
{
int row = loc.getRow();
int col = loc.getCol();
return 0 <= row && row < getNumRows() && 0 <= col && col < getNumCols();
}

public void setColor(Location loc, Color color)
{
if (!isValid(loc))
throw new RuntimeException("cannot set color of invalid location " + loc + " to color " + color);
cells[loc.getRow()][loc.getCol()].setColor(color);
repaint();
}

public Color getColor(Location loc)
{
if (!isValid(loc))
throw new RuntimeException("cannot get color from invalid location " + loc);
return cells[loc.getRow()][loc.getCol()].getColor();
}

public void setImage(Location loc, String imageFileName)
{
if (!isValid(loc))
throw new RuntimeException("cannot set image for invalid location " + loc + " to \"" + imageFileName + "\"");
cells[loc.getRow()][loc.getCol()].setImageFileName(imageFileName);
repaint();
}

public String getImage(Location loc)
{
if (!isValid(loc))
throw new RuntimeException("cannot get image for invalid location " + loc);
return cells[loc.getRow()][loc.getCol()].getImageFileName();
}

public static void pause(int milliseconds)
{
try
{
Thread.sleep(milliseconds);
}
catch(Exception e)
{
//ignore
}
}

//returns -1 if no key pressed since last call.
//otherwise returns the code for the last key pressed.
public int checkLastKeyPressed()
{
int key = lastKeyPressed;
lastKeyPressed = -1;
return key;
}

//returns null if no location clicked since last call.
public Location checkLastLocationClicked()
{
Location loc = lastLocationClicked;
lastLocationClicked = null;
return loc;
}

public void load(String imageFileName)
{
showImage(loadImage(imageFileName));
setTitle(imageFileName);
}

public void save(String imageFileName)
{
try
{
BufferedImage bi = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
paintComponent(bi.getGraphics());
int index = imageFileName.lastIndexOf('.');
if (index == -1)
throw new RuntimeException("invalid image file name: " + imageFileName);
ImageIO.write(bi, imageFileName.substring(index + 1), new File(imageFileName));
}
catch(IOException e)
{
throw new RuntimeException("unable to save image to file: " + imageFileName);
}
}

public void setLineColor(Color color)
{
lineColor = color;
repaint();
}

public void showMessageDialog(String message)
{
JOptionPane.showMessageDialog(this, message);
}

public String showInputDialog(String message)
{
return JOptionPane.showInputDialog(this, message);
}

// void getImage(Location location) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
// }
}


Location File



package Game;
public class Location
{
private int row;
private int col;

public Location(int r, int c)
{
row = r;
col = c;
}

public int getRow()
{
return row;
}

public int getCol()
{
return col;
}

public boolean equals(Location otherLoc)
{
return row == otherLoc.getRow() && col == otherLoc.getCol();
}

public String toString()
{
return "(" + row + ", " + col + ")";
}
}


Cell File



package Game;
public class Cell
{
private Color color;
private String imageFileName;

public Cell()
{
color = new Color(0, 0, 0);
imageFileName = null;
}

public void setColor(Color c)
{
color = c;
}

public Color getColor()
{
return color;
}

public String getImageFileName()
{
return imageFileName;
}

public void setImageFileName(String fileName)
{
imageFileName = fileName;
}
}

Aucun commentaire:

Enregistrer un commentaire