Slick: can't load image in update loop - java

As you can see from the code below, I am trying to import "someimage.png". This is so in the render loop, I have the right image. I put the second line of code. Is this possible? If not what is an alternative. Thanks in advance.
public void update(GameContainer container, int delta) {
//if statement
Image x = new Image("someimage.png");
}
public void render() {
//draw image x
}
There is an "unhanded exception type SlickException".

It looks like the variable "x" is local to the update() function. If your render() function tries to call "x", maybe it's a different variable?

Check out this Slick tutorial here, it shows a basic game setup with image loading. Basically, you want the Images to be member variables of your game class, their values set in the init method, and the render method to draw the pictures. Although this setup will work fine for very simple games, you are probably better off using objects to represent the different things in your game. I hope this helps.

Related

NullpointerException when I use my own multiple method to paint an image

I am trying to paint multiple images depending on whether a Boolean is true or not. But instead when the boolean becomes true or not, I get a NullPointerException involving anything with my methods. (comment in code specifically pointing to where), and I'm 99% sure its because of the graphics and it's null.
Basically I'm also asking how to fix this and how to properly paint images using my own methods in one class. I know how to do it with each image in one class, but I have WAY more than just 2 images, I think I have almost 100, so i don't want to make 100 classes (:|). Here's my code:
List of images class:
public class Images{
public static Toolkit tk = Toolkit.getDefaultToolkit();
public static final Image Image1 = tk.getImage("src/images/image1.png"), Image2 = tk.getImage("src/images/image2.png");
public ImageObserver observer = null; //i just did this for no reason
public static Graphics g = Main.graphics;
public void paintImage1(Graphics g){
Images.g = g;
g.drawImage(Image1, 10, 10, observer); //NullPointerException points here, even if I replace 'pbserver' with null
}
public void paintImage2(Graphics g){
Images.g = g;
g.drawImage(Image2, 10, 10, observer); //strangely, it doesn't point here
}
}
Then, I cite and use it in my class that paints the image with my boolean like so:
public class PaintHandler{
public static Graphics graphics = Images.g;
public void PaintImages(boolean upheld){
if (upheld){
Images.paintImage1(graphics);//NullPionterException points here
}
else if (!upheld){
Images.paintImage2(graphics);//doesn't point here for some reason
}
}
}
The exception also points to the keybindings methods I use to make upheld true or not, another thing that is strange.
Like before, I don't want to make a class for every single image, I would prefer if they were all in one class. Additionally, when I try to use getGraphics() on the JFrame I'm using, I do through this GIGANTIC loop between making thing statics and not being able to apply static terms to non-static context, such as making a variable static, but then it says can't be used in static context, but then when you don't make it static a different variable says change it back to static, you don't make that static, and you go through this huge loop between making it static and changing to not be static (sorry for long explanation, was trying to be specific).
" when I try to use getGraphics() on the JFrame im using" - DON'T, this is not how custom is painting is done in Swing. getGraphics will, at best, return a snap shot of the last paint cycle and anything painted to it will be painted over on the next paint cycle and at worst, will return null.
Take a look at Painting in AWT and Swing and Performing Custom Painting for dore details about how painting works in Swing and how you should work with it...
Instead, create your self a custom component, extending from something like JPanel and use it's paintComponent to paint your images.
Normally, content stored in the src will be made available your application as embedded resources (this will depend on your IDE and build system), but generally speaking, you should not access any resource with the path containing src, this should be an immediate read flag for potential issues.
In this case you should be using Class#getResource to load the resource...
public class Images{
public static final Image Image1 = tk.getImage(Images.class.getResource("/images/image1.png"));
for example.
I would discourage you from using Toolkit.getImage as it will use a background thread to load the image and doesn't throw any kind of exception if the image wasn't loaded
Instead considering using ImageIO.read, see Reading/Loading an Image for more details
Like before, I don't want to make a class for every single image, I
would prefer if they were all in one class. Additionally, when I try
to use getGraphics() on the JFrame I'm using, I do through this
GIGANTIC loop between making thing statics and not being able to apply
static terms to non-static context, such as making a variable static,
but then it says can't be used in static context, but then when you
don't make it static a different variable says change it back to
static, you don't make that static, and you go through this huge loop
between making it static and changing to not be static (sorry for long
explanation, was trying to be specific).
Your images can be stored wherever you like, maybe in a Map of some kind. But they must be painted within a valid context, ie a component's paint method. You can paint as many images you want within in single component or spread them out if your prefer, that's tp up...
The issue with static is probably because you're ...
Still in the main method, which is static and/or
Trying to references (non-static) variables in other classes to which you've not created an instance to.
Only a runnable example will highlight which (if not both)

libGDX - how to remove existing spritebatch on screen?

So I've been looking through and experimenting some stuff but can't quite get how to remove pre-existing spriteBatch on screen.
so basically
I have initiated
batcher.begin();
(blah blah blah)
AssetLoader.font.draw(batcher, "Hey guys", x, y);
something like this...
now I wish to delete/remove/undraw this thing on screen...
how do I do that without using if statement because.. if I start using If statements everything is going to get sooo messy.
Thanks so much!
Its generally accepted practice in an OpenGL application to clear the screen every time and re-draw the entire screen.
So, to "erase" something, you just stop drawing it.
boolean wantToSeeThis = true;
...
void render() {
batcher.begin();
(blah blah blah)
if (wantToSeeThis) {
AssetLoader.font.draw(batcher, "Hey guys", x, y);
}
}
void hideIt() {
wantToSeeThis = false;
}
It is a bit unclear what you are asking. By default your screen gets cleared every frame with this line in the Render method.
gl.glClear( GL20.GL_COLOR_BUFFER_BIT );
Then obviously we need statements of when we want to draw things. If you code your whole program in a single class this obviously gets messy quick. But Java is OOP which means you can add a classes with there own Draw/Render method and there own statements as to when they should be drawn. I suggest you start learning the basics of OOP.

How to get my JPanels graphics object? [duplicate]

This question already has answers here:
How do i get a graphics object in Java?
(2 answers)
Closed 9 years ago.
Im making a basic space invaders game. I got all the resources from the LWJGL .zip file (Im not using LWJGL librarys to create my game, just got the pictures, etc. from it.) Anyway, whenever i press "space" on my keyboard, my KeyListener creates a new bullet that my ship fires. However, i dont know how to draw the bullets image, since my KeyListener doesnt pass a graphics object, and you need one to draw a image. The code thats causing the problem is the "drawImage" method in the "Shot" constructor. Heres my code:
public class KeyTyped{
public void keyESC(){
Screen.isRunning = false;
}
public void keyLEFT() {
Screen.shipPosX -= 10;
}
public void keyRIGHT() {
Screen.shipPosX += 10;
}
//This is automatically called from my KeyListener whenever i
//press the spacebar
public void keySPACE(){
if(!spacePressed){
ShotHandler.scheduleNewShot();
}else{
return;
}
}
}
public class ShotHandler {
public static int shotX = Screen.shipPosX;
public static int shotY = Screen.shipPosY + 25;
public static void scheduleNewShot() {
//All this does is set a boolean to 'false', not allowing you to fire any more shots until a second has passed.
new ShotScheduler(1);
new Shot(25);
}
}
public class Shot extends ShotHandler{
public Shot(int par1){
//This is my own method to draw a image. The first parameter is the graphics object that i need to draw.
GUI.drawImage(*????????*, "res/spaceinvaders/shot.gif", ShotHandler.shotX, ShotHandler.shotY);
}
//Dont worry about this, i was just testing something
for(int i = 0; i <= par1; i++){
ShotHandler.shotY++;
}
}
}
Thanks guys! Any help will be appreciated!
(This is a re-post because the last time i posted this, i didnt get a sufficient answer, at least for my skill level)
Start by taking a look at
Painting in AWT and Swing
Performing Custom Painting
You may also find Concurrency in Swing of some usefulness.
The basic gist is you should have some kind of model which describes the state of the game play at any moment in time. This model is updated outside the content of the Event Dispatching Thread, normally in some kind of background thread, where the time it takes to perform the updates doesn't effect the ability for Swing to continue running and remain responsive to the user.
You will need to override the JPanel's paintComponent method. In here, you would paint the model state to the screen.
There are a bunch of other techniques which could be discussed, but lets get this started
Examples...
Java Bouncing Ball
Drawing 2 Balls to move in different direction on Java but one disappeared
Multiple bouncing balls thread issue
I am trying to make ball gradually move
Java ball object doesn't bounce off of drawn rectangles like it's supposed to.
https://stackoverflow.com/questions/15858623/how-to-use-a-swing-timer-to-animate/15859932#15859932
the images are not loading
Swing animation running extremely slow
How to make line animation smoother?

