Failing to try to change an image when keypressed - java

I'm trying to make it so when I press down the right key a new picture pops up making it look like my character is walking, not quite sure how to do that though... Here's my code:
import java.awt.*;
public class Dude {
int x, dx, y;
Image still;
public Dude() {
ImageIcon i = new ImageIcon("Ken3.png");
ImageIcon ii = new ImageIcon("KenTurn1.png");
still = i.getImage();
x = 50;
y = 785;
}
public void move() {
x = x + dx;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return still;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A)
dx = -2;
if (key == KeyEvent.VK_D)
dx = 2;
if (key == KeyEvent.VK_SPACE)
dx = 5;
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A)
dx = 0;
if (key == KeyEvent.VK_D)
dx = 0;
Any help would be awesome thanks!

something like this, i commented it. Good luck
public class Dude {
private int walkingIndex;
private Image walkingFrames;
private Image still;
private String state;
public Dude() {
// say were starting off standing
state = "standing";
// init our still frame
still = (new ImageIcon("Ken3.png")).getImage();
// set our walking frame to 0 to start
walkingIndex = 0;
walkingFrames = new Image[3]; // or however many images you have in your walking animation
// go through each frame and initialize the image to KenWalking{index}.png
for(int i=0;i<walkingFrames.length;i++) {
walkingFrames[i] = (new ImageIcon("KenWalking"+i+".png")).getImage();
}
}
public void move() {
x+=dx;
// add 1 to the walking index and make sure its not greater than our number of walking frames, % means get the remainder of
// so 12 % 10 = 2, and 8 % 7 = 1
walkingIndex = (walkingIndex+1)%walkingFrames.length;
}
public Image getImage() {
// if our state is walking then give out a walking frame
if(state.equals("walking")) {
return walkingFrames[walkingIndex];
} else {
// otherwise we can assume were standing, so show that image instead
return still;
}
}
public void keyPressed(KeyEvent e) {
... same stuff
state = "walking";
}
public void keyReleased(KeyEvent e) {
... same stuff
state = "standing";
}
}

