I am trying to get this program to show two pictures and check if they are the same picture, i am having trouble getting bildeSjekk() to do this, it shows all pictures and if you double click a picture it removes it, first i need to store the previous instance of the int i, then when teller should become two when two pictures have been revealed, and then i will use current int i and int temp in the int array index and check if the value is the same. It's a Picture memory game.
package prosjekt_1139;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Hukommelse extends JPanel implements MouseListener, ActionListener{
//private JLabel[] kort = new JLabel[16];
private JButton nyOmgang = new JButton("Del ut kortene");
private JButton tilbake = new JButton("Tilbake");
private HovedVinduet vindu;
private int[] index = new int[16];
private int teller =0, temp = 0;
private Image img;
private Image[] imgarray;
private Rectangle[] bokser;
private Point point1;
private URL path1, path2[]= new URL[8];
private boolean sjekk[] = new boolean[16];
public Hukommelse(HovedVinduet vindu) throws IOException{
this.vindu = vindu;
bokser = new Rectangle[16];
imgarray = new Image[8];
point1 = new Point();
img = null;
setBackground(Color.GREEN);
setPreferredSize(new Dimension(720,690));
setLocation(0,0);
nyOmgang.addActionListener(this);
tilbake.addActionListener(this);
add(nyOmgang);
add(tilbake);
this.addMouseListener(this);
boks();
}
// this is my randomisere metode
public void kortIndex(){
int temp;
for (int i = 0;i<index.length;i++){
index[i] = i/2;
//System.out.println(index[i]);
}
for (int i=0;i<1000;i++){
int index1 = (int)(Math.random()*16);
int index2 = (int)(Math.random()*16);
temp = index[index1];
index[index1] = index[index2];
index[index2] = temp;
}
// for (int i = 0; i<index.length;i++)
// System.out.print(index[i]+"\t");
// System.out.println();
}
public void paintComponent(Graphics g){
super.paintComponents(g);
g.setColor(Color.green);
int j = 0;
int k = 0;
for (int i = 0; i<16;i++){
g.drawImage(img, 20+(k*175), 50+(j*160), 150, 150, this);
k++;
if(i == 3 || i == 7 || i == 11 || i == 15){
j++;
k = 0;
}
}
for (int i=0; i<bokser.length; i++) {
if(sjekk[i]){
g.drawImage(imgarray[index[i]], bokser[i].x, bokser[i].y, bokser[i].width, bokser[i].height, this);
}
}
}
//Metode For checking if the image is clicked on
public void bildeSjekk(){
for (int i = 0;i<bokser.length;i++){
if(bokser[i].contains(point1)){
sjekk[i] = true;
teller++;
temp = i;
}
if(teller >= 2 ){
sjekk[i] = false;
sjekk[temp] = false;
teller = 0;
}
}
}
public void boks(){
int j = 0;
int k = 0;
for(int i = 0; i <bokser.length; i++){
bokser[i] = new Rectangle(20+(j*175), 50+(k*160), 150, 150);
j++;
if(i == 3 || i == 7 || i == 11 || i == 15){
j =0;
k++;
}
}
}
public void bilder() throws IOException{
img = ImageIO.read(new File("Image/grass.jpg"));
//repaint();
imgarray[0] = ImageIO.read(new File("Image/bekk.jpg"));
imgarray[1] = ImageIO.read(new File("Image/solnedgang.jpg"));
imgarray[2] = ImageIO.read(new File("Image/tåge.jpg"));
imgarray[3] = ImageIO.read(new File("Image/vile.jpg"));
imgarray[4] = ImageIO.read(new File("Image/fuglekasse.jpg"));
imgarray[5] = ImageIO.read(new File("Image/gullfugl.jpg"));
imgarray[6] = ImageIO.read(new File("Image/byen.jpg"));
imgarray[7] = ImageIO.read(new File("Image/bekk.jpg"));
}
#Override
public void mouseClicked(MouseEvent agr0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println(e.getX()+"\t"+e.getY());
point1 = e.getPoint();
bildeSjekk();
repaint();
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Del ut kortene")){
try {
bilder();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
point1 = new Point(0,0);
for (int i = 0;i<bokser.length;i++){
sjekk[i] = false;
}
teller = 0;
kortIndex();
repaint();
}
if(e.getSource() == tilbake){
vindu.setMenyPanelAktivt();
vindu.setSize(800, 600);
vindu.setLocation(0,0);
}
}
}
You might like this related memory game that uses JToggleBUtton and Unicode glyphs instead of pictures.
Addendum: As an aside, you may get more helpful answers if you prepare an sscce that doesn't depend on a large number of inaccessible images. As an example, RotatableImage is a simple, static class that can be adapted as required.
Related
I am programming a Mario game for my project for my computer science class, and so far the Mario character can run left and right, crouch, and I have built the background.
Two questions that I have are
when making the background move, should I make a separate class that has all the background images? This way I can switch out the various backgrounds I intend to create.
My current program has the issue of when I try and jump (press the up arrow key), Mario does not jump normally, he lags a bit and then rises a lot. I am trying to make it so Mario can rise lets say, one pixel every 100th of a second, but that is not working, instead, it waits around 1 or 2 seconds then rises 100 pixels and stops.
Frame Class:
package FirstPlatformer;
import javax.swing.JFrame;
public class PlatformerFrame
{
public static void main(String[] args)
{
//change to match your values for width/height
//these can be changed
int w = 1525;
int h = 830;
//sets up a JFrame object with title "Template"
JFrame frame = new JFrame("Template");
//make sure the jframe closes when you hit the 'x'
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//adds the drawing panel to the frame
frame.getContentPane().add(new Platformer(w,h));
//resizes the frame to fit the panel
frame.pack();
//makes it visible
frame.setVisible(true);
}
}
Platformer Class:
package FirstPlatformer;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
//change to be your packagename
//all imports are necessary
//must 'extend' JPanel
public class Platformer extends JPanel
{
Random test = new Random();
Color aboveground = new Color (99, 158, 169);
private ImageIcon marioStart, ground, mysteryBlock, smallMarioRight, smallMarioLeft, smallMarioCrouchedLeft, smallMarioCrouchedRight;
//variables for the overall width and height
private int w, h;
boolean start = false;
//crouching mechanism
boolean crouchPressed = false;
boolean crouchReleased = false;
boolean youAreCrouching = false;
//facing direction mechanisms
boolean facingRight = true;
boolean facingLeft = false;
//jumping mechanisms
boolean jumpStart = false;
int jumpCountEqual = 0;
private int number = 0;
private int count = 0;
int baseHeight = 770;
int smallMarioGround = 725;
//variable that establishes marios x coord
int marioX = 0;
//sets up the initial panel for drawing with proper size
public Platformer(int w, int h)
{
setFocusable(true);
this.w = w;
this.h = h;
this.setPreferredSize(new Dimension(w,h));
//creating the images
marioStart = new ImageIcon("src/FirstPlatformer/marioStart.JPG");
//building blocks
ground = new ImageIcon("src/FirstPlatformer/ground.JPG");
mysteryBlock = new ImageIcon("src/FirstPlatformer/mysteryBlock.png");
//small mario actions
smallMarioLeft = new ImageIcon("src/FirstPlatformer/smallMarioRight.png");
smallMarioRight = new ImageIcon("src/FirstPlatformer/smallMarioLeft.png");
smallMarioCrouchedLeft = new ImageIcon("src/FirstPlatformer/marioCrouched.png");
smallMarioCrouchedRight= new ImageIcon("src/FirstPlatformer/marioCrouchedRight.png");
this.addMouseListener(new MouseTracker());
this.addKeyListener(new Keyboard());
}
//all graphical components go here
//this.setBackground(Color c) for example will change background color
public void paintComponent(Graphics g)
{
//this line sets up the graphics - always needed
super.paintComponent(g);
g.setColor(Color.RED);
//all drawings below here:
//creating the starting screen
if(start != true) {
setBackground(Color.BLACK);
marioStart.paintIcon(this,g,240,100);
g.setFont(new Font("Arial", Font.BOLD, 50));
g.drawString("Created by Zane Lanski", 515, 625);
g.drawString("Press Space to Start", 525, 725);
}
else {
//setting the overall background for when mario is aboveground
setBackground(aboveground);
//variable for building the bottom of the level
int groundCount = 0;
//for loop creates the base of the level
for(int groundBase = 0; groundBase <30; groundBase++)
{
ground.paintIcon(this, g, groundCount, 770);
groundCount = groundCount + 52;
}
mysteryBlock.paintIcon(this, g, 500, 500);
if(crouchPressed != true && facingRight == true) {
smallMarioRight.paintIcon(this,g,marioX,smallMarioGround);
}
if(crouchPressed != true && facingLeft == true) {
smallMarioLeft.paintIcon(this,g,marioX,smallMarioGround);
}
if(crouchPressed != false) {
smallMarioCrouchedRight.paintIcon(this,g, marioX, smallMarioGround+18);
}
if(jumpStart == true) {
for(int jumpCount = jumpCountEqual;jumpCount < 100; jumpCount++) {
smallMarioGround = smallMarioGround- 1;
// smallMarioRight.paintIcon(this, g, marioX, smallMarioGround);
try
{
Thread.sleep(10);
}
catch(InterruptedException e)
{
System.out.println(e);
}
repaint();
System.out.println(jumpCount);
jumpCountEqual++;
}
}
}
}
private class MouseTracker implements MouseListener, MouseMotionListener
{
#Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
number++;
count++;
number %= 5;
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
private class Keyboard implements KeyListener
{
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
int key = e.getKeyCode();
repaint();
}
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
int key = e.getKeyCode();
if(key == KeyEvent.VK_RIGHT) {
facingLeft = false;
facingRight = true;
marioX = marioX + 5;
facingRight = true;
facingLeft = false;
}
if(key == KeyEvent.VK_LEFT) {
crouchPressed = false;
marioX = marioX - 5;
facingLeft = true;
facingRight = false;
}
if(key == KeyEvent.VK_DOWN) {
crouchPressed = true;
youAreCrouching = true;
}
if(key == KeyEvent.VK_UP) {
jumpStart = true;
}
if(key == KeyEvent.VK_SPACE) {
start = true;
}
repaint();
}
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
int key = e.getKeyCode();
if(key == KeyEvent.VK_DOWN) {
crouchPressed = false;
}
repaint();
}
}
}
I'm trying to make a space invaders game and I've got an issue where I'm trying to move the spaceinvaders in a loop [though the code shows an iteration of 5 movements in a for] but they aren't updated in the window.
as you can see from the picture, the spaceinvaders have been moved to the right only once, after the iterations of run() have ended
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyledDocument;
import java.util.Random;
public class SpaceInvadersPanel extends JPanel {
boolean running = false;
int indice = 0; //placeholder
int fine = 10; //placeholder
int speed = 10; //placeholder
String correctAnswer = "prova"; //Placeholder
Aliens[] alien = new Aliens[fine];
int alienX = 35;
int alienY = 35;
SpaceInvadersPanel(int SCREEN_WIDTH, int SCREEN_HEIGHT) throws IOException, InterruptedException {
this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
this.setBackground(Color.white);
this.setFocusable(true);
startGame();
}
public void startGame() throws IOException, InterruptedException{
newSpaceInvader();
}
public void newSpaceInvader() {
for(int i = 0; i<alien.length; i++) {
alien[i] = new Aliens(alienX, alienY, speed);
alienX += 50;
if (i == 4) {alienY += 50; alienX = 35;}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
try {
try {
draw(g);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {e.printStackTrace();
}
}
public void draw(Graphics g) throws IOException, InterruptedException {
BufferedImage image = ImageIO.read(new File("C:\\Users\\39340\\Desktop\\", "spaceinvadersart40bianco.png"));
g.setColor(Color.red);
for(int i = 0; i<alien.length; i++) {
g.drawImage(image, alien[i].x, alien[i].y, null);
}
run();
}
public void run() throws IOException, InterruptedException {
for (int i=0; i<5; i++) {System.out.println("sono al run");
move();Thread.sleep(500);}
}
public void move() throws IOException {
for(int i = 0; i<alien.length; i++) {
System.out.println("sto aumentando roba nel move");
System.out.println("alien x = " +alien[i].x);
alien[i].x += 50;
System.out.println("ora alien x = " +alien[i].x);
//alien[i].y += speed;
}
}
public void checkCollision() {}
public void gameOver(Graphics g) {}
}
I am attempting to make minesweeper. I understand that there is probably a better way to do this but this is how I am trying it.
My problem comes in the gridSquare class. This class is a JLabel and I need the frame that the gridSquare is contained within. I attempt to get the frame with the line minesweeperFrame frame = (minesweeperFrame) SwingUtilities.getWindowAncestor(this);. The problem I run into is that frame is null and never set to the gridSquares Frame. Is there any way to fix this.
Main.java
public class Main {
public static void main(String[] args) {
minesweeperFrame frame = new minesweeperFrame();
}
}
gridSquare.java
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Objects;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.Border;
public class gridSquare extends JLabel implements MouseListener{
Boolean isBomb = false;
int gridNum;
int n1,n2,n3,n4,n6,n7,n8,n9;
int bombNumber;
minesweeperFrame frame = (minesweeperFrame) SwingUtilities.getWindowAncestor(this);
gridSquare(int gridNum){
this.gridNum = gridNum;
n1 = gridNum - 10 - 1; //Top left
n2 = gridNum - 10 ; //Top center
n3 = gridNum - 10 + 1; //Top Left
n4 = gridNum - 1;//center left
n6 = gridNum + 1;//center right
n7 = gridNum + 10 -1;//Bottom Left
n8 = gridNum + 10; //Bottom Center
n9 = gridNum + 10 + 1; //Bottom Right
int neighbors[] = {n1,n2,n3,n4,n6,n7,n8,n9};
try {
//get the bomb number
for(int i:neighbors) {
if(frame.getSquares().get(i).getIsBomb()) { // if any neighbor is a bomb increase bombNumber ---------- frame.getSquares().get(i).getIsBomb()
bombNumber++;
}
System.out.println("WORKS");
}
}
catch(Exception e){
System.out.println(e);
}
setText("");
setHorizontalAlignment(JLabel.CENTER);
setVerticalAlignment(JLabel.CENTER);
setFont(new Font("Copperplate Gothic Bold",Font.PLAIN,20));
setForeground(new Color(0x000000)); //set font color CHANGE FOR EACHER NUMBER
setSize(50,50);
Border border = BorderFactory.createLineBorder(Color.darkGray,5);
setBorder(border);
setBackground(new Color(0xd3d3d3)); //set background color ----- change to #424242 after clicked
setOpaque(true);//display background color
addMouseListener(this);
}
public Boolean getIsBomb() {
return isBomb;
}
public void setIsBomb(Boolean isBomb) {
this.isBomb = isBomb;
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
if(e.getButton() == MouseEvent.BUTTON1) {
setText("Left Click!");
if(isBomb) {
setText("bomb");
}
}
if(e.getButton() == MouseEvent.BUTTON3) {
setText("Flag");
}
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
mineSeeperFrame.java
import java.awt.GridLayout;
import java.awt.color.*;
import java.util.ArrayList;
import javax.swing.*;
public class minesweeperFrame extends JFrame{
private final int numColumns = 10;
private int numRows = 8;
int numBombs = 0;
ArrayList<gridSquare> squares = new ArrayList<gridSquare>();
minesweeperFrame(){
setTitle("Minesweeper");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1000,850);
setResizable(false);
setLayout(new GridLayout(numRows,numColumns,1,1));
setVisible(true);
//Fill Arraylist and add to frame
for(int i = 0; i < 80;i++) {
squares.add(new gridSquare(i));
add(squares.get(i));
}
//AddBombs
while(numBombs < 10) {
squares.get((int) (Math.random()*80)).setIsBomb(true);
numBombs++;
}
}
public ArrayList<gridSquare> getSquares() {
return squares;
}
public int getGridRows() {
return numRows;
}
public int getGridColumns() {
return numColumns;
}
}
You cannot do this during initialization:
minesweeperFrame frame = (minesweeperFrame) SwingUtilities.getWindowAncestor(this);
the component is being created and not added to the frame yet, so you get null.
Moreover you add the gridsquare to the frame directly, this is wrong, you must add it to the contentPane, please read:
https://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html
https://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html
noob here trying to make a simple snake game. followed along with tutorial on youtube and my code mayches the working code as best i can tell...snake not responding to commands, seems KeyListener not working. printed out requestFocusInWindow in jpanel constructor to make sure it was in focus and got back false, even though i entered setFocusable(true) asfirst arg in panel constructor.
please help me figure out why snake not responding to movement commands
package otherSnake;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JPanel;
public class Panel extends JPanel implements Runnable {
public static final int width = 800, height = 800;
private boolean running = false;
private Thread thread;
private Bodypart b;
private ArrayList<Bodypart> snake;
private Apple apple;
private ArrayList<Apple> apples;
private Random r;
private int size = 5;
private int x = 10, y = 10;
private boolean right = true, left = false, up = false, down = false;
private int ticks = 0;
private Key key;
public Panel() {
setFocusable(true);
key = new Key();
addKeyListener(key);
setPreferredSize(new Dimension(width, height));
r = new Random();
snake = new ArrayList<Bodypart>();
apples = new ArrayList<Apple>();
start();
}
public void tick() {
if (snake.size() == 0) {
b = new Bodypart(x, y, 10);
snake.add(b);
}
if (apples.size() == 0) {
int xCord = r.nextInt(79);
int yCord = r.nextInt(79);
apple = new Apple(xCord, yCord, 10);
apples.add(apple);
}
ticks++;
if (ticks > 250000) {
if (right)
x++;
if (left)
x--;
if (up)
y--;
if (down)
y++;
ticks = 0;
b = new Bodypart(x, y, 10);
snake.add(b);
if (snake.size() > size) {
snake.remove(0);
}
}
}
public void paint(Graphics g) {
g.clearRect(0, 0, width, height);
g.setColor(Color.BLACK);
for (int i = 0; i < width / 10; i++) {
g.drawLine(i * 10, 0, i * 10, height);
}
for (int i = 0; i < height / 10; i++) {
g.drawLine(0, i * 10, width, i * 10);
}
for (int i = 0; i < snake.size(); i++) {
snake.get(i).draw(g);
}
for (int i = 0; i < apples.size(); i++) {
apples.get(i).draw(g);
}
}
public void start() {
running = true;
thread = new Thread(this, "Game Loop");
thread.start();
}
public void stop() {
running = false;
try {
thread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
while (running) {
tick();
repaint();
}
}
private class Key implements KeyListener {
#Override
public void keyTyped(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_RIGHT ) {
up = false;
down = false;
right = true;
//left=false;
}
if (key == KeyEvent.VK_LEFT ) {
up = false;
down = false;
left = true;
//right=false;
}
if (key == KeyEvent.VK_UP ) {
up = true;
down = false;
left = false;
right = false;
}
if (key == KeyEvent.VK_DOWN ) {
up = false;
down = true;
left = false;
right = false;
}
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
}
I am kind of stuck on this issue.
Basically I have a car image that I need to have go back to the start point once it disappers off the screen on the x axis. I thought I had it fixed by my checkOFFscreen but it did not work so I am suck and asking for some guidance on how to solve this.
Mainpanel.java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
public class MainPanel extends JPanel {
Player myPlayer;
Player myOtherPlayer;
private int WIDTH = 1000;
private int HEIGHT = 1000;
private int WALLWIDTH = 100;
private int WALLHEIGHT = 100;
private ArrayList<Wall> walls = new ArrayList<Wall>();
Timer myTimer = new Timer(500, new timerListener());
JLabel myTimeLabel;
int time =1;
public MainPanel()
{
setPreferredSize(new Dimension(WIDTH,HEIGHT));
JLabel myLabel= new JLabel ("Game ends once 30 seconds is receahed:");
myLabel.setFont(new Font("Serif", Font.BOLD,32));
myLabel.setForeground(Color.WHITE);
myTimeLabel= new JLabel (Integer.toString(time));
myTimeLabel.setFont(new Font("Serif", Font.BOLD,32));
myTimer.start();
add(myLabel);
add(myTimeLabel);
myPlayer = new Player(0,100, "toad.png", KeyEvent.VK_UP, KeyEvent.VK_DOWN, KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT,this, 50, 38);
myOtherPlayer = new Player(200,200, "toad.png", KeyEvent.VK_W, KeyEvent.VK_S, KeyEvent.VK_A, KeyEvent.VK_D,this, 50, 38);
createWalls();
}
public ArrayList<Wall> getWalls() {
return walls;
}
public void createWalls()
{
int j = 0;
for(int i = 0; i < HEIGHT/WALLHEIGHT; i++)
{
for(int k = 0; k < WIDTH/WALLWIDTH; k++)
{
if(i == 0 || i == (HEIGHT/WALLHEIGHT-1))
{
walls.add(new Wall(k*WALLWIDTH,j,"road.png", 100, 100));
}
}
j+=WALLHEIGHT;
}
}
private class timerListener implements ActionListener
{
public void actionPerformed(ActionEvent e) {
time++;
myTimeLabel.setText(Integer.toString(time));
myTimeLabel.setForeground(Color.WHITE);
if(time >= 30)
{
myTimer.stop();
}
repaint();
}
}
public void paintComponent(Graphics page)
{
super.paintComponent(page);
page.drawImage(myPlayer.getImageIcon().getImage(), myPlayer.getX(), myPlayer.getY(), null);
page.drawImage(myOtherPlayer.getImageIcon().getImage(), myOtherPlayer.getX(), myOtherPlayer.getY(), null);
for(int i = 0; i < walls.size(); i++)
{
page.drawImage(walls.get(i).getImageIcon().getImage(), walls.get(i).getX(), walls.get(i).getY(), null);
}
page.setFont(new Font("Arial", Font.PLAIN,32));
page.drawString("Player 1 Score: " + myPlayer.getScore(), 100, 800);
page.drawString("Player 2 Score: " + myOtherPlayer.getScore(), 100, 850);
if(time > 30)
{
page.drawString("GAME OVER", WIDTH/2-100, HEIGHT/2);
JOptionPane.showMessageDialog(null, "Please enter your email");
}
}
}
Player.java
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.ImageIcon;
public class Player extends GameObject implements KeyListener{
private int Up;
private int Down;
private int Left;
private int Right;
private MainPanel myPanel;
private Movement myMovement = new Movement();
private int score = 0;
public Player(int x, int y, String imagePath, int Up, int Down, int Left, int Right, MainPanel myPanel, int HEIGHT, int WIDTH)
{
super(x,y,imagePath, HEIGHT, WIDTH);
this.Up = Up;
this.Down = Down;
this.Left = Left;
this.Right = Right;
this.myPanel = myPanel;
myPanel.addKeyListener(this);
myPanel.setFocusable(true);
checkOffScreen();
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void checkOffScreen(){
if (x >=1050){
x=0;
}
}
public int getScore()
{
return score;
}
#Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
int key = arg0.getKeyCode();
if(key == Left)
{
x-=myMovement.getDistanceLeft();
if(checkWalls())
{
x+=10;
}
}
else if(key == Right)
{
x+=myMovement.getDistanceRight();
if(checkWalls())
{
x-=10;
}
}
myPanel.repaint();
}
public boolean checkWalls()
{
ArrayList<Wall> walls = myPanel.getWalls();
for(int i = 0 ; i < walls.size(); i++)
{
if(areRectsColliding(x,x+HEIGHT,y,y+WIDTH,walls.get(i).getX(), walls.get(i).getX()+ walls.get(i).getHEIGHT(),
walls.get(i).getY(),walls.get(i).getY()+walls.get(i).getWIDTH()))
{
return true;
}
}
return false;
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
private boolean areRectsColliding(int r1TopLeftX, int r1BottomRightX,
int r1TopLeftY, int r1BottomRightY, int r2TopLeftX,
int r2BottomRightX, int r2TopLeftY, int r2BottomRightY) {
if (r1TopLeftX < r2BottomRightX && r1BottomRightX > r2TopLeftX
&& r1TopLeftY < r2BottomRightY && r1BottomRightY > r2TopLeftY) {
return true;
} else {
return false;
}
}
#Override
public ImageIcon getImageIcon() {
// TODO Auto-generated method stub
return new ImageIcon(imagePath);
}
}
checkOffScreen looks like it's in your initialization of the player, not the main loop of the game. You need to check the x when you repaint, just like when you're moving the image of the car, every time you call to move the image of the car, you need to check your x axis after it's been moved.
Pseudo code
Player.checkOffScreen();
myPanel.repaint();
This should move the car back to the beginning after it's reached the parameters given.