EDIT: This post suggests that it is an IDE specific problem, but the solution given is for IntelliJ. I'm using Eclipse.
I'm following this guide about game programming in Android. But before that it teaches about game programming in Java.
When I try to load an image in the applet as specified on the guide, nothing is shown, just the black background. My source code and the web's one are almost identical, how can I solve this?
Here is my code:
package game;
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 Incio 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);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("LAS AVENTURAS DE RABOCOP");
addKeyListener(this);
robot = new Robot();
try {
base = getDocumentBase();
} catch (Exception e) {
// TODO: handle exception
}
character = getImage(base, "/src/data/Robot.bmp");
System.out.println(base);
}
#Override
public void start() {
// TODO Auto-generated method stub
}
#Override
public void stop() {
// TODO Auto-generated method stub
}
#Override
public void destroy() {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent k) {
switch (k.getKeyCode()) {
case KeyEvent.VK_UP:
break;
case KeyEvent.VK_DOWN:
break;
case KeyEvent.VK_RIGHT:
break;
case KeyEvent.VK_LEFT:
break;
case KeyEvent.VK_SPACE:
break;
}
}
#Override
public void keyReleased(KeyEvent k) {
switch (k.getKeyCode()) {
case KeyEvent.VK_UP:
break;
case KeyEvent.VK_DOWN:
break;
case KeyEvent.VK_RIGHT:
break;
case KeyEvent.VK_LEFT:
break;
case KeyEvent.VK_SPACE:
break;
}
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
robot.update();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
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);
}
public void paint(Graphics g) {
g.drawImage(character, robot.getCenterX()-61, robot.getCenterY()-63, this);
}
}
Thanks.
Related
I am currently working on a 2D game which will be a puzzle. I got everything set up, got all my pieces added to my board (called View) and they're all aligned properly.
My next step is to select a piece by MouseEvent#mousePressed to be able to move it with the arrow keys with KeyEvent#keyPressed. The issue I'm currently running into is that my pieces will repaint themself whenever I move or resize the window. If I click on one piece and want to move it, the other pieces move too (in a way, they should not since one step equals about 100 pixel).
If anyone could tell me where my issue is and give me some advice, I would appreciate it.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Puzzle {
public static void main(String[] args) {
SwingUtilities.invokeLater(Puzzle::new);
}
public Puzzle() {
JFrame frame = new JFrame("Puzzle");
frame.setSize(400, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
View view = new View();
view.createPieces();
frame.setContentPane(view);
view.setFocusable(true);
MouseAdapterMod listener = new MouseAdapterMod(view);
view.addMouseListener(listener);
view.addKeyListener(listener);
frame.setVisible(true);
}
}
class View extends JPanel {
final List<Piece> pieces = new ArrayList<>();
public View() {
}
void createPieces() {
Piece topLeft = new Piece(100, 100, 0, Color.YELLOW);
pieces.add(topLeft);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D gc = (Graphics2D) g;
for (Piece needle : pieces) {
needle.translate(needle.getLocation().x, needle.getLocation().y);
gc.setColor(needle.color);
gc.fill(needle);
gc.draw(needle);
}
}
}
class Piece extends Polygon {
int x;
int y;
final Color color;
Point location;
Piece(int x, int y, int type, Color color) {
this.x = x;
this.y = y;
this.color = color;
this.location = new Point(x, y);
int[] arrX = new int[] { 0, 100, 100, -100, -100, 0 };;
int[] arrY = new int[] { 0, 0, -100, -100, 100, 100 };
for (int drawIndex = 0; drawIndex < arrX.length; drawIndex++) {
addPoint(arrX[drawIndex], arrY[drawIndex]);
}
}
Point getLocation() {
return location;
}
void setLocation(Point location) {
this.location = location;
}
}
class MouseAdapterMod implements MouseListener, KeyListener {
final View view;
Polygon current;
public MouseAdapterMod(View view) {
this.view = view;
}
#Override
public void mousePressed(MouseEvent e) {
for (Piece piece : view.pieces) {
if (piece.contains(e.getX(), e.getY())) {
current = piece;
System.out.println(current);
}
}
}
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
current.translate(0, -100);
view.repaint();
break;
case KeyEvent.VK_DOWN:
current.translate(0, +100);
view.repaint();
break;
case KeyEvent.VK_LEFT:
current.translate(-100, 0);
view.repaint();
break;
case KeyEvent.VK_RIGHT:
current.translate(+100, 0);
view.repaint();
break;
}
}
#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 mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#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
}
}
(Sorry for the indent, stackoverflow is messing it up)
EDIT: But the problem is, eventually I want to move my pieces using Piece#setLocation to always keep track of their current x/y coordinates. I figured, I need to invoke Piece#getLocation in my painting to draw them based on the location but yet I do not know how. Using Piece#setLocation literally does nothing.
If you revert back to your Piece code from this question, you can move pieces by:
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
view.translatePiece(0, -100);
break;
case KeyEvent.VK_DOWN:
view.translatePiece(0, +100);
break;
case KeyEvent.VK_LEFT:
view.translatePiece(-100, 0);
break;
case KeyEvent.VK_RIGHT:
view.translatePiece(+100, 0);
break;
}
}
And adding to your view:
void translatePiece(int dx, int dy) {
if (current != null) {
current.x += dx;
current.y += dy;
repaint();
}
}
The if (current != null) { ... } test will prevent your application from crashing if you press an arrow key before clicking on a piece, which it currently does.
You could, instead of translating the Polygon, translate the location, and use it for painting:
In keyPressed, replace current.translate to translate the location instead of the whole Polygon (you could override Piece#translate to call current.getLocation().translate for example).
In View#paintComponent, replace:
needle.translate(needle.getLocation().x, needle.getLocation().y);
with
gc.translate(needle.getLocation().x, needle.getLocation().y);
and add
gc.translate(-needle.getLocation().x, -needle.getLocation().y);
at the end of your for-loop.
This will translate the whole Graphics2D to paint a polygon, and revert it after.
I'm having some issues with my code.
I want to fix the background image to stay there fixed, meanwhile other components can move.
It's a simple a game where a circle avoid the squares but the istruction about the game will be added further.
Here's my code
import java.applet.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Line2D;
import java.net.URL;
import javax.swing.*;
public class Main extends Applet implements Runnable,KeyListener{
Thread r;
Image bg = null;
int a,b;
int x = 600;
int y = 400;
public void init(){
setSize(600,600);
try
{
MediaTracker tr = new MediaTracker (this);
bg = getImage
(new URL("file:D:/workspace/Game/bin/image.jpg")); //set image
tr.addImage(bg, 0);
} catch (Exception e) { System.out.println(e.toString());
}
}
public void start(){
if(r == null){
r = new Thread(this);
r.start();
}
}
public void paint(Graphics g){
g.drawImage(bg,0,0,this);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(20));
g2.draw(new Line2D.Float(0, 500, 600, 500));
g.fillRect(x, y, 20, 20);
}
public void pp(Graphics g){
}
public void run() {
Thread Th = Thread.currentThread();
while(r == Th) {
if(a < 600) {
a = a+10;
x = x-10;
repaint();
}else{
repaint();
a = 30;
x = 600;
}
try {
Thread.sleep(100);
} catch(InterruptedException e) { }
}
}
#Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
if you run the code, you'll see that the line and the background will be loaded a lot of time...
I'd like to make something similar to a cursor, ( I get no errors )
So basically I get the coordinates once I enter the applet, and based on them I have my image drawn.
Here's the code... Can you please tell me where I'm wrong ? Thanks
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
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.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class Z_applets extends Applet implements
KeyListener, MouseListener, MouseMotionListener {
int z = 100;
int t = 100;
// boolean gigel = true;
//----------------- Images
Image image;
//-----------------
//----------------- Mouse Coordinates
Point p = null;
int x;
int y;
//----------------------------------
Color color = Color.GREEN;
public void init() {
addKeyListener(this);
addMouseListener(this);
}
public void paint(Graphics g) {
setBackground(Color.BLACK);
g.setColor(color);
g.drawImage(image, x, y, this);
g.fillOval(z, t, 15, 15);
}
public void update(Graphics g) {
paint(g);
}
public void loadImage() {
//URL url = getClass().getResource("borat.jpg");
//image = getToolkit().getImage(url);
try {
URL url = new URL(getCodeBase(), "trollface.png");
System.out.println(getCodeBase());
image = ImageIO.read(url);
} catch (IOException e) {
System.out.println("error" + e.getMessage());
}
}
#Override
public void keyTyped(KeyEvent ke) {
}
#Override
public void keyPressed(KeyEvent ke) {
char option;
option = ke.getKeyChar();
switch (option) {
case 'w': {
t--;
repaint();
break;
}
case 's': {
t++;
repaint();
break;
}
case 'a': {
z--;
repaint();
break;
}
case 'd': {
z++;
repaint();
break;
}
case '1': {
color = Color.GREEN;
break;
}
case '2': {
color = Color.RED;
break;
}
case '3': {
color = Color.YELLOW;
break;
}
// case 'r':
// {
// loadImage();
// repaint();
// break;
// }
}
}
#Override
public void keyReleased(KeyEvent ke) {
}
#Override
public void mouseClicked(MouseEvent me) {
// p = me.getPoint();
// x = p.x;
// y = p.y;
// repaint();
}
#Override
public void mousePressed(MouseEvent me) {
}
#Override
public void mouseReleased(MouseEvent me) {
}
#Override
public void mouseEntered(MouseEvent me) {
// p=me.getPoint();
//-------Debug--------
System.out.println(p);
System.out.println(p.x);
System.out.println(p.y);
//----------------------
// x = p.x;
// y = p.y;
// repaint();
}
#Override
public void mouseExited(MouseEvent me) {
}
#Override
public void mouseDragged(MouseEvent me) {
}
#Override
public void mouseMoved(MouseEvent me) {
p = me.getPoint();
x = p.x;
y = p.y;
repaint();
}
}
Without knowing what problem you have exactly, I suppose the image isn't being moved.
I looks you don't register a MouseMotionListener so do that and implement the mouseMoved method.
I'm trying to make a game in Eclipse that runs on Windows 8 using type keys.
Whenever I run the app using extends Applet I just get a blank screen. I can change the color of the background but none of my images are showing. I can even play with the app and use my arrow keys to get the returns but I can't see anything on the screen. I'm not sure if I should extend Applet or JApplet.
Here's my code
package kiloboltgame;
import java.applet.Applet;
import java.awt.*;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.Graphics;
import java.net.URL;
public class StartingClass extends Applet implements Runnable, KeyListener {
private Robot robot;
private Image image, currentSprite, character, characterDown, characterJumped, background;
private Graphics second;
private URL base;
private static Background bg1, bg2;
#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
}
character = getImage(base, "data/character.png");
characterDown = getImage(base, "data/down.png");
characterJumped = getImage(base, "data/jumped.png");
currentSprite = character;
background = getImage(base, "data/background.png");
}
#Override
public void start() {
bg1 = new Background(0,0);
bg2 = new Background(2160, 0);
robot = new Robot();
Thread thread = new Thread(this);
thread.start();
}
#Override
public void stop() {
//super.stop();
}
#Override
public void destroy() {
//super.destroy();
}
#Override
public void run() {
while (true) {
robot.update();
if (robot.isJumped()){
currentSprite = characterJumped;
} else if (robot.isJumped() == false && robot.isDucked() == false){
currentSprite = character;
}
bg1.update();
bg2.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(background, bg1.getBgX(), bg1.getBgY(), this);
g.drawImage(background, bg2.getBgX(), bg2.getBgY(), this);
g.drawImage(currentSprite, 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:
currentSprite = characterDown;
if (robot.isJumped() == false){
robot.setDucked(true);
robot.setSpeedX(0);
}
break;
case KeyEvent.VK_LEFT:
robot.moveLeft();
robot.setMovingLeft(true);
break;
case KeyEvent.VK_RIGHT:
robot.moveRight();
robot.setMovingRight(true);
break;
case KeyEvent.VK_SPACE:
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:
currentSprite = character;
break;
case KeyEvent.VK_LEFT:
robot.stopLeft();
break;
case KeyEvent.VK_RIGHT:
robot.stopRight();
break;
case KeyEvent.VK_SPACE:
//System.out.println("Stop jumping");
break;
}
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public static Background getBg1(){
return bg1;
}
public static Background getBg2(){
return bg2;
}
}
A simple question with a perhaps not so simple solution. My code is supposed to show a triangle on a black background that can be moved around onscreen. Only nothing displays, just a white area that can't be right-clicked on. It does not work in either the appletviewer or an HTML document, and shows no syntax errors. What is wrong with my code?
import java.awt.*;
import java.applet.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.awt.event.*;
public class Shipmovementtest extends Applet implements Runnable,KeyListener{
Graphics2D g2d;
Ship ship1 = new Ship();
BufferedImage backbuffer;
AffineTransform identity = new AffineTransform();
Shape ship1shape;
Thread gameloop;
public void start()
{
gameloop = new Thread(this);
gameloop.start();
}
public void run()
{
Thread t = Thread.currentThread();
while(gameloop==t)
{
try
{
Thread.sleep(20);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
repaint();
}
}
public void stop()
{
gameloop = null;
}
public void init()
{
ship1shape = ship1.getShape();
backbuffer = new BufferedImage(640,480,BufferedImage.TYPE_INT_RGB);
g2d = backbuffer.createGraphics();
addKeyListener(this);
setFocusable(true);
requestFocusInWindow();
}
public void update(Graphics g)
{
g2d.setTransform(identity);
g2d.setPaint(Color.BLACK);
g2d.fillRect(0,0,getSize().width,getSize().height);
drawShip();
paint(g);
}
public void keyTyped(KeyEvent e){}
public void keyPressed(KeyEvent e)
{
int ke = e.getKeyCode();
switch(ke)
{
case KeyEvent.VK_LEFT:
ship1.setFaceAngle(ship1.getFaceAngle()-5);
break;
case KeyEvent.VK_RIGHT:
ship1.setFaceAngle(ship1.getFaceAngle()+5);
break;
case KeyEvent.VK_UP:
ship1.incX(-ship1.calcAngleMoveX(ship1.getFaceAngle())*ship1.velocity);
ship1.incY(-ship1.calcAngleMoveY(ship1.getFaceAngle())*ship1.velocity);
break;
case KeyEvent.VK_DOWN:
ship1.incX(ship1.calcAngleMoveX(ship1.getFaceAngle())*ship1.velocity);
ship1.incY(ship1.calcAngleMoveY(ship1.getFaceAngle())*ship1.velocity);
break;
}
}
public void paint(Graphics g)
{
g2d.drawImage(backbuffer,0,0,this);
}
public void keyReleased(KeyEvent e){}
public void drawShip()
{
g2d.setTransform(identity);
g2d.translate(ship1.getX(),ship1.getY());
g2d.rotate(Math.toRadians(ship1.getFaceAngle()));
g2d.setColor(ship1.getColor());
g2d.fill(ship1.getShape());
}
}
In the end of paint you need to actually draw the buffer to the real graphics g. Currently you are only painting in the buffer.
So correct code would be
public void paint(Graphics g)
{
g.drawImage(backbuffer,0,0,this);
}