Storing data in Ram - java

I ve got a problem in a game project. I develop a bot in video game. The game engine of the game is that the game gives every game tick information about the track and i use that information to make decisions about bot strategy. I want to store that information all these game ticks in a txt file. However, i noticed that when i store the data in txt files my bot fails to make correct decision. Actually the behavior of the bot slow down. Is there efficient way to store my data to ram? My project is in java.

If the bot needs the data to make it's decision, it's best to keep all that data in ram.
If you need to save the data for other reasons to disk, you might want to consider only saving the data every minute, and not every game tick, as disk-io tends to be slow.

File writing is comparatively very slow, hence why your game slows down. What information exactly do you need to store? Defining a class (used statically, if necessary, but preferably not) whose members represent the data you need is probably a way to go about it...

Related

Implementing Google Saved Games for Android (Java)

I'm attempting to implement a VERY simple saved games setup on Android. I am providing two buttons to the user-- one is "save" and one is "load."
Both will call simple functions:
Save(name);
Load(name);
When I save, I want it to overwrite whatever exists, if it has the same name-- no matter what. Similary, if I try to load, and the name doesn't exist, I just want to bomb out and say, nope, doesn't exist.
(The game has user created levels, so it would be too dangerous to sync it behind the scenes-- my users will have to do their own conflict management).
Here's my problem... two problems actually. One, I cannot find any sample code that is simpler than a deluxe save/load suite designed for multiple save games, conflict resolution, and a cherry on top. The second problem is, even the complex code is so full of depreciations that I can't even paste it into my code and start playing with it (even the apparently newest stuff is full of unresolvable methods and depreciations).
Can anyone either explain, or point me to, a "simplest" implementation of saved games, that just writes some data to by synced, and then reads it back?

Saving multithreaded game

I have written a 2d platformer in java, and i was wondering how i would save the game. I looked at just serializing the whole game using XMLEncoder or ObjectOutputStream, however those didn't save threads correctly. When i started the game again the thread weren't running. So then i tried calling start on all of the threads after the game loaded, but that created a major problem with the threads being in invalid states and the game started glitching up. What is the best way to just write the whole game to a save file.
Saving a game will rarely be as straightforward as saving all objects exactly as they are in memory at the time of exit/saving and then loading them back to their exact state afterward.
It is more likely that you will need/want to create a data structure to represent your game's state which you will then write to disk. Multithreading is unlikely to be your primary concern. You will want to start these threads back up anew when you load your game state.
Consider that many games save/load via a menu. If your game starts out with a splash screen, or at least a main menu, you wouldn't want to be loading objects from their exact state on startup anyway. Find the minimal important elements that you need to reconstruct everything that is important about the state of the game and save that to disk. Most of the state of a game can be implicitly recreated from a very small amount of data.
Sadly, the exact method of how you should save/load your game is not easily answered on a Q/A website as it will depend heavily on the exact data structures you are using and the entire nature of your game.
You should serialize only your business domain data, not threads. Threads need to be created again when you reload data. ObjectOutputStream is ok assuming your domain classes are Serializable.

Where should I store my game level state?

I have a game where I draw and move bitmaps over a SurfaceView. The user can interact (drag and drop) these bitmaps. When the player hits the home button then goes back into the game, I want to be able to pause the game, then restore it to where it was before he left it. What is the best way to store my custom objects?
Should I implement onSaveInstanceState(Bundle) and have all of the classes whose objects I want to save implement the Parcelable interface? This would be quite a bit of work, and I'm still not sure how I would save things like bitmaps. I suppose I wouldn't and I would just reload those from disk.
I am also confused about what kind of storage a bundle offers: disk storage that never goes away unless you clear it yourself, or memory storage that goes away if the OS decides to remove your program from memory while it's in the background. According to the comments in this question, it is disk storage. The documentation implies that it is memory storage, saying Note that it is important to save persistent data in onPause(), however I don't find it very clear. This page also implies that it is not persistent: it only lasts as long as the application remains in memory. So which one is it?
The last link above suggests using onRetainNonConfigurationInstance() to keep objects in memory while the application is in the background. This would imply that if the program is taken out of memory by the OS while in the background, everything would be lost. This seems to be what most (all I tested on) games do: if you hit home while playing then go back in, the level resumes. If you hit home, open a lot of stuff (sufficient to make Android remove the game from memory), then go back in, nothing is resumed, the game starts from the main menu. Does that mean this is what they use, and if so, is that a good practice?
Note that the question about a Bundle's persistency is just a secondary curiosity. I don't really care if the state of this game is not permanently saved and can be lost after the game being in the background for a while (as described in 2 above). I'm interested in the best practice for this case.
The basic idea is, IMO, identify the smallest collection of values that will enable you to recreate the state of your game. Save those in shared preferences.

Best way to implement game playback?

