So I'm making a game, and the user controls a rectangle that moves left to right along a box at the bottom, but it falls of the edges and I don't know how to stop this, help would be appreciated. I have tried many things to stop this but nothing has worked and I really need some help to keep the rectangle actually on the screen.
public Rectangle character;
public Rectangle bottomBox;
public int charW = 100;
public int charH = 15;
public boolean right = false;
public boolean left = false;
public boolean up = false;
public boolean down = false;
public boolean mouseActive = false;
public Point mouse;
public Keying(Display f, Images i){
character = new Rectangle(180, 180, charW, charH);
bottomBox = new Rectangle (0, 350, 9000, 30);
f.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_D){
mouseActive = false;
right = true;
character.x += 1;
}
if(e.getKeyCode() == KeyEvent.VK_A){
mouseActive = false;
left = true;
character.x -= 1;
}
if(e.getKeyCode() == KeyEvent.VK_M){
mouseActive = false;
}
}
public void keyReleased(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_D){
right = false;
}
if(e.getKeyCode() == KeyEvent.VK_A){
left = false;
}
}
});
f.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e){
int mouseX = e.getX();
int mouseY = e.getY();
mouse = new Point(mouseX, mouseY);
if(mouseActive && character.x != Main.w - charW){
character.x = mouse.x;
character.y = mouse.y;
}
repaint();
}
});
f.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
mouse = new Point (e.getX(), e.getY());
if(e.getButton() == MouseEvent.NOBUTTON){
character.x = mouse.x;
character.y = mouse.y;
}
}
});
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Point pt1 = new Point(character.x, character.y + character.height);
if(!bottomBox.contains(pt1) && !mouseActive){
character.y++;
}
this.setBackground(Color.YELLOW);
{g.setColor(Color.BLACK);
g.fillRect(character.x, character.y, character.width, character.height);}
{g.setColor(Color.darkGray);
g.fillRect(bottomBox.x, bottomBox.y, bottomBox.width, bottomBox.height);
if(right && character.x != Main.w - charW){
character.x += 1;
}
if(left && character.x != 0){
character.x -= 1;
}
repaint();
}
}
}
I really need some help to keep the rectangle actually on the screen.
Well you need to do some basic logic check to see if the rectangle can be painted within the bounds of the panel.
You now the location of the rectangle and the width so just check if the sum is not greater than the width of the panel.
For example you can check out the logic found in Motion Using the Keyboard. All the code examples contain a move(...) method which does the boundary checking.
Also, note from the example that your painting code should NOT be calculation the location of the characters. A painting method should only paint the character based on the current properties of the character. Only a user action should change a property of the character because you can't control when the painting method is called.
Related
I'm working on a snake game, and I'm trying to make the snake move to the right. The issue here is the snake isn't actually moving, it just seems to copy itself to the right and also it's not going to the right automatically you have to keep pressing the key.
I am really not sure what the issue is, I made some code without any images. That should make the code run able for testing as it is.
public class Game{
static Graphics g;
public static void main(String[] args) {
JFrame b = new JFrame("Snake");
b.setBounds(300,60,905,700);
b.setBackground(Color.DARK_GRAY);
b.setResizable(false);
Snake snake = new Snake();
b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.add(snake);
b.setVisible(true);
}
}
public class Snake extends JPanel implements KeyListener,ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private int[] snakeXlength = new int [750];
private int[] snakeYlength = new int [750];
private boolean right = true;
private boolean left = false;
private boolean up = false;
private boolean down = false;
private ImageIcon rightmouth;
private ImageIcon snakeimage;
private ImageIcon leftmouth;
private ImageIcon downmouth;
private ImageIcon upmouth;
private ImageIcon enemy;
private Timer timer;
private int snakeDelay = 100;
private int moves = 1;
private int lengtOfSnake = 3;
public Snake(){
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(snakeDelay, this);
timer.start();
}
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.drawRect (20, 24, 851, 612);
g.setColor(Color.BLACK);
g.fillRect (21, 25, 850, 610);
if (moves == 0) {
snakeXlength[2]= 63;
snakeXlength[1]= 83;
snakeXlength[0]= 100;
snakeYlength[2]= 100;
snakeYlength[1]= 100;
snakeYlength[0]= 98;
rightmouth = new ImageIcon("rightmouth.png");
rightmouth.paintIcon(this, g, snakeXlength[0], snakeYlength[0]);
}
for(int a = 0; a < lengtOfSnake; a++) {
if (a == 0 && right) {
if (a == 0 && right) {
g.setColor(Color.RED);
g.drawRect(5,10,snakeXlength[a],snakeYlength[a]);
g.fillRect (snakeXlength[a],snakeYlength[a],21,21);
g.drawRect(5,10,snakeXlength[a],snakeYlength[a]);
// rightmouth = new ImageIcon("rightmouth.png");
//rightmouth.paintIcon(this, g, snakeXlength[a], snakeYlength[a]);
}
if (a == 0 && left) {
leftmouth = new ImageIcon("leftmouth.png");
leftmouth.paintIcon(this, g, snakeXlength[a], snakeYlength[a]);
}
if (a == 0 && down) {
downmouth = new ImageIcon("downmouth.png");
downmouth.paintIcon(this, g, snakeXlength[a], snakeYlength[a]);
}
if (a == 0 && up) {
upmouth = new ImageIcon("uptmouth.png");
upmouth.paintIcon(this, g, snakeXlength[a], snakeYlength[a]);
}
if (a != 0) {
g.setColor(Color.GREEN);
g.fillOval(snakeXlength[a],snakeYlength[a],17,17);
//snakeimage = new ImageIcon("snakeimage.png");
//snakeimage.paintIcon(this, g, snakeXlength[a], snakeYlength[a]);
}
}
g.dispose();
}
public void keyPressed(KeyEvent e) {
timer.start();
if(right) {
for (int r = lengtOfSnake-1; r >= 0;r--) {
snakeYlength[r+1] = snakeYlength[r];
}
for(int r = lengtOfSnake;r >=0;r--) {
if(r==0) {
snakeXlength[r] = snakeXlength[r] +25;
}
else {
snakeXlength[r] = snakeXlength[r-1];
}
if(snakeXlength[r] > 850){
snakeXlength[r] = 25;
}
}
repaint();
}
if(left) {
}
if(up) {
}
if(down) {
}
}
#Override
public void keyTyped(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
moves++;
right = true;
if(left != true) {
right = true;
}
else
{
right = false;
left = true;
}
down = false;
up = false;
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
moves++;
left = true;
if(right != true) {
left = true;
}
else
{
left = false;
right = true;
}
down = false;
up = false;
} if(e.getKeyCode() == KeyEvent.VK_UP) {
moves++;
up = true;
if(down != true) {
up = true;
}
else
{
up = false;
down = true;
}
left = false;
right = false;
}
if(e.getKeyCode() == KeyEvent.VK_DOWN) {
moves++;
down = true;
if(up != true) {
down = true;
}
else
{
up = true;
down = false;
}
left = false;
right = false;
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
it just seems to copy itself to the right
public void paint(Graphics g)
{
g.setColor(Color.WHITE);
Custom painting should be done by overriding paintComponent(...) and then you need to invoke super.paintComponent(...):
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.WHITE);
This will make sure the background of the panel is cleared before doing the custom painting.
it's not going to the right automatically you have to keep pressing the key.
Well, that is usually the way a game is designed. You only have motion when the key is pressed as this will keep generating events. Then if you don't want motion you just don't press any keys.
If you want animation then you use a Swing Timer. Each time the Timer fires you invoke a move(...) method. This method would need to look at your "direction" variable to determine whether to move the snake left, right, up or down.
Check out:
Motion Using the Keyboard for animation when a key is pressed and held and
get width and height of JPanel outside of the class for continuous animation
So I am trying to make a game like Snake, but I am running into some issues.
I want to repeat the if statement inside of of the moveup class using a while loop, but
when I try to use the KeyListener to listen for the key press of the up arrow key to break the while loop it acts like it only looped once (moved up 5 pixels). The loop is supposed to make the snake continue going up without having to click multiple times, but it just moves five (the value I set it to do) pixels. Here is the code:
public class Snake extends JFrame implements KeyListener {
int ballX = 50;
int ballY = 50;
int playerX = 250;
int playerY = 250;
boolean up = false;
boolean right = false;
boolean down = false;
boolean left = true;
class DrawPane extends JPanel {
public void paintComponent(Graphics gc) {
Random rand = new Random();
int dotsX = rand.nextInt(500) + 1;
int dotsY = rand.nextInt(500) + 1;
Graphics g = this.getGraphics();
setVisible(true);
super.paintComponents(gc);
gc.setColor(Color.BLUE);
gc.fillRect(ballX, ballY, 10, 10);
gc.setColor(Color.RED);
gc.fillRect(playerX, playerY, 10, 10);
}
}
public Snake(String title) {
super(title);
JFrame frame = new JFrame();
setContentPane(new DrawPane());
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setSize(500, 500);
this.setBackground(Color.YELLOW);
this.setResizable(false);
this.addKeyListener(this);
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if (e.getKeyCode() == KeyEvent.VK_UP) {
up = true;
right = false;
down = false;
left = false;
moveup(e);
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
up = false;
right = false;
down = true;
left = false;
movedown(e);
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
up = false;
right = true;
down = false;
left = false;
moveright(e);
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
up = false;
right = false;
down = false;
left = true;
moveleft(e);
}
}
public void moveup(KeyEvent e) {
while (up) {
if (playerX < 500 || playerX > 0) {
playerX = playerX + 5;
repaint();
if (e.getKeyChar() == KeyEvent.VK_UP)
break;
}
}
}
public void moveright(KeyEvent e) {
if (playerX < 500 || playerX > 0) {
playerX = playerX + 5;
repaint();
// moveright();
}
}
public void movedown(KeyEvent e) {
if (playerY < 500 || playerY > 0) {
playerY = playerY + 5;
repaint();
// movedown();
}
}
public void moveleft(KeyEvent e) {
if (playerX < 500 || playerX > 0) {
playerX = playerX - 5;
repaint();
// moveleft();
}
}
public void snakePanel() {
JPanel panel1 = new JPanel();
panel1.setBackground(Color.red);
}
public void ActionListener() {
}
public static void main(String[] args) {
Snake r = new Snake("Snake");
}
}
It never loops because of the break. Effectively you're saying:
if keycode is up
loop
move up
break if keycode is up // Will always be true
More so, you shouldn't be looping in an event handler like that. Event handlers should execute and return quickly else you'll block the event thread. Should be using a timer to act as a heartbeat and update the position/repaint periodically.
Keep in mind that you DON'T want to use Swing for more advanced games in the future.
--- Quick solution:
Just remove your while(). The KeyListener interface lets you abstract the concept of "while this key is pressed, do this". Instead, when you implement the interface, you say: "whenever this key is pressed, do this". It's an event.
Here's your working code:
http://pastebin.com/b0CZDxpD
This is the code for my game. The entire image flickers every 30 ms (aprox)
public class MainGame extends Canvas implements Runnable, KeyListener, MouseListener, MouseMotionListener {
boolean isRunning = false;
public boolean isClicked, isReleased, lClick, rClick, down, up, upPressed;
public boolean drawArrow;
public boolean lastLeft, lastRight, goingLeft, goingRight, left, right;
public int x = 0, y = 0, aX = 250, aY = 250;
double modifier = 4;
public Graphics g;
ImageIcon background = new ImageIcon("F:/workspace/RPGGame/src/healy.jpg");
Image picture = background.getImage();
Image offscreen;
ControlBase base = new ControlBase();
Graphics buffer;`
private boolean fireLeft;
private boolean fireRight;
private int arrowCounter = 0;
public MainGame () {
base.frame.setVisible(true);
base.frame.setResizable(false);
base.frame.setMinimumSize(new Dimension(1024, 768));
base.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
base.frame.setLocationRelativeTo(null);
base.frame.addMouseListener(this);
base.frame.addKeyListener(this);
JPanel panel = new JPanel();
Container pane = base.frame.getContentPane();
pane.add(panel);
pane.paint(g);
base.frame.setVisible(true);
Graphics g = base.frame.getGraphics();
g.drawImage(picture, x, y, this);
}
public void run() {
while(isRunning) {
paint(base.frame.getGraphics());
//moves left
if (left == true){
x+=1;
lastLeft = true;
lastRight = false;
}
//moves right
if (right == true){
x-=1;
lastLeft = false;
lastRight = true;
}
//moves down
if (down == true){
y-=1;
}
if (goingLeft == true) {
aX--;
}
if (goingRight == true) {
aX++;
}
if(attackStyle == 1) {
melee();
}
else if (attackStyle == 2) {
range();
}
else {
magic();
}
System.out.println(arrowCounter);
base.arrowMech();
fireLeft = base.fireLeft;
fireRight = base.fireRight;
base.frame.repaint();
}
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.clearRect(0, 0, 1024, 768);
g.setColor(Color.red);
g.fillOval(250, 250, 20, 20);
g.drawImage(picture, x, y, this);
if (drawArrow == true) {
if (fireLeft) {
arrowCounter++;
goingLeft = true;
goingRight = false;
base.drawArrow(g);
}
if (fireRight) {
arrowCounter++;
goingLeft = false;
goingRight = true;
base.drawArrow(g);
}
}
if ((arrowCounter >=450) || (!drawArrow)){
arrowCounter = 0;
aX = 250;
aY = 250;
}
}
public void update(Graphics g) {
repaint();
}
public void start() {
isRunning = true;
new Thread(this).start();
}
public void stop() {
isRunning = false;
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
public void mouseClicked(MouseEvent click) {
if(click.getButton() == 1) {
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
/** This method handles mouse clicks
*/
public void mousePressed(MouseEvent click) {
if(SwingUtilities.isLeftMouseButton(click)) {
lClick = true;
}
else if (SwingUtilities.isRightMouseButton(click)) {
rClick = true;
}
}
/** This method handles the release of mouse clicks
*/
public void mouseReleased(MouseEvent release) {
if(SwingUtilities.isLeftMouseButton(release)) {
lClick = false;
}
else if (SwingUtilities.isRightMouseButton(release)) {
rClick = false;
}
}
/**
* This method handle the movement for the character and all other key binds
*/
public void keyPressed(KeyEvent e) {
//left arrow
if(e.getKeyCode() == 37 || e.getKeyCode() == 65){
left = true;
}
//up arrow
if(e.getKeyCode() == 38 || e.getKeyCode() == 87){
up = true;
upPressed = true;
down = false;
}
//right arrow
if(e.getKeyCode() == 39 || e.getKeyCode() == 68){
right = true;
}
//down arrow
if(e.getKeyCode() == 40 || e.getKeyCode() == 83){
down = true;
}
}
/**
* This method handles the stopping of movement for the character and stoping all other key binds
*/
public void keyReleased(KeyEvent e) {
//left arrow
if(e.getKeyCode() == 37 || e.getKeyCode() == 65){
left = false;
}
//up arrow
if(e.getKeyCode() == 38 || e.getKeyCode() == 87){
up = false;
upPressed = false;
}
//right arrow
if(e.getKeyCode() == 39 || e.getKeyCode() == 68){
right = false;
}
//down arrow
if(e.getKeyCode() == 40 || e.getKeyCode() == 83){
down = false;
}
}
public void keyTyped(KeyEvent e) {
}
Any help would be appreciated. Have tried using a bufferstrategy to no avail. Is there any other way to do it without using a bufferstrategy?
I don't think you need to call the paint(Graphics g) method. It should be called automatically by the parent when needed. Especially since you are calling repaint at the end of the code
I'm coding a game and I'm using Java's Swing. And right now i'm trying to get the KeyListeners and Action listeners to work.
What I'm trying to do is to make my object to move according to what key i'm pressing. (Left,Right,Up,Down), But for some reason nothing happens when i press either of these keys, but when i press 3 of them at the same time. the object is strangely moving to the left..
So here's my code for the class to create the Runner-object:
import java.awt.*;
public class Runner{
private int xpos, ypos, base, side;
public Runner(int b, int h ) {
base = b;
side = h;
}
public void setPosition(int x, int y){
xpos = x;
ypos = y;
}
public void view(Graphics g) {
int x[] = { xpos, xpos-base/2, xpos + base/2};
int y[] = { ypos, ypos + side, ypos + side };
g.setColor(Color.lightGray);
g.fillPolygon( x, y, 3 );
g.setColor(Color.darkGray);
g.drawLine(xpos, ypos, xpos, ypos + side);
}
public void shoot(Graphics g){
g.setColor(Color.red);
g.drawLine(xpos,ypos, xpos, 0);
}
}
And here's the code thats suppose to run the damn thing:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RunningGame extends JPanel implements KeyListener, ActionListener{
Runner rs;
int x,y;
Timer t;
boolean shot = false;
boolean left = false, right = false, up = false, down = false;
public RunningGame() {
x = 100;
y = 150;
rs = new Runner(40,60);
rs.setPosition(x,y);
this.addKeyListener(this);
this.setBackground(Color.black);
t = new Timer(40, this);
t.start();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
rs.view(g);
if(shot) rs.shoot(g);
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 37) {left = true;}
if (e.getKeyCode() == 39) {right = true;}
if (e.getKeyCode() == 38) {up = true;}
if (e.getKeyCode() == 40) {down = true;}
if (e.getKeyCode() == 32) {shot = true;}
rs.setPosition(x,y);
this.repaint();
}
public void keyReleased(KeyEvent e){
if (e.getKeyCode() == 37) left = false;
if (e.getKeyCode() == 39) right = false;
if (e.getKeyCode() == 38) up = false;
if (e.getKeyCode() == 40) down = false;
if (e.getKeyCode() == 32) shot = false;
this.repaint();
}
public void keyTyped(KeyEvent e){}
public void actionPerformed(ActionEvent e) {
if (left) {
if(right){
right = false;
x = x - 10; shot = false;
}
}
if (right) {
if(left){
left = false;
x = x + 10; shot = false;
}
}
if (up) {
if(down){
down = false;
y = y - 10; shot = false;
}
}
if (down) {
if(up){
up = false;
y = y + 10; shot = false;
}
}
rs.setPosition(x,y);
this.repaint();
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300, 300); f.setLocation(100,100);
f.setTitle("Running");
RunningGame p = new RunningGame();
f.add(p); f.setVisible(true);
p.requestFocus();
}
}
(This is not the final code it's just using an example with a spaceship, later i will use a different object, just wanna test the KeyListener and ActionListener so it works before proceeding.)
Anyways can anyone help me make the space ship move smoothly? and without having to release all keys to activate another? i.e If i hold left i want it to be able to press another button. so that if i press right, the space ship will start to move in that direction instead.
//MrElephants
In the blocks that look like:
if (left) {
if(right){
right = false;
x = x - 10; shot = false;
}
}
I think you should have x = x - 10; outside the second if:
if (left) {
if(right){
right = false;
shot = false;
}
x = x - 10;
}
although I'm not really sure what that inner if is for, maybe you should remove it completely (but keep the x -= 10 etc.). This should be sufficient to make the movement seem natural.
I've been told by my friend that my code isn't very OO. How would I make this more OO and reusable?
I tried making a class called level, that printed the images in level, but noting printed, so that didn't work.
(code dump coming, I'm sorry)
public class Main extends Applet implements Runnable, KeyListener,
java.awt.event.MouseListener {
double x_pos = 300;
double y_pos = 200;
int radius = 20;
int appletsize_x = 640;
int appletsize_y = 440;
double speed = 3;
float speedModifier = 1f;
Image grass;
Image hero;
Image hero45;
Image hero90;
Image hero135;
Image hero180;
Image hero225;
Image hero270;
Image hero315;
Image sprite;
Image tree;
Image path;
private boolean leftPressed;
private boolean rightPressed;
private boolean downPressed;
private boolean upPressed;
private Image dbImage;
private Graphics dbg;
public void init() {
Dimension dim = getMaximumSize();
this.setSize(appletsize_x, appletsize_y);
MediaTracker mt = new MediaTracker(this);
tree = getImage(getCodeBase(), "tree_64.png");
grass = getImage(getCodeBase(), "grassTile.png");
path = getImage(getCodeBase(), "path.png");
hero = getImage(getCodeBase(), "hero.png");
hero45 = getImage(getCodeBase(), "hero45.png");
hero90 = getImage(getCodeBase(), "hero90.png");
hero135 = getImage(getCodeBase(), "hero135.png");
hero180 = getImage(getCodeBase(), "hero180.png");
hero225 = getImage(getCodeBase(), "hero225.png");
hero270 = getImage(getCodeBase(), "hero270.png");
hero315 = getImage(getCodeBase(), "hero315.png");
sprite = getImage(getCodeBase(), "hero.png");
mt.addImage(hero, 0);
mt.addImage(path, 0);
mt.addImage(tree, 0);
mt.addImage(grass, 0);
mt.addImage(hero45, 0);
mt.addImage(hero90, 0);
mt.addImage(hero135, 0);
mt.addImage(hero180, 0);
mt.addImage(hero225, 0);
mt.addImage(hero270, 0);
try {
mt.waitForID(0);
} catch (InterruptedException ie) {
}
}
public void start() {
this.addKeyListener(this);
this.addMouseListener(this);
Thread th = new Thread(this);
th.start();
}
public void stop() {
}
public void destroy() {
}
public void run() {
// lower ThreadPriority
this.requestFocusInWindow();
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
while (true) {
if (downPressed && leftPressed) {
double y_decr, x_incr;
y_decr = Math.sqrt(Math.pow(speed, 2)) / 1.5;
x_incr = Math.sqrt(Math.pow(speed, 2)) / 1.5;
y_pos += y_decr;
x_pos -= x_incr;
} else if (downPressed && rightPressed) {
y_pos += Math.sqrt(Math.pow(speed, 2)) / 1.5;
x_pos += Math.sqrt(Math.pow(speed, 2)) / 1.5;
} else if (upPressed && rightPressed) {
y_pos -= Math.sqrt(Math.pow(speed, 2)) / 1.5;
x_pos += Math.sqrt(Math.pow(speed, 2)) / 1.5;
} else if (upPressed && leftPressed) {
y_pos -= Math.sqrt(Math.pow(speed, 2)) / 1.5;
x_pos -= Math.sqrt(Math.pow(speed, 2)) / 1.5;
} else {
// Hitting (right)
if (x_pos > this.getSize().width - radius) {
// x_speed = -x_speed;
}
if (leftPressed == true) {
x_pos -= speed * speedModifier;
}
if (rightPressed == true) {
x_pos += speed * speedModifier;
}
if (upPressed == true) {
y_pos -= speed * speedModifier;
}
if (downPressed == true) {
y_pos += speed * speedModifier;
}
}
// Hitting right
if (x_pos > this.getSize().width - 32) {
x_pos = this.getSize().width - 32;
} // Hitting left
if (x_pos < 0) {
x_pos = 0;
}
// } // Hitting top
if (y_pos < 0) {
y_pos = 0;
}
// Hitting bottom
if (y_pos > this.getSize().height - 32) {
y_pos = this.getSize().height - 32;
}
repaint();
try {
// Stop thread for 1 milliseconds
Thread.sleep(20);
} catch (InterruptedException ex) {
// do nothing
}
// set ThreadPriority to maximum value
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
}
}
public void paint(Graphics g) {
int layout = 0;
int coll = 0;
while (coll <= 440) {
drawRows(layout, grass, g, coll);
coll = coll + 32;
}
drawCollums(0, path, g, 180);
g.drawImage(tree, 50, 40, this);
g.drawImage(tree, 300, 20, this);
g.drawImage(tree, 500, 300, this);
int x_posI = (int) x_pos;
int y_posI = (int) y_pos;
if (downPressed && leftPressed) {
this.sprite = hero225;
} else if (downPressed && rightPressed) {
this.sprite = hero135;
} else if (upPressed && rightPressed) {
this.sprite = hero45;
} else if (upPressed && leftPressed) {
this.sprite = hero315;
} else if (leftPressed == true) {
this.sprite = hero270;
} else if (rightPressed == true) {
this.sprite = hero90;
} else if (upPressed == true) {
this.sprite = hero;
} else if (downPressed == true) {
this.sprite = hero180;
}
// this.sprite will contain value set on last "movement"
g.drawImage(this.sprite, x_posI, y_posI, this);
}
public void update(Graphics g) {
if (dbImage == null) {
dbImage = createImage(this.getSize().width, this.getSize().height);
dbg = dbImage.getGraphics();
}
dbg.setColor(getBackground());
dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
dbg.setColor(getForeground());
paint(dbg);
g.drawImage(dbImage, 0, 0, this);
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
leftPressed = true;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rightPressed = true;
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
upPressed = true;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
downPressed = true;
}
}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
leftPressed = false;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rightPressed = false;
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
upPressed = false;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
downPressed = false;
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("HIT!");
// 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
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
public void drawRows(int x, Image image, Graphics g, int coll) {
while (x <= appletsize_x) {
g.drawImage(image, x, coll, this);
x += 32;
}
}
public void drawCollums(int y, Image image, Graphics g, int coll) {
while (y <= appletsize_x) {
g.drawImage(image, coll, y, this);
y += 32;
}
}
}
You should ask your friend what he or she meant. If I were to guess, I would say that your Applet class is doing a lot of things: it's the animation loop; it's the key handler; it's the mouse handler; it's the UI. Those could be broken out into separate objects that were designed to work together.
Another improvement might be to translate your four ...Pressed flags into an integer from 0 through 7, representing the eight possible directions. For instance:
0 1 2
7 3
6 5 4
(You can assign the direction numbers any way you like.) Then you could use the direction number to index into an array of images. (This has nothing to do with being object-oriented, but it would simplify your code.)
Well for one thing, all those images should be in an array. And they should contain a filename so you can load them in a nice loop. You have over 3 pages of copy&paste code, that's absolutely horrible... What if you want to change the way they get loaded slightly?
Then, Math.sqrt(Math.pow(speed, 2)) jumps out at me. That's the equivalent of Math.abs(speed), and about 1/200x as fast.
This next part is particularly funny too. I won't comment on whether or not it's needed (and it most likely isn't, it's a design flaw on your part), but.. ya..
// Stop thread for 1 milliseconds
Thread.sleep(20);
I'd suggest you read books and article about OOP and in this particular case you should take a look at the MVC pattern (MVC article in wikipedia). For a good OO conception the events (keyPressed(KeyEvent e) for example) shouldn't be treated in the same class as the actual "graphics building" class.
Build a new package for your application and group all your data structures inside. Create a class for Your Hero, create classes for trees and grass. See how they can share attributes and create a class hierarchy, maybe with an abstract class.
These are just a few cues, it could be long to give you an Object Oriented course here ;)
But follows this tracks and read.
Also, you should learn how to stop threads elegantly.
And you could use inner classes for your listeners, even use a MouseAdater.
Regards,
Stéphane
You might like to study this game that also moves a player around a grid using the keyboard.