If i understand the question right, you are looking for a keyListener. In that case, you can do two things. Add keybindings or add an KeyListener.
Please have in mind that i haven't tested the code on your template, it work well for me in an AWT frame. Hope it helps
First implement the EventListener to Dude
public class Dude implements KeyListener{ ...
For the KeyListener to work you must have a focusable component..
component.addKeyListener(this);
component.setFocusable(true);
component.setFocusTraversalKeysEnabled(false);
The method below will be implemented with the KeyListener
#Override
public void keyPressed(KeyEvent e) {
int x = e.getKeyCode();
switch(x){
case KeyEvent.VK_UP:
// Do Your stuff
break;
case KeyEvent.VK_DOWN:
// Do Your stuff
break;
case KeyEvent.VK_RIGHT:
// Do Your stuff
break;
case KeyEvent.VK_LEFT:
// Do Your stuff
break;
}
}

Related

Processing, bullet position for firing

I am very new to Processing, and given myself the task of creating a defenders type game, however I can't figure out how to get the bullet to fire at the same position as the defender, I created a 'Defenders' class and a 'bullet' class and tried to use the variables that are in the defenders class in the bullet class however it is still not working, any help would be greatly appreciated.
//////bullet class variables
int y = d1.y;
int x = d1.x;
int speedX = -1;
int size = 10;
///moving the bullet
void move()
{
x=x-speedX;
}
//////drawing the bullet
void render()
{
fill(200,0,250);
rect(x,y,size+15,size);
}
/////getting the bullet to move in response to the mouse
void keyPressed()
{
d1.keyPressed();
if(key == CODED)
{
if(keyCode == CONTROL)
{
render();
move();
}
}
//////Defender class variables
int y = 25;
int x = 50;
int deltaX = 4;
////drawing the defender
void render()
{
fill (250, 0, 0);
rect(x,y,25,50);
triangle(75,y+15,75,y+35,90,y+25);
}
//////moving the defender in response to the mouse
void keyPressed()
{
if(keyPressed == true)
{
if(keyCode == UP)
{
y=y-1;
}
if(keyCode==DOWN)
{
y=y+1;
}
}
}
}

Stop player movement when releasing a key

I am making a game in Java, and I am working on player movement, but whenever a press a directional key, the player moves but doesn't stop when I release the key.
I can't seem to see what I am doing wrong. May someone point me in the right direction?
// Input class implements KeyListener
public static final int LEFT = 0;
public static final int RIGHT = 1;
public static final int UP = 2;
public static final int DOWN = 3;
public boolean[] keys = new boolean[64];
public void getKeys(KeyEvent e, boolean move) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
keys[LEFT] = move;
break;
case KeyEvent.VK_RIGHT:
keys[RIGHT] = move;
break;
case KeyEvent.VK_UP:
keys[UP] = move;
break;
case KeyEvent.VK_DOWN:
keys[DOWN] = move;
break;
case KeyEvent.VK_BACK_QUOTE:
keys[BQUOTE] = move;
break;
}
keys[OTHER] = move;
}
#Override
public void keyPressed(KeyEvent e) {
getKeys(e, true);
}
#Override
public void keyReleased(KeyEvent e) {
getKeys(e, false);
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
// Player Class
public void tick() {
if (Engine.key_input.keys[KInput.LEFT]) {
dx = -speed;
animDir = SpriteLoader.L;
sprite = SpriteLoader.anim(SpriteLoader.ANIM_PLAYER, animDir);
}
if (Engine.key_input.keys[KInput.RIGHT]){
dx = speed;
animDir = SpriteLoader.R;
sprite = SpriteLoader.anim(SpriteLoader.ANIM_PLAYER, animDir);
}
if (Engine.key_input.keys[KInput.UP]){
dy = -speed;
animDir = SpriteLoader.U;
sprite = SpriteLoader.anim(SpriteLoader.ANIM_PLAYER, animDir);
}
if (Engine.key_input.keys[KInput.DOWN]){
dy = speed;
animDir = SpriteLoader.D;
sprite = SpriteLoader.anim(SpriteLoader.ANIM_PLAYER, animDir);
}
}
// Engine Class
public class Engine {
public Input key_input;
public Engine() {
key_input = new Input();
}
// add keyListener(Input) to component
}
This is not enough info from you. But this is suspicious:
public boolean[] keys = new boolean[64]
Where is the code that says, "I've used this keys value, now I want to ignore it next time"?
In your tick method, you only ever check for a "pressed" state, you never reset the movement delta
For example...
public void tick() {
if (Engine.key_input.keys[KInput.LEFT]) {
dx = -speed;
} else {
dx = 0;
}
I would make determinations of animDir and sprite based on the dx and dy variables after you've updated the deltas.
I would also check the left and right, and up and down in a single if block...
For example
if (Engine.key_input.keys[KInput.LEFT]) {
dx = -speed;
} else if (Engine.key_input.keys[KInput.RIGHT]) {
dx = speed;
} else{
dx = 0;
}
This ensures that you don't accidentally reset the movement
In your handler, you are only ever setting the keys[] = true, but you are not ever returning them back to false.
You need to add a keyReleased() method that will un-move all keys that have been released.

Applet not showing image

I was following this tutorial here
and I downloaded its source code and ran but the image is not showing.
here is the result
I was expecting that the result would be like this
same as the result in the tutorial.
Here is the code:
StartingClass.java
package kiloboltgame;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.net.URL;
public class StartingClass extends Applet implements Runnable, KeyListener {
private Robot robot;
private Image image, character;
private Graphics second;
private URL base;
#Override
public void init() {
setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Q-Bot Alpha");
try {
base = getDocumentBase();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.toString());
}
// Image Setups
character = getImage(base, "data/character.png");
System.out.println(" "+base);
}
#Override
public void start() {
robot = new Robot();
Thread thread = new Thread(this);
thread.start();
}
#Override
public void stop() {
// TODO Auto-generated method stub
}
#Override
public void destroy() {
// TODO Auto-generated method stub
}
#Override
public void run() {
while (true) {
robot.update();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void update(Graphics g) {
if (image == null) {
image = createImage(this.getWidth(), this.getHeight());
second = image.getGraphics();
}
second.setColor(getBackground());
second.fillRect(0, 0, getWidth(), getHeight());
second.setColor(getForeground());
paint(second);
g.drawImage(image, 0, 0, this);
}
#Override
public void paint(Graphics g) {
g.drawImage(character, robot.getCenterX() - 61, robot.getCenterY() - 63, this);
}
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Move up");
break;
case KeyEvent.VK_DOWN:
System.out.println("Move down");
break;
case KeyEvent.VK_LEFT:
robot.moveLeft();
break;
case KeyEvent.VK_RIGHT:
robot.moveRight();
break;
case KeyEvent.VK_SPACE:
System.out.println("Jump");
robot.jump();
break;
}
}
#Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Stop moving up");
break;
case KeyEvent.VK_DOWN:
System.out.println("Stop moving down");
break;
case KeyEvent.VK_LEFT:
robot.stop();
break;
case KeyEvent.VK_RIGHT:
robot.stop();
break;
case KeyEvent.VK_SPACE:
System.out.println("Stop jumping");
break;
}
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
Robot.java
package kiloboltgame;
import java.awt.Graphics;
public class Robot {
private int centerX = 100;
private int centerY = 382;
private boolean jumped = false;
private int speedX = 0;
private int speedY = 1;
public void update() {
// Moves Character or Scrolls Background accordingly.
if (speedX < 0) {
centerX += speedX;
} else if (speedX == 0) {
//System.out.println("Do not scroll the background.");
} else {
if (centerX <= 150) {
centerX += speedX;
} else {
//System.out.println("Scroll Background Here");
}
}
// Updates Y Position
centerY += speedY;
if (centerY + speedY >= 382) {
centerY = 382;
}
// Handles Jumping
if (jumped == true) {
speedY += 1;
if (centerY + speedY >= 382) {
centerY = 382;
speedY = 0;
jumped = false;
}
}
// Prevents going beyond X coordinate of 0
if (centerX + speedX <= 60) {
centerX = 61;
}
}
public void moveRight() {
speedX = 6;
}
public void moveLeft() {
speedX = -6;
}
public void stop() {
speedX = 0;
}
public void jump() {
if (jumped == false) {
speedY = -15;
jumped = true;
}
}
public int getCenterX() {
return centerX;
}
public int getCenterY() {
return centerY;
}
public boolean isJumped() {
return jumped;
}
public int getSpeedX() {
return speedX;
}
public int getSpeedY() {
return speedY;
}
public void setCenterX(int centerX) {
this.centerX = centerX;
}
public void setCenterY(int centerY) {
this.centerY = centerY;
}
public void setJumped(boolean jumped) {
this.jumped = jumped;
}
public void setSpeedX(int speedX) {
this.speedX = speedX;
}
public void setSpeedY(int speedY) {
this.speedY = speedY;
}
}
and here is my file structure in intelij
Whats wrong with the code?? I tride the "../data/character.png" and "../src/data/character.png" but it didnt work.
applet.html the page loading the applet.
data (directory)
Character.png
If that is the structure of the server, the image will be available by:
getImage(base, "data/character.png");
I stressed server above since that is apparently not how your IDE is set up.
Can you elaborate more?
You opened the src/kilobolt path to show the locations of the source files, but it you expand the bin folder and trace down, you'll probably find the .class files in the bin/kilobolt directory.
An IDE typically won't use an HTML file for loading the applet, but if IntelliJ did, it would probably put it in the bin directory so it has direct access to the class files.
The path from there to the image would be ../data/character.png, but instead of using that path, suggest you get the IDE to copy the image into the bin.
At this stage it has become about IntelliJ so any further questions you have, will need to be about the IDE and the run-time class-path it uses.
This seems to be an image issue. The computer is not able to find the location of the image, or the image is being drawn under the applet.
IF you are using a linux/Mac/unix machine, most of time, I have had to either start from the root folder such as /Users/.....to the source folder, or when using a directory that is closer, just use '/' in front of it. Example is:
You're using a directory named src, with an 'img' folder inside. To get to the 'img' contents, you have two options:
//......src/img
or
/src/img/....
Hope that helped with anything
Copy your data folder into the bin folder.
Clean the project and run.
It will work.
#Luiggi Mendoza I had the same issue and was able to resolve it by right clicking on 'character.png' and selecting properties and then copying the image's location all the way from its root. In my case it was "/Users/macbookpro/NetBeansProjects/Kilobolt/src/data/character.png" and bingo the robot appeared in the applet window.
And yeah, i am learning game from the same website as you were 3 years back

How to create random monsters

I am making a game like Space Impact. In my game the rockets are working correctly, but I can't create monsters randomly. Monsters are on the screen but they aren't moving so they aren't active
How can I do this?
public class Dnm extends JFrame implements Runnable {
Graphics dbg;
Image dbImage;
Image Pik1;
Image Boss;
static ImageIcon active;
int x, y, xDirection, yDirection, BossX, BossY;
public void run() {
try {
while (true) {
move();
boss();
Thread.sleep(10);
}
} catch (Exception e) {
System.out.println("Uh-oh, something went wrong!.");
}
}
private void move() {
x += xDirection;
y += yDirection;
}
private void boss() {
while (BossX == 0) {
BossX = getX() - 1;
}
Random rastgele = new Random(getY());
BossY = rastgele.nextInt();
}
public void setXDirection(int xdir) {
xDirection = xdir;
}
public void setYDirection(int ydir) {
yDirection = ydir;
}
// KEY COMMANDS //
public class AL extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == e.VK_LEFT) {
setXDirection(-1);
}
if (keyCode == e.VK_RIGHT) {
setXDirection(+1);
}
if (keyCode == e.VK_UP) {
setYDirection(-1);
}
if (keyCode == e.VK_DOWN) {
setYDirection(+1);
}
}
#Override
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == e.VK_LEFT) {
setXDirection(0);
}
if (keyCode == e.VK_RIGHT) {
setXDirection(0);
}
if (keyCode == e.VK_UP) {
setYDirection(0);
}
if (keyCode == e.VK_DOWN) {
setYDirection(0);
}
}
#Override
public void keyTyped(KeyEvent e) {
}
}
// CONSTRUCTOR //
public Dnm() {
//Image Import
ImageIcon still = new ImageIcon("img/rocket.png");
Pik1 = still.getImage();
addKeyListener(new AL());
setTitle("Dnm");
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
setVisible(true);
x = 15;
y = 15;
}
public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void paintComponent(Graphics g) {
ImageIcon background = new ImageIcon("img/space.jpeg");
Image background1 = background.getImage();
ImageIcon still1 = new ImageIcon("img/Alien.png");
Boss = still1.getImage();
g.setColor(Color.red);
g.drawImage(background1, 0, 0, this);
g.drawImage(Boss, BossX, BossY, this);
g.drawImage(Pik1, x, y, this);
g.setColor(Color.blue);
repaint();
}
public static void main(String[] args) {
Dnm game = new Dnm();
Thread t1 = new Thread(game);
t1.start();
}
}
Thank You.
With your code being incomplete, it is hard to say for sure, but this line looks suspicious:
while (BossX == 0) {
BossX = getX() - 1;
}
This code is mostly likely going to be executed once, right? If BossX is initially zero, the code executes where you change its value. On the next update, BossX is not zero (presumably), so the code doesn't execute. Since BossX is the X coordinate where you are drawing the boss, then it will not move. Instead it just gets redrawn over and over in the same spot.
To get the monster to move randomly, increment or decrement both the X and Y coordinate values randomly during each game loop. Add a second random variable to cause them to move at random speeds in the random direction (by adjusting the coordinate value by a value greater than one).
As NPE commented, you should step through the code in a debugger and find out precisely what is going on.
I am fairly a beginner at programming, but here is my best attempt:
I would create a method that is called every x seconds that generates a random number using Math.Random(). I would say
int number = .5;
if(number > Math.Random())
GenerateMonster();
Your GenerateMonster method would then create a new object with the default values for monster. In order for the monster's created to act a certain way, you need to inherit those functions wherever you defined how you want the monster to act. I don't see the code for these functions so I am assuming you just didn't list them. Hope this at least helps. Good Luck!

