With Slick2D, how to change the resolution during gameplay? - java

I am developing a tile-based strategy game using Java and the Slick2D API.
So far so good, but I've come to a standstill on my options menu. I have plans for the user to be able to change the resolution during gameplay (it is pretty common, after all).
I can already change to fullscreen and back to windowed, this was pretty simple...
//"fullScreenOption" is a checkbox-like button.
if (fullScreenOption.isMouseOver(mouseX, mouseY)) {
if (input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) {
fullScreenOption.state = !fullScreenOption.state;
container.setFullscreen(fullScreenOption.state);
}
}
But the container class (Implemented by Slick, not me), contrary to my previous beliefs, does not seem to have any display-mode/resolution-change functions! And that's pretty much the situation...
I know it's possible, but i don't know what is the class responsible (if it exists)!
The AppGameContainer class, used on the very start of the game's initialization, is the only place with any functions for changing the display-mode that I've found so far, but it's only used at the very start, and as of Slick's tutorials, is implemented as local.
//This is my implementation of it...
public static void main(String[] args) throws SlickException {
AppGameContainer app = new AppGameContainer(new Main());
// app.setTargetFrameRate(60);
app.setVSync(true);
app.setDisplayMode(800, 600, false);
app.start();
}
I can define it as a static global on the Main class, in order to use it inside the update() method of the options screen, but it's probably a (very) bad way to do it...

There is an easy way to do this. I found this on another site. You can cast the GameContainer object (the one you get from the update method) into an AppGameContainer method. Then you can access the setDisplayMode:
AppGameContainer gc = (AppGameContainer) container;
gc.setDisplayMode(800, 600, false);
Original post here.