Libgdx ParticleEffect: There are no errors, but nothing is drawn

Why doesn't this code work. There are no errors, but nothing is drawn.
The render method contains:
effect = new ParticleEffect();
effect.setPosition(200, 200);
effect.start();
float delta = Gdx.graphics.getDeltaTime();
GL10 gl = Gdx.app.getGraphics().getGL10();
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
spriteBatch.begin();
effect.draw(spriteBatch, delta);
spriteBatch.end();
If you are creating a new effect every frame, it will never move or do anything, since it will be reset each frame. You should create the effect outside your loop.
I don't know how the particleeffect will be with no setup. So you should also try adding a texture and set it's preferences.
I think only creating constructor for the ParticleEffect does not suffice, so you have to load particle effect file using effect object you have created in the following manner. Also you have to take this thing out of the loop.
effect.load(Gdx.files.internal("data/yellow_particle"),
Gdx.files.internal("data"));
Run once:
effect = new ParticleEffect();
effect.load(Gdx.files.internal("path/to/your/particle.p", "directory/with/your/particle/png"));
effect.setPosition(200, 200);
effect.start();
Run in render:
spriteBatch.begin();
effect.draw(spriteBatch, delta);
spriteBatch.end();
And in dispose:
effect.dispose();
Particle.png can be copied from libgdx sources for example:
https://github.com/libgdx/libgdx/blob/master/extensions/gdx-tools/assets/particle.png
And watch again the video tutorial - you are messing and missing many things:
http://www.youtube.com/watch?v=LCLa-rgR_MA
The tutorial itself covers less things, than video, but pasting here for hope it will be updated:
https://github.com/libgdx/libgdx/wiki/2d-particle-effects
Make the particle-effects in your class's constructor. Dont make particle-effects objects every time in your render method. Thats why, your particle effects are initializing every time, and you cant see anything.

