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;
}
}
Related
So i am trying to move the ball using arrow keys and Key event ,but the ball doesn't move.If anyone can help i would gladly appreciate it ,and keep in mind that i am a beginner in java.Here is the code:
package prozor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.KeyEvent;
#SuppressWarnings("serial")
public class prozor extends JPanel {
public int x = 0;
public int y = 0;
public boolean up,down,left,right;
public int vx,vy;
public void update(){
vx=0;
vy=0;
if(up)vy=-5;
if(down)vy=5;
if(right)vy=-5;
if(left)vy=5;
}
public void keyPressed(KeyEvent e){
switch(e.getKeyCode()) {
case KeyEvent.VK_DOWN: down = true; break;
case KeyEvent.VK_UP: up = true; break;
case KeyEvent.VK_LEFT: left = true; break;
case KeyEvent.VK_RIGHT: right = true; break;
}
update();
}
public void moveBall() {
x +=vx;
y +=vy;
}
public void keyReleased(KeyEvent e){
switch(e.getKeyCode()) {
case KeyEvent.VK_DOWN: down = false; break;
case KeyEvent.VK_UP: up = false; break;
case KeyEvent.VK_LEFT: left = false; break;
case KeyEvent.VK_RIGHT: right = false; break;
}
update();
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(x, y, 20, 20);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Sample Frame");
prozor game = new prozor();
frame.add(game);
frame.setSize(300, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.moveBall();
game.repaint();
Thread.sleep(10);
}
}
}
I made a ping pong game in Java but the paddles doesn't work, and I can't figure out the problem.
Main class: in the main class I give the thread and run the program:
package pingpong;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class PingPong extends JFrame {
int Gwidth=400,Gheight=300;
Dimension screenSize = new Dimension(Gwidth,Gheight);
//double Buffering
Image dbImage;
Graphics dbg;
//ball objects
static Ball b = new Ball(193,143);
//constructor
public PingPong() {
this.setTitle("ping pong Game");
this.setResizable(false);
this.setSize(screenSize);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBackground(Color.black);
this.setVisible(true);
}
#Override
public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
draw(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void draw(Graphics g) {
b.draw(g);
b.p1.draw(g);
b.p2.draw(g);
g.setColor(Color.white);
g.drawString(""+b.p1Score,15,50);
g.drawString(""+b.p2Score,370,50);
repaint();
}
//event listining class
public class AL extends KeyAdapter { //key buildings
#Override
public void keyPressed(KeyEvent e) {
b.p1.keyPressed( e);
b.p2.keyPressed( e);
}
public void keyRealesed(KeyEvent e){
b.p1.keyReleased( e);
b.p2.keyReleased( e);
}
}
public static void main(String[] args) {
PingPong pp = new PingPong();
//create and start threads
Thread ball=new Thread(b);
ball.start();
Thread p1=new Thread(b.p1);
Thread p2= new Thread(b.p2);
p1.start();
p2.start();
}
}
this is my ball class:
package pingpong;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Random;
public class Ball implements Runnable{
//global variables
int x,y,XDir,YDir;
//score
int p1Score,p2Score;
Paddle p1=new Paddle(15 , 140, 1);
Paddle p2=new Paddle(370, 140 ,2 );
Rectangle ball;
public Ball(int x,int y){
p1Score=p2Score=0;
this.x=x;
this.y=y;
//randomly moving the ball
Random r=new Random();
int rDir = r.nextInt(1);
if (rDir == 0) {
rDir--;
}setXDir(rDir);
int yrDir = r.nextInt(1);
if (yrDir == 0) {
yrDir--;
}setYDir(yrDir);
//create 'ball'
ball = new Rectangle(this.x, this.y,7, 7);
}
public void collision(){
if(ball.intersects(p1.paddle)){
setXDir(+1);}
if(ball.intersects(p2.paddle)){
setXDir(-1);}
}
public void draw(Graphics g){
g.setColor(Color.cyan);
g.fillRect(ball.x,ball.y,ball.width,ball.height);
}
public void move(){
collision();
ball.x +=XDir;
ball.y +=YDir;
//bounce the ball when edge is detected
if(ball.x<0){
setXDir(+1);
//add to score
p1Score++; //?
}
if(ball.x>=385){
setXDir(-1);
//add to score
p2Score++; //?
}
if(ball.y<=15)
setYDir(+1);
if(ball.y>=270)
setYDir(-1);
}
public void setXDir(int xdir){
XDir=xdir;
}
public void setYDir(int ydir){
YDir=ydir;
}
public void run(){
try{
while(true){
move();
Thread.sleep(4);
}
}catch(Exception e) {System.out.println("sorry"+e.getMessage());}
}
}
and there is my paddle class :
package pingpong;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
public class Paddle implements Runnable {
int x, y, yDir, id;
Rectangle paddle;
public Paddle(int x, int y, int id) {
this.x = x;
this.y = y;
this.id = id;
paddle = new Rectangle(x, y, 15, 50);
}
public void keyPressed(KeyEvent e) {
switch (id) {
default:
System.out.println("please enter a valid id");
break;
case 1:
if (e.getKeyCode() == e.VK_UP) {
setYDir(-1);
}
if (e.getKeyCode() == e.VK_DOWN) {
setYDir(+1);
}
break;
case 2:
if (e.getKeyCode() == e.VK_W) {
setYDir(-1);
}
if (e.getKeyCode() == e.VK_S) {
setYDir(+1);
}
break;
}
}
public void keyReleased(KeyEvent e) {
switch (id) {
default:
System.out.println("please enter a valid id");
break;
case 1:
if (e.getKeyCode() == e.VK_UP) {
setYDir(0);
}
if (e.getKeyCode() == e.VK_DOWN) {
setYDir(0);
}
break;
case 2:
if (e.getKeyCode() == e.VK_W) {
setYDir(0);
}
if (e.getKeyCode() == e.VK_S) {
setYDir(0);
}
break;
}
}
public void draw(Graphics g) {
switch (id) {
default:
System.out.println("please enter a valid id");
break;
case 2:
g.setColor(Color.YELLOW);
//draw paddle #1
g.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
break;
case 1:
g.setColor(Color.white);
// draw paddle #2
g.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
break;
}
}
public void setYDir(int ydir) {
yDir = ydir;
}
public void move() {
paddle.x += yDir;
if (paddle.y <= 15) {
paddle.y = 15;
}
if (paddle.y >= 250) {
paddle.y = 250;
}
}
#Override
public void run() {
try {
while (true) {
move();
Thread.sleep(6);
}
} catch (Exception e) {
System.out.println("try again" + e.getMessage());
}
}
}
I personally think I have a problem in the paddle but I can't figure it out.
If you're moving your paddle in Y axis (inside move, this looks wrong:
paddle.x += yDir;
Should be
paddle.y += yDir;
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.
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.
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);
}