Theoretically all you have to do is create a new AppGameContainer object, and then re-run all your initialization code, except for code that resets the state of your game (you don't want the game to be reset to its starting state, after all).
You're right that the tutorials don't cover this, so I don't think you're missing anything. Here's a list of concerns that you'll have to handle when changing resolution. So long as you break these out into separate methods in such a way that you can re-run init any time in the game, then you should be fine.
Your render method needs to check the current resolution with each execution when it determines what to draw. To say it another way, the render method shouldn't care what the current resolution is - it should just look it up each time, and do what's appropriate.
If you're using the Slick buttons and other UI events, including event listeners, then before you re-initialize everything, you need to get a list of all the subscribed listeners, re-initialize your UI elements in the new AppGameContainer, and have all the listeners re-subscribe to the new elements.
Analyze your code and look for any other place that depends on the UI being a certain state, and re-initialize it from the init method when the resolution changes.
So, the pseudo-code version of this is:
When your game first starts up:
main(args)
- initi()
if (gameStartingForTheFirstTime())
- initUI()
- initGameState()
- initWhateverElseYouNeedToForYourGame()
if (resolutionChanging())
- initUI()

After also consulting gamedev.stackexchange and Slick2D's forums, the action i took to solve the problem was to use a mix between #normalocity's solution, the use of the ScalableGame interface, as well as, and most importantly, compiling my own version of the API (since it's open-source).
The changes to the API include, but are not limited to, a more direct access to Container's setDisplayMode(), with solved the problem related to this question.
For anyone with the same or similar problems, this is the solution I suggest.
EDIT-NOTE: Although my answer is still valid, and I am not developing with Slick2D, #Requios' answer is a better approach without any problems, judging by the positive votes and lack of comments pointing out any problems. So that's the approach I'd recommend, and I've accordingly switched the "chosen answer" to his, as well as cast my own upvote.

Related

Java- Check for key presses not using KeyListener

I'm making a prototype for a videogame using Java (I plan on porting it to Unity later, but since I'm pretty comfortable with Java, I figure it'll be quicker to get an idea for the structure and basic components of my game in Java). Perhaps ironically, however, I have some doubts about how to do this thing in Java.
What is the best way to collect key presses? I know about KeyListeners and how to use them, but they don't seem ideal. I would like to be able to call a keyPress() method once every update cycle (at the beginning of the cycle, specifically) for precision reasons–I have information being updated each cycle and I want it to vary depending on which key is pressed–I realize that being even a couple of frames asynchronous isn't a huge deal, but immediacy of response is pretty important in making the game play well, I feel. I also don't want to be individually alerted every time a different key is pressed, but ideally, I'd like to generate a kind of list of which keys are pressed at any given moment (the game input consists of specific keystrokes, and so at any moment, I want to know what the active keystroke is). There's also other issues, regarding the timings when game events happen that make being synchronized to within 3 or 4 frames pretty important. It is less important that each cycle run fast than it is that I get the response to keys at the beginning of the cycle.
Is there way to do this? If there is, is it a good idea? Would it be too slow to expect any kind of consistent gameplay if I run this every update cycle (I'd expect it might even be faster or at least lighter than a listener)? Are there other places where this could wrong?
Thanks
first you should look at your gameplay.
The use of events will not problem for you. And code disorder and event control make it difficult.
There are many solutions to this. At first, did you used any frameworks (like the Libgdx)? if yes. this is handle, Otherwise you can go yourself.
One way to use "Message Handling". in this solution,You can write the code below.
public interface Telegram {
public boolean handleMessage(final Telegram msg,Object yourObject );
}
public class MessageHandler {
private static Map<String,List<Telegram>> telegramKeyMap = new HashMap<>();
public static void addTelegram(String key,Telegram telegram){
List<Telegram> telegramList = telegramKeyMap.getOrDefault(key, new ArrayList<Telegram>());
telegramList.add(telegram);
}
public static void dispatchMessage(String key,Object addVal){
List<Telegram> telegramList = telegramKeyMap.getOrDefault(key, new ArrayList<Telegram>());
for (Telegram telegram : telegramList) {
telegram.handleMessage(telegram,addVal);
}
}
}
public class Player implements Telegram {
public Player() {
}
#Override
public boolean handleMessage(Telegram msg, Object yourObject) {
return false;
}
}
in this code you can implement Telegram for any classes. then on the listeners call dispatchMessage. for input you can used any Objects(like Listener, keyCode,...)
dispatcher fine any object with this key, them call handleMessage method. Now, each of your objects can handle their work.
second solution : Use "Event Management"
If the first option does not resolve your problem, then I'll take the second solution to the sample code. The message handler is used in most game engine engines, and it does increase the speed of the game, but it's opening up your hands sharply.

Agent in JADE behaviour not working

I'm trying to create a game where JADE Agents are the 'enemies' and they chase a player around a maze.
So far I have:
MazeView.java (uses Swing to paint various things on the screen, and lets the user interact through button presses)
Enemy.java (a JADE agent that will have behaviours like search, pursue, etc.)
And a few other classes doing things like generating the actual maze data structure etc.
My problem is that, while I can instantiate an Agent and paint it on the screen, for some reason I can't add any behaviours. For example, if I wanted something like this (in Enemy.java):
protected void setup() {
// Add a TickerBehaviour that does things every 5 seconds
addBehaviour(new TickerBehaviour(this, 5000) {
protected void onTick() {
// This doesn't seem to be happening?
System.out.println("5 second tick... Start new patrol/do something?");
myAgent.addBehaviour(new DoThings());
}
}); // end of addBehaviour
System.out.println("End of setup()...");
} // end of setup
When I run the code, no errors are thrown, and I can see "End of setup()..." displayed in console. So for some reason it's just not going into the addBehaviour() method at all. Even if the DoThings() behaviour didn't work (right now it just prints a message), it should at least display the "5 second tick" message before throwing an error. What is going wrong here?
I think it could be something to do with the fact that currently there is no concept of 'time' in my maze. The user presses a key, and THEN processing happens. So having an agent that does things every 5 seconds might not work when there is no real way to facilitate that in the maze? But I'm still confused as to why it just skips addBehaviour() and I don't get an error.
A possible solution might be to re-implement my maze as a constant loop that waits for input. Would that allow a concept of 'time'? Basically I'm not sure how to link the two together. I am a complete beginner with JADE.
Any ideas would be appreciated. Thanks!
I've never used Jade, but my first thought was that you are adding behaviors and then assuming that Jade will decide to run them at some point. When you say that you never see your behaviors activate, it strengthened that hypothesis.
I looked at the source and sure enough, addBehaviour() and removeBehaviour() simply add and remove from a collection called myScheduler. Looking at the usages, I found a private method called activateAllBehaviours() that looked like it ran the Behaviours. That method is called from the public doWake() on the Agent class.
I would guess that you simply have to call doWake() on your Agent. This is not very apparent from the JavaDoc or the examples. The examples assume that you use the jade.Boot class and simply pass the class name of your agent to that Boot class. This results in the Agent getting added to a container that manages the "waking" and running of your Agents. Since you are running Swing for your GUI, I think that you will have to run your Agents manually, rather than the way that the examples show.
I got more curious, so I wrote my own code to create and run the Jade container. This worked for me:
Properties containerProps = new jade.util.leap.Properties();
containerProps.setProperty(Profile.AGENTS, "annoyer:myTest.MyAgent");
Profile containerProfile = new ProfileImpl(containerProps);
Runtime.instance().setCloseVM(false);
Runtime.instance().createMainContainer(containerProfile);
This automatically creates my agent of type myTest.MyAgent and starts running it. I implemented it similar to your code snippet, and I saw messages every 5 seconds.
I think you'll want to use setCloseVM(false) since your UI can handle closing down the JVM, not the Jade container.

Static sprite batch?

As my research goes everywhere it's said that we should only use one sprite batch per instance. But what if i set sprite batch to static in class which controls the game (calls different screens etc).
When i have tryed this its working like charm, but is that a good practice or it may result some problems in future. Then if it could be done can i also share stage and shape renderer?
note: the main reason why i am trying to go with that "static batch technique" is that java crashes when i try to dispose stage, sprite batch or shape renderer
I do it that way as well and I didn't run into any problems so far.
You need to be careful with the SpriteBatch.begin() and SpriteBatch.end() calls, since you may never know where it was started already, and where it was stopped when it is shared.
Same applies for the Camera/ProjectionMatrix. And also for the currently used ShaderProgram in case you are working with shaders.
Make sure that you are always fully aware of where you are doing what with your SpriteBatch otherwise you might face weird bugs one day.
Stage should not be shared, since it will probably serve different purposes. For different UIs it doesn't make any sense to use only one Stage.
ShapeRenderer could be shared, since it kind of works the same like SpriteBatch, but probably you only want to use it in a single place.
dispose() should actually work without any problems. You have to make sure that you dispose everything in the correct order so nothing will be left over in the end and cause exceptions.
As #noone allready said it should not cause any problems, if you take care.
But i just wanted to point out another thing: In some Screens (MenuScreen, OptionScreen, ...) you may use Scene2dUi for some UI stuff. So you will use Stages, which belong to the Screen and are not shared. So in this case you should remember, that every Stage has its own SpriteBatch and Camera. So it could be, that you only need an additional SpriteBatch in your
GameScreen. If this is the case i would not make it static and have it only in the GameScreen.
As noone said dispose() should work, if you use the correct order, and so also going with more then 1 SpriteBatch should not cause any problems.
So i think both ways will work and are good approaches. It depends on your design and how/where you want to use the SpriteBatches and Cameras.

How can I best apply OOP principles to games and other input-driven GUI apps?

Whenever I try to write graphical programs (whether a game or really any GUI app) I always wind up with one or two god classes with way too many methods (and long methods, too), and each class having far too many responsibilities. I have graphics being done at the same time as calculations and logic, and I feel like this is a really bad way to go about organizing my code. I want to get better at organizing my code and abstracting out responsibilities to different classes. Here's an example of where I'd like to start - I want to write a Minesweeper clone, just sort of as practice and to try to improve my software engineering skills. How would I go about making this nice and object-oriented? For the sake of discussion, let's just say I'm using Java (because I probably will, either that or C#). Here's some things I would think about:
should each tile inherit from JButton or JComponent and handle drawing itself?
or should the tiles just be stored as some non-graphical MinesweeperTile object and some other class handles drawing them?
is the 8-segment display countdown timer (pre-Vista, at least) a separate class that handles drawing itself?
when the user clicks, do the tiles have mouse event listeners or does some other collision detection method loop through the tiles and check each one to see if it's been hit?
I realize that there's not just one way to write a GUI application, but what are some pretty basic things I can start doing to make my code more organized, manageable, object-oriented, and just over all write better programs?
edit: I guess I should add that I'm familiar with MVC, and I was originally going to incorporate that into my question, but I guess I didn't want to shoehorn myself into MVC if that's not necessarily what I need. I did searched for topics on MVC with GUI apps but didn't really find anything that answers my specific question.
edit2: Thanks to everyone who answered. I wish I could accept more than one answer..
Here is a simple (but effective) OO design to get you started:
First create a Game object that is pure Java/C# code. With no UI or anything else platform specific. The Game object handles a Board object and a Player object. The Board object manages a number of Tile objects (where the mines are). The Player object keeps track of "Number of turns", "Score" etc. You will also need a Timer object to keep track of the game time.
Then create a separate UI object that doesn't know anything about the Game object. It is completely stand alone and completely platform dependent. It has its own UIBoard, UITile, UITimer etc. and can be told how to change its states. The UI object is responsible for the User Interface (output to the screen/sound and input from the user).
And finally, add the top level Application object that reads input from the UI object, tells the Game what to do based on the input, is notified by the Game about state changes and then turns around and tells the UI how to update itself.
This is (by the way) an adaption of the MVP (Model, View, Presenter) pattern. And (oh by the way) the MVP pattern is really just a specialization of the Mediator pattern. And (another oh by the way) the MVP pattern is basically the MVC (Model, View, Control) pattern where the View does NOT have access to the model. Which is a big improvement IMHO.
Have fun!
use a MVC framework that handles all the hard organization work for you. there's a ton of MVC framework topics on SO.
using high quality stuff written by others will probably teach you faster - you will get further and see more patterns with less headache.
I'm not suggesting this is the only way to do it, but what I would suggest is something like the following. Other people, please feel free to comment on this and make corrections.
Each tile should inherit from something and handle drawing itself. A button seems like the best solution because it already has the button drawing functionality (pressed, unpressed, etc) built in.
Each tile should also be aware of its neighbors. You would have eight pointers to each of its eight neighbors, setting them to null of course if there is no neighbor. When it goes to draw, it would query each neighbor's IsMine() function and display the count.
If none of its neighbors are a mine, it would then recurse into each neighbor's Reveal() method.
For the 7-segment display, each digit is its own class that handles drawing. Then I would make a CountdownSegmentDigit class that inherits from this class, but has additional functionality, namely CountDown(), Set(), and Reset() methods, as well as a HitZero event. Then the display timer itself is a collection of these digits, wired up to propagate zeroes left. Then have a Timer within the timer class which ticks every second and counts down the rightmost digit.
When the user clicks, see above. The tile itself will handle the mouse click (it is a button after all) and call its Reveal() method. If it is a mine, it will fire the MineExploded event, which your main form will be listening to.
For me, when I think of how to encapsulate objects, it helps to imagine it as a manufacturing process for physical parts. Ask yourself, "How can I design this system so it can be most efficiently built and reused?" Think about future reuse possibilities too. Remember the assembly process takes small pieces and builds them up into larger and larger pieces until the entire object is built. Each bit should be as independent as possible and handle its own logic, but be able to talk to the outside world when necessary.
Take the 7-segment display bit, you could have another use for it later that does not count down. Say you want a speedometer in a car or something. You will already have the digits that you can wire up together. (Think hardware: stock 7-segment displays that do nothing but light up. Then you attach a controller to them and they get functionality.)
In fact if you think hard enough, you might find you want CountUp() functionality too. And an event argument in HitZero to tell whether it was by counting up or down. But you can wait until later to add this functionality when you need it. This is where inheritance shines: inherit for your CountDownDigit and make a CountUpOrDownDigit.
Thinking about how I might design it in hardware, you might want to design each digit so it knows about its neighbors and count them up or down when appropriate. Have them remember a max value (remember, 60 seconds to a minute, not 100) so when they roll over 0, they reset appropriately. There's a world of possibilites.
The central concern of a Graphic User Interface is handling events. The user does X and you need to response or not respond to it. The games have the added complexity in that it needs to change state in real time. In a lot of cases it does this by transforming the current state into a new state and telling the UI to display the results. It does this in a very short amount of time.
You start off with a model. A collection of classes that represents the data the user wants to manipulate. This could represent the accounts of a business or vast frontiers of an unknown world.
The UI starts with defining a series of forms or screens. The idea is that is for each form or screen you create a interface that defines how the UI Controller will interact with it. In general there is one UI Controller classes for each form or screen.
The form passes the event to the UI Controller. The UI Controller then decides which command to execute. This is best done through the Command design pattern where each command is it own class.
The Command then is executed and manipulate the model. The Command then tells the UI Controller that a screen or a portion of a screen needs to be redraw. The UI Control then looks at the data in the model and uses the Screen Interface to redraw the screen.
By putting all the forms and screen behind a interface you can rip out what you have and put something different in. This includes even not having any forms at all but rather mock objects. This is good for automated testing. As long as something implements the Screen Interface properly the rest of the software will be happy.
Finally a game that has to operate in real time will have a loop (or loops) running that will be continually transforming the state of the game. It will use the UI Controller to redraw what it updated. Commands will insert or change information in the model. The next time the loop comes around the new information will be used. For example altering a vector of a object traveling through the air.
I don't like the MVC architecture as I feel it doesn't handle the issues of GUIs well. I prefer the use of a Supervising Controller which you can read about here. The reason for this is that I believe automated tests are one of the most important tools you have. The more you can automate the better off you are. The supervising presenter pattern makes the forms a thin shell so there is very little that can't be tested automatically.
Sorry to say it, but it seems you have mess in your head trying to improve your coding too much in one step.
There is no way to answer your question as such, but here we go.
First start with OOP, think about what objects are required for your game/GUI and start implementing them a little at a time, see if there are chances to break up these objects further, or perhaps reunite some objects that make no sense on their own, then try to figure out if you have repeated functionality among your objects, if you do, figure out if this repeated functionality is a (or many) base class or not.
Now this will take you a few days, or weeks to really grok it well, then worry about dividing your logic and rendering.
I have some tutorials that are written in C#. It discusses this very same topic. It is a starting point for a RogueLike game.
Object Oriented Design in C# Converting Legacy Game
Object Oriented Design: Domain Type Objects
Object Oriented Design: Rethinking Design Issues
BROKEN LINK - Object Oriented Design: Baby Steps in Acceptance Testing

Pacman in Java questions

For my university assignment I have to make a networkable version of pacman. I thought I would best approach this problem with making a local copy of pacman first and then extend this functionality for network play.
I would have to say that I am relatively new to java GUI development and utilizing such features within java.
http://www.planetalia.com/cursos/Java-Invaders/
http://javaboutique.internet.com/PacMan/source.html
I have started following the above links with regards to game development within java and an example of the pacman game.
I decided to represent the maze as an int array with different values meaning different things. However when the paint method inside the main game loop is run i am redrawing the whole maze with this method.
for (int i : theGame.getMaze())
{
if (i == 4)
{
g.setColor(mazeWallColour);
g.fillRect(curX, curY, cellSize, cellSize);
curX += 25;
}
else
{
curX += cellSize;
}
index++;
// Move to new row
if (index == 25)
{
index = 0;
curX = 10;
curY += cellSize;
}
}
However this is providing me with less then 1fps. Although i've noticed the example linked above uses a similar way of redrawing each time the paint method is called and i believe does this on a image that is not viewable (kinda like double buffering [I've used a BufferStrategy like the first link explains]) What would be a better way to redraw the maze?
Any pointers/advice with this would be useful.
Thank you for your time.
http://pastebin.com/m25052d5a - for the main game class.
Edit: I have just noticed something very weird happening after trying to see what code was taking so long to execute.
In the paintClear(Graphics g) method i have added
ocean = sprites.getSprite("oceano.gif");
g.setPaint(new TexturePaint(ocean, new Rectangle(0,t,ocean.getWidth(),ocean.getHeight())));
g.fillRect(10, 10,getWidth() - 20,getHeight() - 110);
which made the whole thing run smoothly - however when i removed these lines the whole thing slowed down? What could have caused this?
Updated code
First off, I'd recommend that you use named constants rather than having random magic numbers in your code and consider using enums for your cell types. While it won't make your code run any faster, it certainly will make it easier to understand. Also, 'i' is normally used as a counter, not for a return value. You should probably call it cellType or something similar. I'd also recommend that you use a 2D array for your stage map since it makes a number of things easier, both logistically and conceptually.
That said, here are a few things to try:
Pull the setColor() out of the loop and do it once. The compiler might be able to do loop-invariant hoisting and thus do this for you (and probably will), but conceptually, you should probably do this anyway since it appears you want all of your walls to be one color anyway.
Try calling drawRect() instead of fillRect() and see if that draws faster. I don't think it will, but it is worth a shot, even if it looks uglier. Similarly, you can try creating an Image and then drawing that. This has the advantage that it is really easy to tell your Graphics object to implement a transform on your image. Also, consider taking this out completely and make sure that it is being a significant performance hit.
Also, normally you don't need to ask for the parent for its Graphics object and implement painting directly on it. Rather, you should override its paintComponent() method and just utilize the Graphics given to you (possibly calling helper methods as you do). Swing components are double-buffered by default, so you don't need to implement that yourself; just let the swing object do its job and let you know when to paint.
Also, you end up repainting the entire screen, which is something of overkill. If you call repaint(Rectangle), Swing can choose to redraw only the sections of your board that are explicitly marked dirty. When you update one of your sprites, call repaint(r) only on the area of the sprite's old and new locations. When you complete a level and need a new board, then you can call repaint() (without parameters) to redraw the entire map.
You should also look at Sun's tutorial to get some tips for efficiency in Swing.
I still consider myself a beginner with Java, but I recently developed a Frogger-esque game with dynamic map and editor using some of the techniques you've mentioned, and I'm only too happy to provide some help.
As mentioned, enum's are the way to go. I set my map up as a 2-dimensional array and set an enum for each different type, writing a method inside my map class to take in one image and divide each square in the map to each value in my enum.
A tutorial that helped me with mapping can be found on Coke and Code. All the source code is there if you need a hand with any of it, although you do seem to have a decent grasp of what you're doing. If you still need help I could always drag out some source code.
It looks like your call to Thread.sleep doesn't do what you intended, but I don't think it's the source of your trouble. You have:
Thread.sleep(Math.max(0, startTime - System.currentTimeMillis()));
startTime will always be less than System.currentTimeMillis(), so startTime - System.currentTimeMillis() will always be negative and thus your sleep will always be for 0 milliseconds. It's different from the example you showed because the example increments startTime by 40 milliseconds before doing the calculation. It is calculating how long to sleep for to pad out the drawing time to 40 milliseconds.
Anyway, back to your problem. I'd recommend measurement to figure out where your time is being spent. There's no point optimising until you know what's slow. You already know how to use System.currentTimeMillis(). Try using that to measure where all the time goes. Is it all spent drawing the walls?
EDIT - I see this got marked as accepted, so should I infer that the problem went away when you fixed the sleep time? I don't have a lot of Java GUI experience, but I can speculate that perhaps your code was starving out other important threads. By setting your thread to have maximum priority and only ever calling sleep(0), you pretty much guarantee that no other thread in your process can do anything. Here's a post from Raymond Chen's blog that explains why.
The code you listed above can't be the source of the 1fps problem... I have code doing far more than this that runs far faster.
Can you benchmark that code and make sure it's the root of the problem?
I'm no game developer, but that framerate seems very slow.
I'm not quite sure how your code is working, but one possibility for improving rendering performance would be to find those parts of the display that don't change much (such as the walls of the maze) and avoid re-creating them for each frame.
Create a BufferedImage containing the constant elements (maze?, background) and then re-draw it first for each frame. On top of this Buffered image, draw the variable elements (PacMan, ghosts, dots, etc).
This technique, along with many other Java2D performance tips, is discussed in Romain Guy's excellent book Filthy Rich Clients.
Just so you don't worry that it's Java, I worked on a Spectrum Analyzer (Like an o-scope) where the entire GUI portion(the trace, menus, button & wheel handling) was done in Java. When I got there it was getting 1fps, when I left it was 12-20. That had a lot of processing going on and was running on a very slow processor.
Look at only updating parts of the GUI that you need to update. Often you can redraw the entire screen but just set a clipping region to the part that is truly updated.
Be careful about inner loops--they are The Speed Killer.
Try to avoid allocating and freeing huge numbers of objects. I'm not saying don't use objects, I'm saying don't create one for each pixel :)
Good luck
Wow, that's a pretty tough problem to give someone just learning Java.
My advice? Think in terms of objects. Can you write something WITHOUT a user interface that mimics the behavior of the game itself? Once you get that working, you can concentrate on the special problems of the user interface. Yes, start with a local version before the networked piece.
I'm not a gamer. I wonder what Java2D API would offer to make your life better?
How much time do you have to finish it?
This might sound obvious but your performance problem is because you are redrawing the entire maze, which doesn't need to be done, instead you need to redraw only changed parts of your maze.
The way I've approached this issue before is by seperating the updating of the maze from the actual redrawing into different threads (kind of like a threaded MVC). Every time you change a cell in your maze you would mark it as "dirty", your redraw thread will check every now and then to redraw only the dirty cells.
Sorry for the extremly generic advice
Java/Swing double-buffers by default. If you're using Swing, you don't need to double-buffer separately, like other answers suggest.
I agree with Allain, that the code you listed can't be the cause of 1fps. I've written highly inefficient Java/Swing animation code that runs much faster than you describe. Do some more testing to narrow down the cause of the slowness.
If possible, you should keep an image of the maze, and draw it in one library call. It probably doesn't need to be full resolution, either -- if you want a blocky, 8-bit feel, I expect the graphics library will be more than happy to oblige 8^)
Also, as others have mentioned, you can save time by redrawing only those parts of the screen that need updating. This can be annoying to implement, but it may allow you to significantly improve your frame rate. Be sure to do some experiments to make sure this is the case before exerting the required effort!

Categories