Design decision : Adding new arguments to a method V/S creating an instance variable

Lets suppose we have a class Shape which has a method rotate(int velocity). This method makes a shape rotate with a speed of velocity(the parameter passed to rotate). This method has been called in a project, say at 100 places.
But now a new requirement comes, that the rotate functionality will also depend on the color of the shape, i.e. if the color is blue then the velocity should be decreased by 1, else no change should be made.
One solution to this problem would be to change the rotate(int velocity) method to rotate(int velocity, Color color), then add an if statement inside rotate method to check for the color, and make a change in 100 calls of rotate.
E.g.
shape.rotate(50, blue) ;
Inside the rotate method,
void rotate(int velocity, Color color) {
if(color == blue)
--velocity ;
}
Another solution would be to make color as an instance variable of the shape object, and then without adding a new argument to the rotate method, simply set the color before calling it, and squeeze the if check inside the rotate method.
E.g.
shape.setColor(blue) ;
shape.rotate(50) ;
Inside the rotate method,
void rotate(int velocity) {
if(this.color == blue)
--velocity ;
}
Yet another solution would be to overload the rotate method and create a new method named rotate(int velocity, Color color) and use it in the new calls. This would leave the existing code which uses rotate(int velocity) unchanged.
Which of these would be the best possible solution? Or, does there exist a better solution? If yes, then what could it be?
Regards
I'd say there are a couple of questions you need to ask yourself.
Do you care about the color outside of the rotate method? If yes, make it an instance variable; if no, pass it to the rotate method.
Are you likely to care about the color outside of the rotate method further down the line? If yes, make it an instance variable; if no, pass it to the rotate method.
Are you always going to care about the color when calling the rotate method? If yes, make it an argument (to force them to set the color when rotating the shape).
A good principle of OO is to co-locate related behavior and state. In this case the rotate behavior of shape depends on the colour state of shape, so it makes sense to co-locate both in the Shape class, c.q. create a field 'colour' and use it within the rotate method to customize the rotation behavior.
Apart from this design decision, you are really also asking about a refactoring decision: how do I handle the application code that depends on shape? My approach in cases like this is to think ahead: how many changes like these to the Shape class can we expect? If this is a rare change then you could just go ahead and change all the code locations that initialize the shape class so a colour is set. If shape changes more often, then you should be more rigorous and make your code less tightly coupled. A way to do that in this case is to create an abstract factory (or use the factory offered by a D.I. framework like Spring) so that the application code does not need to know the creation details of shape.
BTW your third option seems sub-optimal to me: part of the code is not made aware of the addition of the colour state to shape, and keeps calling the old 'deprecated' rotate method. This means that setting a shape's colour to blue will not universally affect the rotation behavior, but only in 'special cases'. This weakens the design and makes it harder for the developers after you to understand it.
I think the first option is is tedious to implement. What if you miss at one place, what if later u realize that you need rotate(single parameter) again.
The second option is irrelevant as many have already pointed out.
3rd I think is the best solution, as it will not break your code. You can have both the overloaded method, can use any of them as per requirement.
As for me, I see classic example of inheritance usage here.
class Shape {
public void rotate(int v) {}
}
class GreenShape extends Shape {
public void rotate(int v){
super.rotate(v + 10);
}
}

Categories