2D Top-Down Java (1.8) Game from Scratch(nothing) - java

So, first of all this is my first time posting and I am trying to make a top-down game with java(1.8) and IntelliJ, nothing else. I have all of my code good and done(for making the sprite show up), I test it and it keeps giving me error messages saying that certain parts are invalid. It is supposed to display an image (character) on the screen in the top right here is all code and please keep in mind that I do not have this fully finished:
Game.java
package main;
import main$entities.Player;
import main$gfx.ImageLoader;
import main$gfx.SpriteSheet;
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.lang.*;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 700, HEIGHT = 400, SCALE = 1;
public static boolean running = false;
public Thread gameThread;
private BufferedImage spriteSheet;
private Player player;
public void init(){
ImageLoader loader = new ImageLoader();
spriteSheet = loader.load("./spritesheet.png");
SpriteSheet ss = new SpriteSheet(spriteSheet);
player = new Player(0, 0, ss);
}
public synchronized void start(){
if(running)return;
running = true;
gameThread = new Thread(this);
gameThread.start();
}
public synchronized void stop(){
if(!running)return;
running = false;
try {
gameThread.join();
} catch (InterruptedException e) {e.printStackTrace();}
}
public void run(){
long lastTime = System.nanoTime();
final double amountOfTicks = 60D;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
while(running){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
if(delta >= 1){
tick();
delta--;
}
render();
}
stop();
}
public void tick(){
player.tick();
}
public void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
// Render Here
g.fillRect(0, 0, WIDTH * SCALE, HEIGHT * SCALE);
player.render(g);
// End Render
g.dispose();
bs.show();
}
public static void main(String[] args){
Game game = new Game();
game.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
JFrame frame = new JFrame("Tile RPG");
frame.setSize(WIDTH *SCALE, HEIGHT * SCALE);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(game);
frame.setVisible(true);
game.start();
}
}
ImageLoader.java
package main$gfx;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class ImageLoader {
public BufferedImage load(String path){
try {
return ImageIO.read(getClass().getResource(path));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
SpriteSheet.java
package main$gfx;
import java.awt.image.BufferedImage;
public class SpriteSheet {
private BufferedImage sheet;
public SpriteSheet(BufferedImage sheet){
this.sheet = sheet;
}
public BufferedImage crop(int col, int row, int w, int h){
return sheet.getSubimage(col * 16, row * 16, w, h);
}
}
Player.java
package main$entities;
import main.Game;
import main$gfx.SpriteSheet;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Player implements KeyListener{
private int x, y;
private SpriteSheet ss;
private boolean up = false, dn = false, lt = false, rt = false;
private final int SPEED = 3;
public Player(int x, int y, SpriteSheet ss){
this.x = x;
this.y = y;
this.ss = ss;
}
public void tick(){
if(up){
y -= SPEED;
}
if(dn){
y += SPEED;
}
if(lt){
x -= SPEED;
}
if(rt){
x += SPEED;
}
}
public void render(Graphics g){
g.drawImage(ss.crop(0 ,0, 16, 16), x, y, 16 * Game.SCALE, 16 * Game.SCALE, null);
}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
}
The error messages(It gives me multiple messages, each time is different // = what is on that line, so you don't have to find it by counting, your welcome):
First time I run the Game.java:
Exception in thread "Thread-2" java.lang.NullPointerException
at main.Game.tick(Game.java:64) // player.tick();
at main.Game.run(Game.java:56) // tick();
at java.lang.Thread.run(Thread.java:745) // this is in the JDK itself
Process finished with exit code 0
Second(and all that proceed) time I run the Game.java:
Exception in thread "Thread-2" java.lang.NullPointerException
at main.Game.render(Game.java:77) // player.render(g);
at main.Game.run(Game.java:59) // render();
at java.lang.Thread.run(Thread.java:745) // this is in the JDK itself
Process finished with exit code 0

That game.start(); takes all the responsibility. Your Game class is not extending a Thread, the thread itself will start automatically right after you instantiate your game's class, since the thread is created inside the game class.
So remove :
game.start();
Btw you fall on trap :
public static final int WIDTH = 700, HEIGHT = 400;
won't work, because those fields hide another fields, why? because
WIDTH & HEIGHT is preserved arguments for
.fillRect(...);

It's because you never call the init() method and, therefore the player and the spriteheet never gets created
You can add a constructor to the Game class like this:
public Game() {
init();
}
Or you can add the following line in the main method:
public static void main(String[] args){
Game game = new Game();
game.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
JFrame frame = new JFrame("Tile RPG");
frame.setSize(WIDTH *SCALE, HEIGHT * SCALE);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(game);
frame.setVisible(true);
// Add this line
game.init();
game.start();
}
}
But I prefer the first way

Related

Created a game where the Frame's width is accurate after I run it but the height never updates

I'm learning to make games using a a tutorial on youtube. Everything seems fine except when I run the program. A frame shows up with the accurate width I want but the height looks like it sets to a default no matter what value I give it.
package ca.vanzeben.game;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 160;
public static final int Height = WIDTH/ 12*9;
public static final int SCALE = 3; // able to move screen
public static final String NAME = "Juego";
private JFrame frame;
public boolean running = false;
public int tickCount = 0;
private BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();
public Game() { //game constructor
setMinimumSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE));
setMaximumSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE));
setPreferredSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE));
frame = new JFrame(NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // closes game completely
frame.setLayout(new BorderLayout());
frame.add(this,BorderLayout.CENTER); //adds canvas to JFrame and centers it
frame.pack();//keeps everything sized correctly
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public synchronized void start() {//so u can start from the applet
running = true;
new Thread(this).start();
}
public synchronized void stop(){
running = false;
}
public void run() {
long lastTime = System.nanoTime();
double nsPerTick = 1000000000.0/60; //nanoseconds per tick or per update
int ticks = 0;
int frames = 0;
long lastTimer = System.currentTimeMillis();
double delta = 0.0; //how many unprocessed nano seconds
while(running){
long now = System.nanoTime();
delta+=(now-lastTime)/nsPerTick;
lastTime = now;
boolean shouldRender = true;
while(delta>=1){
ticks++;
tick();
delta -= 1;
shouldRender = true;
}
try{
Thread.sleep(2);
}catch(InterruptedException e){
e.printStackTrace();
}
if(shouldRender){
frames++;
render();
}
if(System.currentTimeMillis()-lastTimer>=1000){
lastTimer += 1000;
System.out.println(frames + " frames " + ticks + " ticks ");
frames = 0;
ticks = 0;
}
}
}
public void tick(){ //updates the game, updates the logic
tickCount++;
for(int i =0;i<pixels.length;i++){
pixels[i] = i + tickCount;
}
}
public void render(){ //prints out ^
BufferStrategy bs = getBufferStrategy();
if(bs == null){
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
g.setColor(Color.BLACK);
g.drawRect(0, 0, getWidth(), getHeight());
g.dispose();
bs.show();
}
public static void main(String[] args){
new Game().start();
}
}
You defined Height and used HEIGHT. Change it to:
public static final int HEIGHT = WIDTH / 12 * 9;
This is how it looked like to me:
Before:
After:

Java - NullPointerException with graphics [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I was trying to draw a simple rectangular on a JFrame but when I tried to draw it it gave me a NullPointerException. I could not find the problem because it is one of my codes that I already used. The object that is Null is a Graphics object that I got from the super class. Can someone help me with this?
Error:
Exception in thread "Thread-2" java.lang.NullPointerException
at com.daansander.game.Game.render(Game.java:83)
at com.daansander.game.Game.run(Game.java:76)
at java.lang.Thread.run(Thread.java:745)
Full Code:
package com.daansander.game;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferStrategy;
/**
* Created by Daan on 12-9-2015.
*/
public class Game extends Canvas implements Runnable {
public static final int WIDTH = 500;
public static final int HEIGHT = WIDTH / 12 * 9;
public static final int SCALE = 2;
public static final String NAME = "2DGame";
private JFrame frame;
private volatile boolean running;
public Game() {
setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
frame = new JFrame(NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(this, BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
new Game().start();
}
public synchronized void start() {
running = true;
new Thread(this).start();
}
public synchronized void stop() {
}
#Override
public void run() {
long lastTime = System.currentTimeMillis();
long current;
long delta = 0;
int frames = 0;
// int ticks = 0;
while (running) {
current = System.currentTimeMillis();
delta += current - lastTime;
lastTime = current;
frames++;
if (delta > 1000) {
delta -= 1000;
System.out.println("FRAMES " + frames);
frames = 0;
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
render();
}
}
public void render() {
BufferStrategy bs = getBufferStrategy();
Graphics g = bs.getDrawGraphics(); // <----- Line of error
// g.setColor(Color.black);
// g.drawRect(0, 0, 5, 5);
//
// g.dispose();
// bs.show();
}
public void tick() {
}
public void init() {
}
}
getBufferStrategy() is returning null. As fabian linked to above:
public BufferStrategy getBufferStrategy()
Returns the BufferStrategy used by this component. This method will return null if a BufferStrategy has not yet been created or has been disposed.
You need to create a BufferStrategy first.

Cant read input file-Java

So I am following a series of tutorials to learn how to make a game in java(i am still pretty new), and i think i followed his code exactly, but it still prints the stack trace when i run it. Here is my code...
Game.java
package com.game.src.main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable{
private static final long serialVersionUID = 1L;
public static final int WIDTH = 320;
public static final int HEIGHT = WIDTH / 12 * 9;
public static final int SCALE = 2;
public final String TITLE = "2D Space Game";
private JFrame frame = new JFrame(TITLE);
private boolean running = false;
private Thread thread;
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
private BufferedImage spriteSheet = null;
private BufferedImage player;
public void init(){
BufferedImageLoader loader = new BufferedImageLoader();
spriteSheet = loader.loadImage("/sprite_sheet.png");
SpriteSheet ss = new SpriteSheet(spriteSheet);
player = ss.grabImage(1, 1, 32, 32);
}
public void run(){
long lastTime = System.nanoTime();
final double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long now = 0;
int updates = 0, frames = 0;
long timer = System.currentTimeMillis();
init();
while(running){
now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
if(delta >= 1){
tick();
updates++;
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000){
timer += 1000;
frame.setTitle("2-D Space Game || Updates: " + updates + ", FPS: " + frames);
frames = 0;
updates = 0;
}
}
stop();
}
private void tick(){
}
private void render(){
BufferStrategy bs = this.getBufferStrategy();
try {
Thread.sleep(2);
} catch (InterruptedException e){
e.printStackTrace();
}
if(bs == null){
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
/////////////////////////////////////
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
g.drawImage(player, 100, 100, this);
/////////////////////////////////////
g.dispose();
bs.show();
}
private synchronized void start(){
if(running) return;
running = true;
thread = new Thread(this);
thread.start();
}
private synchronized void stop(){
if(!running) return;
try{
thread.join();
}catch(InterruptedException e){
e.printStackTrace();
}
System.exit(1);
}
public static void main(String args[]){
Game game = new Game();
game.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setResizable(false);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
game.start();
}
}
SpriteSheet.java
package com.game.src.main;
import java.awt.image.BufferedImage;
public class SpriteSheet {
private BufferedImage image;
public SpriteSheet(BufferedImage image){
this.image = image;
}
public BufferedImage grabImage(int col, int row, int width, int height){
return image.getSubimage((col * 32) - 32, (row * 32) - 32, width, height);
}
}
BufferedImageLoader.java
package com.game.src.main;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class BufferedImageLoader {
private BufferedImage image;
public BufferedImage loadImage(String path){
try {
image = ImageIO.read(getClass().getResource(path));
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return image;
}
}
Now here is the stacktrace that shows up:
Exception in thread "Thread-0" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1388)
at com.game.src.main.BufferedImageLoader.loadImage(BufferedImageLoader.java:13)
at com.game.src.main.Game.init(Game.java:30)
at com.game.src.main.Game.run(Game.java:45)
at java.lang.Thread.run(Thread.java:745)
Can anyone help?
BTW:
sprite_sheet.png does exist
Ok I figured it out. My sprite_sheet.png was in my "res" folder, and i needed to add it to the build path
The issue here is with the way you are addressing your png, and that the location you are specifying is not in your build path, or where you expect it to be. If you provide me the pwdon your location I will update with actual path you should use
You either need to provide the full path
/home/me/myprogram/sprite_sheet.png
or use relative path
./sprite_sheet.png
Your program is looking for the file in the root directory /
You need to provide a full path relative to your CLASSPATH, or a relative path relative to the current class's package.

Illegal State Exception With Creating a Buffer Stragety

Hi i was coding and this came up
Exception in thread "Thread-2" java.lang.IllegalStateException: Component must have a valid peer
at java.awt.Component$FlipBufferStrategy.createBuffers(Unknown Source)
at java.awt.Component$FlipBufferStrategy.(Unknown Source)
at java.awt.Component$FlipSubRegionBufferStrategy.(Unknown Source)
at java.awt.Component.createBufferStrategy(Unknown Source)
at java.awt.Canvas.createBufferStrategy(Unknown Source)
at java.awt.Component.createBufferStrategy(Unknown Source)
at java.awt.Canvas.createBufferStrategy(Unknown Source)
at spoderman.game.Main.render(Main.java:79)
at spoderman.game.Main.run(Main.java:64)
at java.lang.Thread.run(Unknown Source)
Here is the Code
i pinpointed the error which was createBufferStrategy(3);
Please Help!!!
package spoderman.game;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class Main extends Canvas implements Runnable{
private static final long serialVersionUID = 8496269517740959648L;
public static JFrame frame = new JFrame();
public static Thread gameThread = new Thread();
public static final int WIDTH = 720, HEIGHT = 240, SCALE = 2;
public static String title = "The Adventures of Spoderman";
public static boolean isrunning = false;
public synchronized void start(){
if(isrunning)return;
isrunning = true;
gameThread = new Thread(this);
gameThread.start();
}
public synchronized void stop(){
if(!isrunning)return;
try {
gameThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
isrunning = false;
}
public void run() {
long lastTime = System.currentTimeMillis();
final double amountOfTicks = 60D;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
while(isrunning){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
if(delta >= 1){
tick();
delta--;
}
render();
}
stop();
}
public void tick(){
}
public void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//ALL THAT IS RENDERED
g.fillRect(0, 0, WIDTH, HEIGHT);
//ALL THAT IS RENDERED
g.dispose();
bs.show();
}
public static void main (String [] args){
Main main = new Main();
main.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
main.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
main.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
main.start();
JFrame();
}
public static void JFrame(){
frame.setTitle(title);
frame.setSize(WIDTH * SCALE, HEIGHT * SCALE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Try this on the Jframe
public static void JFrame(Main main) {// <---get de arg game.
frame.add(main);// add the main(canvas).
frame.setTitle(title);
frame.setSize(WIDTH * SCALE, HEIGHT * SCALE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
edit on the main
public static void main(String[] args) {
Main main = new Main();
main.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
main.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
main.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
JFrame(main);// get the Frame working and pas the main
main.start();// start main
}
and last just change the size
// g.fillRect(0, 0, WIDTH, HEIGHT);//The old one
g.fillRect(0, 0, WIDTH * SCALE, HEIGHT * SCALE);// change the size
full code
package testCodeDel;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class Main extends Canvas implements Runnable {
private static final long serialVersionUID = 8496269517740959648L;
public static JFrame frame = new JFrame();
public static Thread gameThread = new Thread();
public static final int WIDTH = 720, HEIGHT = 240, SCALE = 2;
public static String title = "The Adventures of Spoderman";
public static boolean isrunning = false;
public synchronized void start() {
if (isrunning)
return;
isrunning = true;
gameThread = new Thread(this);
gameThread.start();
}
public synchronized void stop() {
if (!isrunning)
return;
try {
gameThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
isrunning = false;
}
public void run() {
long lastTime = System.currentTimeMillis();
final double amountOfTicks = 60D;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
while (isrunning) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
if (delta >= 1) {
tick();
delta--;
}
render();
}
stop();
}
public void tick() {
}
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
// ALL THAT IS RENDERED
// g.fillRect(0, 0, WIDTH, HEIGHT);//The old one
g.fillRect(0, 0, WIDTH * SCALE, HEIGHT * SCALE);// change the size
// ALL THAT IS RENDERED
g.dispose();
bs.show();
}
public static void main(String[] args) {
Main main = new Main();
main.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
main.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
main.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
JFrame(main);// get the Frame working pas de main
main.start();// start main
}
public static void JFrame(Main main) {// <---get de arg main.
frame.add(main);// add the main(canvas).
frame.setTitle(title);
frame.setSize(WIDTH * SCALE, HEIGHT * SCALE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Or just delete JFrame() and do this on your main
public static void main(String[] args) {
Main main = new Main();
main.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
main.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
main.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
//JFrame(main);// get the Frame working pas de main
JFrame frame = new JFrame();
frame.add(main);// add the main(canvas).
frame.setTitle(title);
frame.setSize(WIDTH * SCALE, HEIGHT * SCALE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
main.start();// start main
}

" The constructor Window(int, int, String, Game) is undefined "

I am having issues with a 2D platform game. I get an error that reads what the title of the question said. Here are my Game.java and Window.java files. Please tell me what I should do.
I've tried a ton of things and I just don't know where to go or what to do. Thanks in advance :)
Window.java
package com.sam.platform.window;
import java.awt.Dimension;
import javax.swing.JFrame;
public class Window
{
public Window(int w, int h, String title, Game game)
{
game.setPreferredSize(new Dimension(w, h));
game.setMaximumSize(new Dimension(w, h));
game.setMinimumSize(new Dimension(w, h));
JFrame frame = new JFrame(title);
frame.add(game);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
game.start();
}
}
Game.java
package com.sam.platform.window;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Window;
import java.awt.image.BufferStrategy;
import com.sam.platform.framework.ObjectId;
public class Game extends Canvas implements Runnable
{
private static final long serialVersionUID = -414187095722102896L;
private boolean running = false;
private Thread thread;
public static int WIDTH, HEIGHT;
//Object
Handler handler;
private void init()
{
WIDTH = getWidth();
HEIGHT = getHeight();
handler = new Handler();
handler.addObject(new Player(100, 100, handler, ObjectId.Player));
handler.createLevel();
this.addKeyListener(new KeyInput(handler));
}
public synchronized void start(){
if(running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
public void run()
{
init();
this.requestFocus();
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int updates = 0;
int frames = 0;
while(running){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1){
tick();
updates++;
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000){
timer += 1000;
System.out.println("FPS:" + frames + " TICKS: " + updates);
frames = 0;
updates = 0;
}
}
}
private void tick()
{
handler.tick();
}
private void render()
{
BufferStrategy bs = this.getBufferStrategy();
if(bs == null)
{
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
//////////////////////////////////
//Draw Here
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
handler.render(g);
//////////////////////////////////
g.dispose();
bs.show();
}
public static void main(String args[]){
new Window(900, 900, "Hop", new Game()); //error is here "The constructor Window(int, int, String, Game) is undefined"
}
}
Your Window class is fine, but the class you're importing in Game is java.awt.Window.
You could solve this by doing new com.sam.platform.window.Window(...), but I would advise against it, it will just confuse you.
Rename the class to something like GameWindow instead.
You have two different classes called Window in use in your Game class. One is com.sam.platform.window.Window. The other is java.awt.Window. Since you have imported java.awt.Window into your Game class, it thinks you are trying to instantiate one of those (not your own Window class).
I suggest renaming you own class to disambiguate (and avoid confusion) to, say, GameWindow.

Categories

Resources