My avatar for Mario won't jump as I intend - java

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();
}
}
}

Related

How to get the JFrame with the JLabel? Error when attempted

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

snake game in java won't detect arrow keys (snake won't respond to input)

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
}
}
}

How to create a JavaFX Scene for multiple Key Listeners?

so I am trying to create a Tron mulitplayer game, which is a bit like snake.
Anyways multiple people should be able to play that game using one keyboard, but diffrent key combinations to steer their character on the screen. One player would currently use the WASD Keys and the other one should use the arrow keys.
My problem is that I have created a scene with Javafx Scene Builder using an FXML. Only after creating the game I have noticed that the scene builder is apparently only supporting one key listener, so at the moment only one player can control their game figure.
Is there any way to fix that? Please help so one player can use the WASD-Keys and the other one can use the arrow keys to navigate.
MY question is diffrent from the existing solutions as the snakes need to belong to diffrent players. It is not sufficient to just check if a key input was pressed or two were pressed simultaneously, but it needs to check if the correct player pressed the input, even if another player pressed their input at that time too.
Hope that clears up the confusuion a bit.
Key Listener
import java.util.ArrayList;
import javafx.scene.Scene;
public class Human extends Player implements Runnable{
int keyboardControlsLayout;
Scene scene;
public Human(int stepSize, String colour, int playerNum, Scene scene,
int keyboardControlsLayout) {
super(stepSize, colour, playerNum);
// keyboardControlsLayout(0) = WASD
// keyboardControlsLayout(1) = ARROWS
this.keyboardControlsLayout = keyboardControlsLayout;
this.scene = scene;
}
#Override
public void run() {
// TODO Auto-generated method stub
while(this.getSnake().getAlive()) {
if (keyboardControlsLayout == 1) {
// use WASD
System.out.println("wasd");
scene.setOnKeyPressed(event -> {
switch (event.getCode()) {
case W:
snake.setDirection(0);
break;
case S:
snake.setDirection(1);
break;
case A:
snake.setDirection(3);
break;
case D:
snake.setDirection(2);
break;
default:
break;
}
//System.out.println(event.getCode().toString());
});
} else if (keyboardControlsLayout == 0) {
System.out.println("arrows");
// use arrow keys
scene.setOnKeyPressed(event -> {
switch (event.getCode()) {
case UP:
snake.setDirection(0);
break;
case DOWN:
snake.setDirection(1);
break;
case LEFT:
snake.setDirection(3);
break;
case RIGHT:
snake.setDirection(2);
break;
default:
break;
}
});
}
}
}
}
Where I create the scene:
public void newGame() {
System.out.println("<----- NEW GAME ----->");
game = new Game(10, scene, numHumans);
displayController.setUpDisplay(game);
timer = new Timeline((new KeyFrame(
Duration.millis(80),
event -> {
try {
timerTick();
} catch (Exception e) {
// TODO Auto-generated catch
block
e.printStackTrace();
}
})));
timer.setCycleCount(Animation.INDEFINITE);
start();
}
private void start() {
// starts game and logic
}
private void loadDisplayFXMLLoader() {
FXMLLoader displayFXMLLoader = new
FXMLLoader(getClass().getResource("DisplayView.fxml"));
try {
scene = new Scene(displayFXMLLoader.load(), 500, 525);
} catch (IOException e) {
Main.outputError(e);
}
displayController = displayFXMLLoader.getController();
}
private void loadScene() {
this.setScene(scene);
this.show();
//error Handling and closing
}
Any help would be appreciated!
Thanks
I'm not familiar with FXML but I personally use the javafx myself and it works well. I tweaked an old program to suit your needs if you'd like to try and test it out
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class yeet {
private static JFrame frame;
private static JPanel panel;
private static int x = 300;
private static int y = 300;
private static int x1 = 500;
private static int y1 = 500;
private static boolean running = true;
private static boolean moving = false;
private static boolean moving1 = false;
private static boolean up;
private static boolean down;
private static boolean right;
private static boolean left;
private static boolean up1;
private static boolean down1;
private static boolean right1;
private static boolean left1;
private static Timer refresh;
private static Timer speed;
private static Graphics g;
public static void main(String[] args) {
UI();
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if(moving && up) y--;
if (moving && down) y++;
if (moving && right) x++;
if (moving && left) x--;
if (moving1 && up1) y1--;
if (moving1 && down1) y1++;
if (moving1 && right1) x1++;
if (moving1 && left1) x1--;
panel.repaint();
}
};
ActionListener al1 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
guy(g);
laser(g);
}
};
refresh = new Timer(0, al1);
refresh.start();
speed = new Timer (4, al);
speed.start();
while (running) {
guy(g);
laser(g);
}
}
public static void guy(Graphics g) {
g = panel.getGraphics();
g.setColor(Color.green);
g.drawRect(x, y, 25, 25);
g.fillRect(x, y, 25, 25);
}
public static void laser (Graphics g) {
g = panel.getGraphics();
g.setColor(Color.red);
g.drawRect(x1, y1, 30, 30);
g.fillRect(x1, y1, 30, 30);
}
public static void UI () {
frame = new JFrame("Multiple movement test");
panel = new JPanel();
panel.setBackground(Color.black);
panel.setLayout(null);
frame.setSize(600,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.setVisible(true);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
moving = true;
up = true;
down = false;
right = false;
left = false;
refresh.start();
speed.start();
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
moving = true;
down = true;
up = false;
right = false;
left = false;
refresh.start();
speed.start();
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
moving = true;
left = true;
up = false;
down = false;
right = false;
refresh.start();
speed.start();
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
moving = true;
right = true;
left = false;
up = false;
down = false;
refresh.start();
speed.start();
}
if (e.getKeyCode() == KeyEvent.VK_W) {
moving1 = true;
up1 = true;
down1 = false;
right1 = false;
left1 = false;
refresh.start();
speed.start();
}
if (e.getKeyCode() == KeyEvent.VK_A) {
moving1 = true;
left1 = true;
up1 = false;
down1 = false;
right1 = false;
refresh.start();
speed.start();
}
if (e.getKeyCode() == KeyEvent.VK_S) {
moving1 = true;
down1 = true;
up1 = false;
right1 = false;
left1 = false;
refresh.start();
speed.start();
}
if (e.getKeyCode() == KeyEvent.VK_D) {
moving1 = true;
right1 = true;
up1 = false;
down1 = false;
left1 = false;
refresh.start();
speed.start();
}
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
});
frame.add(panel);
}
}
Hope this helps!