I'm creating a grid based game in Java and I want to implement game recording and playback. I'm not sure how to do this, although I've considered 2 ideas:
Several times every second, I'd record the entire game state. To play it back, I write a renderer to read the states and try to create a visual representation. With this, however, I'd likely have a large save file, and any playback attempts would likely have noticeable lag.
I could also write every key press and mouse click into the save file. This would give me a smaller file, and could play back with less lag. However, the slightest error at the start of the game (For example, shooting 1 millisecond later) would result in a vastly different game state several minutes into the game.
What, then, is the best way to implement game playback?
Edit- I'm not sure exactly how deterministic my game is, so I'm not sure the entire game can be pieced together exactly by recording only keystrokes and mouse clicks.
A good playback mechanism is not something that can be simply added to a game without major difiiculties. The best would be do design the game infrastructure with it in mind. The command pattern can be used to achieve such a game infrastructure.
For example:
public interface Command{
void execute();
}
public class MoveRightCommand implements Command {
private Grid theGrid;
private Player thePlayer;
public MoveRightCommand(Player player, Grid grid){
this.theGrid = grid;
this.thePlayer = player;
}
public void execute(){
player.modifyPosition(0, 1, 0, 0);
}
}
And then the command can be pushed in an execution queue both when the user presses a keyboard button, moves the mouse or without a trigger with the playback mechanism. The command object can have a time-stamp value (relative to the beginning of the playback) for precise playback...
Shawn Hargreaves had a recent post on his blog about how they implemented replay in MotoGP. Goes over several different approaches and their pros and cons.
http://blogs.msdn.com/shawnhar/archive/2009/03/20/motogp-replays.aspx
Assuming that your game is deterministic, it might be sufficient if you recorded the inputs of the users (option 2). However, you would need to make sure that you are recognizing the correct and consistent times for these events, such as when it was recognized by the server. I'm not sure how you handle events in the grid.
My worry is that if you don't have a mechanism that can uniformly reference timed events, there might be a problem with the way your code handles distributed users.
Consider a game like Halo 3 on the XBOX 360 for example - each client records his view of the game, including server-based corrections.
Why not record several times a second and then compress your output, or perhaps do this:
recordInitialState();
...
runs 30 times a second:
recordChangeInState(previousState, currentState);
...
If you only record the change in state with a timestamp(and each change is small, and if there is no change, then record nothing), you should end up with reasonable file sizes.
There is no need to save everything in the scene for every frame. Save changes incrementally and use some good interpolation techniques. I would not really use a command pattern based approach, but rather make checks at a fixed rate for every game object and see if it has changed any attribute. If there is a change that change is recorded in some good encoding and the replay won't even become that big.
How you approach this will depend greatly on the language you are using for your game, but in general terms there are many approaches, depending on if you want to use a lot of storage or want some delay. It would be helpful if you could give some thoughts as to what sacrifices you are willing to make.
But, it would seem the best approach may be to just save the input from the user, as was mentioned, and either store the positions of all the actors/sprites in the game at the same time, which is as simple as just saving direction, velocity and tile x,y, or, if everything can be deterministic then ignore the actors/sprites as you can get their information.
How non-deterministic your game is would also be useful to give a better suggestion.
If there is a great deal of dynamic motion, such as a crash derby, then you may want to save information each frame, as you should be updating the players/actors at a certain framerate.
I would simply say that the best way to record a replay of a game depends entirely on the nature of the game. Being grid based isn't the issue; the issue is how predictable behaviour is following a state change, how often there are new inputs to the system, whether there is random data being injected at any point, etc, You can store an entire chess game just by recording each move in turn, but that wouldn't work for a first person shooter where there are no clear turns. You could store a first person shooter by noting the exact time of each input, but that won't work for an RPG where the result of an input might be modified by the result of a random dice roll. Even the seemingly foolproof idea of taking a snapshot as often as possible isn't good enough if important information appears instantaneously and doesn't persist in any capturable form.
Interestingly this is very similar to the problem you get with networking. How does one computer ensure that another computer is made aware of the game state, without having to send that entire game state at an impractically high frequency? The typical approach ends up being a bespoke mixture of event notifications and state updates, which is probably what you'll need here.
I did this once by borrowing an idea from video compression: keyframes and intermediate frames. Basically, every few seconds you save the complete state of the world. Then, once per game update, you save all the changes to the world state that have happened since the last game update. The details (how often do you save keyframes? What exactly counts as a 'change to the world state'?) will depend on what sort of game information you need to preserve.
In our case, the world consisted of many, many game objects, most of which were holding still at any given time, so this approach saved us a lot of time and memory in recording the positions of objects that weren't moving. In yours the tradeoffs might be different.

Alternatives to rotating buffers into Players in J2ME?

Due to (quite annoying) limitations on many J2ME phones, audio files cannot be played until they are fully downloaded. So, in order to play live streams, I'm forced to download chunks at a time, and construct ByteArrayInputStreams, which I then feed to Players.
This works well, except that there's an annoying gap of about 1/4 of a second every time a stream ends and a new one is needed. Is there any way to solve this problem, or the problem above?
The only good way to play long (3 minutes and more) tracks with J2ME JSR135, moderately reliably, on the largest number of handsets out there, is to use a "file://" url when you create the player, or to have the inputstream actually come from a FileConnection.
recent blackberry phones can use a ByteArrayInputstream only when they have a large java heap memory available.
a lot of phones running on the Symbian operating system will allow you to put files in a private area for the J2ME application while still being able to play tracks in the same location.
Unfortunately you can't get rid of these gaps, at least not on any device I've tried it on. It's very annoying indeed. It's part of the spec that you can't stream audio or video over HTTP.
If you want to stream from a server, the only way to do it is to use an RTSP server instead though you'll need to check support for this on your device.
And faking RTSP using a local server on the device (rtsp://localhost...) doesn't work either.. I tried that too.
EDIT2: Or you could just look at this which seems to be exactly what you want: http://java.sun.com/javame/reference/apis/jsr135/javax/microedition/media/protocol/DataSource.html
I would create two Player classes and make sure that I had received enough chunks before I started playing them. Then I would start playing the first chunk through player one and load the second one into player two. Then I would use the TimeBase class to keep track of how much time has passed and when I knew the first chunk would end (you should know how long each chunk has to play) then I would start playing the second chunk through the second player and load the third chunk into the first and so on and so forth until there are no more chunks to play.
The key here is using the TimeBase class properly to know when to make the transition. I think that that should get rid of the annoying 1/4 second gap bet between chunks. I hope that works, let me know if it does because it sounds really interesting.
EDIT: Player.prefetch() could also be useful here in reducing latency.

Categories

Resources