• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
RLS0812

Saving And Loading Object Arrays

5 posts in this topic

I have written some code, which saves and loads object arrays to / from file.
I would like to know if this test code is correct, and if there is any way to improve it.
The goals of this test code:
1: - Create object arrays
2: - Save object arrays
3: - Load object arrays

[Note:] The objects being used here are just for testing.
[source lang="java"]import java.io.*;

public class Main {

public static void main(String[] args){
// Simulate Unknown Number Of Objects
String[] cc = {"One","Two","Three","Four"};
// Create The Dump Array
String_Object[] DA = new String_Object[cc.length];
// Create Loading Array
String_Object[] LA;
File file = new File("EXP.sav");
int x= 0;
// Create Object Array
while (x != cc.length){
String_Object STR = new String_Object(cc[x]);
DA[x] = STR;
x ++;
}
x = 0;
// Save Object Array
try{
FileOutputStream SO = new FileOutputStream(file);
ObjectOutputStream save = new ObjectOutputStream(SO);
save.writeObject(DA);
save.close();
}
catch(Exception e){System.out.println(e);}
// Load Object Array
//if (file.exists() ){}
try{
FileInputStream SO = new FileInputStream(file);
ObjectInputStream save = new ObjectInputStream(SO);
LA = (String_Object[]) save.readObject();
save.close();
while (x != LA.length){
LA[x].out();
x ++;
}}
catch(Exception e){System.out.println(e);}
x = 0;
//else{System.out.println("Error Finding File");}
}}

// ========== //

// This Class Is Here To Simulate An Object
public class String_Object implements java.io.Serializable{
String st;
public String_Object (String xx){
st = xx;
}
public void out(){
System.out.println(st);
}}

[/source] Edited by Shippou
0

Share this post


Link to post
Share on other sites
Looks good to me. Something I would comment on is to flush a output/input stream before closing it.

So Eg:
[source lang="java"]save.writeObject(DA);
save.flush();
save.close();[/source]

This just makes things safer when closing files.

Hope this helped :)

~Ben
0

Share this post


Link to post
Share on other sites
Seems all right to me. There are a few minor issues. Idiomatically one would use a finally block for closing the file streams. A Serializable class should consider having a known serialVersionUID, though this means that you need to be concious when serialized classes become incompatible. You also need to understand that Java will eagerly serialise the entire object graph, thus you need a mechanism for controlling how much of the graph is serialised (using the "transient" keyword) and how to rebuild the full graph from the partially saved graph.

When I used Java in the past for this, I tried to isolate the serialization from the actual objects of interest. That is, I would create an inner serialised class which contained just enough information to re-construct the overall object. This object acted as a kind of "factory", which when passed a "context" object was able to rebuild the full object, including restoring some references that would not be possible to save.

As an example, imagine a simple "game" that consists of little dust motes that spawn at the top of the screen and fade over time. I have just written this code right now, it has neither been compiled nor tested.

Let us imagine we are using some helper classes from other libraries:
[code]
// Possibly from some physics or game library
public class Vec2 {
public float x;
public float y;
}


// Possibly from some game or graphics library
public class Texture {
// ...
}
[/code]
Note that these classes might be provided by a third party and might not be serializable.

Now here is a basic game object class we want to be able to serialize:
[code]
public class DustMote {


private static final float InitialLifetime = 60;

private final Vec2 position = new Vec2();
private final Texture texture;
private float life;

public DustMote(Vec2 position, Texture texture) {
this.position.set(position);
this.texture = texture;
this.life = InitialLifetime;
}

// ...
}
[/code]
You can imagine some simple functionality to decrement the life field as time progresses and to draw the texture in the appropriate position. The actual game logic is irrelevant here.

Let us create a few interfaces to allow us to define what we want to achieve:
[code]
public interface GameContext {
public Texture getTexture(String name);
}


public interface Saveable {
public Restorable save();
}

public interface Restorable extends Serializable {
public Saveable restore(GameContext gameContext);
}
[/code]
The Saveable will be implemented by the game object. The Restorable will be a simple immutable object containing just the fields of interest. The GameContext is the connection that allows us to reconnect the revived objects correctly into the object graph. In this case, it allows the game objects to retrieve other objects, in this case textures.

Here is what our game object might become:
[code]
public class DustMote implements Saveable {


private static final float InitialLifetime = 60;

private final Vec2 position = new Vec2();
private final Texture texture;
private float life;

public DustMote(Vec2 position, GameContext context) {
this(position, InitialLifetime, context);
}

private DustMote(Vec2 position, long life, GameContext context) {
this.position.set(position);
this.texture = context.getTexture("dust-mote");
this.life = life;
}

// ...

@Override
public Restorable save() {
return new DustModeState(this);
}

private static class DustMoteState implements Restorable {

private static final long serialVersionUID = 1L;

private final float x;
private final float y;
private final float life;

public DustMoteState(DustMote dustMote) {
this.x = dustMote.position.x;
this.y = dustMote.position.y;
this.life = dustMote.life;
}

@Override
public DustMote restore(GameContext context) {
Vec2 position = new Vec2(x, y);
return new DustMote(position, life, context);
}
}

}
[/code]
The advantage of this approach is that it separates the serialised state from the current game state. Thus you don't need to weaken the game object's invariants just to support reviving the object. We have also removed the problem of worrying about whether our libraries have taken serialization into account.

When we want to save the game, the game just iterates through each Saveable, calling the save() method - the returned objects can be sent to the ObjectOutputStream. During loading, you can iterate through the ObjectInputStream, casting each returned value to a Restorable and calling the restore() object on it. The returned object would be added to some kind of collection in a "game world" object, or similar.

I'm not saying this is the best way, but it avoids some problems with directly serializing the game objects while being reasonably quick to get up and running, compared to hand writing serialisation routines.
1

Share this post


Link to post
Share on other sites
Thank you for that.

Is there any easy to serialize bufferedImage ?

I think this will work, but haven't tested it yet
[CODE]
public class Image_Storage(BuferedImage Bi implements Serializable{
int width; int height; int[] pixels;
public ImagenPerso(BufferedImage Bi) {
width = Bi.getWidth();
height = Bi.getHeight();
pixels = new int[width * height];
int[] tmp=Bi.getRGB(0,0,width,height,pixels,0,width);
}
public BufferedImage getImage() {
BufferedImage Bi = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
Bi.setRGB(0,0,width,height,pixels,0,width);
return Bi;
}
}
[/CODE]
0

Share this post


Link to post
Share on other sites
[quote name='rip-off' timestamp='1345802441' post='4972924']
Have you considered saving it as a standard image format - e.g. PNG?
[/quote]
What I am trying to do, is condense many images and files that belong together into one file.
Each "glob" file would contain the user sprite sheets, user background tile sheets, user midi files, user made scripts, and user created maps ...

The goal is to easily share data with users over a socket server / client , and add a layer of security to user generated material.

The issues I have to deal with:
1: All user generated material is unique
2: All user generated maps must be accessible to other users using socket server / client
3: All user generated content has to have some sort of protection to make it harder to steal.
4: Normal formats will be .png - .midi
5: Custom formats will be .scr ( custom scripting language i have developed(hashmap) ) - .ovw ( over world map( 2d array) ) - .map ( map files 5 layer 2 array ) - .sho ( shops (hashmap) ) - .itm ( items ( hashmap ) ) - .npc ( NPCs ( hashmap ) ) - .que ( quests ( hashmap ) ) - .eve ( events ( hashmap ) ) - .pls (player statistics ( hashmap ) ) Edited by Shippou
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0