Buffered Keyboard Input

I am trying to write a 2d graphical game. In this game I have keyboard inputs to move a square block on a black plane. I order to ensure smooth key motions I want to use Buffered key input. In order to do this I use a boolean array that saves the key strokes.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Timer;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame{
/**
* #param args
*/
class Entity
{
int x = 150,y = 150;
int Speed = 5;
}
Entity user = new Entity();
boolean[] keys = new boolean[KeyEvent.KEY_TYPED];
public Main()
{
setSize(800,600);
setLocationRelativeTo(null);
final JPanel display = new JPanel()
{
protected void paintComponent(Graphics g)
{
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.RED);
g.fillRect(user.x, user.y, 30, 30);
}
};
addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent arg0)
{
keys[arg0.getKeyCode()] = true;
if(keys[KeyEvent.VK_UP])
{
user.y -= user.Speed;
}
if(keys[KeyEvent.VK_DOWN])
{
user.y += user.Speed;
}
if(keys[KeyEvent.VK_LEFT])
{
user.x -= user.Speed;
}
if(keys[KeyEvent.VK_RIGHT])
{
user.x += user.Speed;
}
setFocusable(true);
repaint();
}
});
//add a action listener
//remember to set the focusable
add(display);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t = new Thread();
try {
t.sleep(100);
Main m = new Main();
m.setVisible(true);
m.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
In this input the block moves in the correct direction but just twice, then It moves in a different motion and it even Stops moving.
I have searched in all my Java books that I have and it does not help much. How can I get this error fixed?
Make the boolean[] keys a local variable so that it does not contain previously pressed keys, which will impact the x,y coordinates.
public void keyPressed(KeyEvent arg0)
{
boolean[] keys = new boolean[KeyEvent.KEY_TYPED];
keys[arg0.getKeyCode()] = true;
if(keys[KeyEvent.VK_UP])
{
user.y -= user.Speed;
}
else if(keys[KeyEvent.VK_DOWN])
{
user.y += user.Speed;
}
else if(keys[KeyEvent.VK_LEFT])
{
user.x -= user.Speed;
}
else if(keys[KeyEvent.VK_RIGHT])
{
user.x += user.Speed;
}
setFocusable(true);
repaint();
}
If you just want to clear the keys
public void keyPressed(KeyEvent arg0)
{
keys = new boolean[KeyEvent.KEY_TYPED];
keys[arg0.getKeyCode()] = true;
/* Rest of code */

trouble with logic in java

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.

Categories

Resources