My boolean method java

I've done quite a bit of searching for an answer to this, and some editing and I cant get it to work. I think there's something wrong with my boolean method, getColor(). Im trying to use it in a loop from a different class.
herse my getColor method, from the AvatarPanel class
public boolean setColor(boolean good)
{
if (good == true)
what--;
avatars.get(0).setBackground(colors.get(what));
repaint();
if (good == false)
what++;
avatars.get(0).setBackground(colors.get(what));
repaint();
return good;
}
And here's the attackPerformed method from the Background class that Im trying to use getColor in. Im not sure if I wrote one of the methods wrong, or if attackPerformed needs a listener. The game is still running normally and working fine. I just wanted some help making sure these were at least written correctly.
I decided it might be a good idea to show the background constructor because I think its where I need to call attackPerformed. I can't figure out where it is that I need to call the attackPerformed, though I'm pretty sure it'll be in the background constructor. The attackPerformed method is shown below, constructor is at top.
public class Background extends JPanel implements Constants, ActionListener
{
private static final long serialVersionUID = 1L;
private final Color BACK_COLOR = Color.GRAY;
private ArrayList<Sprite> sprites;
private Avatar avatar;
/** Constructor */
public Background()
{
sprites = new ArrayList<Sprite>();
reset(0);
setBackground(BACK_COLOR);
KeyboardFocusManager manager =KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.addKeyEventDispatcher(new KeyEventDispatcher()
{
public boolean dispatchKeyEvent(KeyEvent event)
{
int x = 0, y = 0;
double angle = 0;
Point p = avatar.getPosition();
switch (event.getKeyCode())
{
case KeyEvent.VK_DOWN:
y=6;
angle=270;
break;
case KeyEvent.VK_UP:
y = -6;
angle = 90;
break;
case KeyEvent.VK_LEFT:
x = -6;
break;
case KeyEvent.VK_RIGHT:
x = 6;
angle = 180;
break;
}
avatar.setParameters();
p.x += x;
p.y += y;
avatar.setPosition(p);
avatar.setAngle(angle);
if (!getBounds().contains(avatar.getBounds()))
{
avatar.restore();
Toolkit.getDefaultToolkit().beep();
return true;
}
repaint();
return true;
}
});
Timer timer = new Timer(15, this);
timer.start();
} //end of constructor
public void attackPerformed()
{
for(Sprite s : sprites)
{
AvatarPanel panel = new AvatarPanel();
Rectangle r = new Rectangle(sprites.get(0).getBounds());
Rectangle p = new Rectangle(sprites.get(1).getBounds());
if(r.intersects(p))
{
panel.setColor(false);
}
}
}
public void actionPerformed(ActionEvent e)
{
for (Sprite s : sprites)
{
if (s instanceof Move)
{
s.setParameters();
for (int i=0; i<3; i++)
{
((Move)s).nextPosition();
if (!getBounds().contains(s.getBounds()))
{
((Move) s).moveFailed();
}
else break;
}
}
}
repaint();
}
public #Override void paintComponent(Graphics g)
{
super.paintComponent(g); /* Let the parent class do its painting */
for (Sprite sprite: sprites)
{
sprite.draw(g);
}
}
public void reset(int level)
{
Sprite sprite = null;
int x, y, angle;
double scale, min, max;
sprites.clear();
int[] figures = FIGURES[level];
for (int f=0; f<figures.length; f++)
{
for (int i=0; i<figures[f]; i++)
{
x = (int)(Math.random()*600 + 100);
y = (int)(Math.random()*400 + 100);
switch (f)
{
case 0:
sprite = avatar = new Avatar(x,y);
break;
case 1:
sprite = new Predator(x,y);
break;
case 2:
sprite = new Mine(x,y);
break;
case 3:
sprite = new Shield(x,y);
break;
}
angle = (int)(Math.random()*360);
sprite.setAngle(angle);
min = sprite.getMinScaleFactor();
max = sprite.getMaxScaleFactor();
scale = Math.random() * (max - min) + min;
sprite.setScale(scale);
sprites.add(sprite);
repaint();
}
}
}
}
Looks like your if and else case are very similar.
You can simplify it to this.
public boolean setColor(boolean good)
{
what+=good?-1:+1;
avatars.get(0).setBackground(colors.get(what));
repaint();
    return good;
}
I would strongly recommend to use brackets, as the method repaint() would execute outside of if statement. Since, boolean can only have two possible values you can use 'else' instead of second if...
public boolean setColor(boolean good)
{
if (good == true)
{
what--;
avatars.get(0).setBackground(colors.get(what));
repaint();
}
else
{
what++;
avatars.get(0).setBackground(colors.get(what));
repaint();
}

Categories

Resources