الفريق العربي للبرمجةأرشيف المنتديات · 2000 – 2023
نسخة أرشيفية للقراءة فقط — التسجيل والمشاركة مغلقان، والمحتوى محفوظ كما كان.

حفظ اللعبة

بدأه nourkhan في 8 يوليو 2011 · 10 رد · 736 مشاهدة · في JavaSE
مشاركة: واتساب X فيسبوك تيليجرام
#1 صاحب الموضوع

السلام عليكم ورحمة الله وبركاته.

اريد من فضلكم حفظ اللعبة حتى يتسنى فتحها تانية .

شكرا لكم.

IG.rar

#2

يمكنك حفظ أي لعبة أو أي Object مهما كان نوع هذا الـ Object بصيغة dat.

فلنفرض أنك تريد حفظ Object من نوع ObjectType، يمكنك حفظ هذا الـ Object أو استيراده بالكود التالي:

public class MyGame implements Serializable
{
    private static void saveGame(ObjectType YourObject, String filePath) throws IOException
    {
        ObjectOutputStream outputStream = null;
        try
        {
            outputStream = new ObjectOutputStream(new FileOutputStream(filePath));
            outputStream.writeObject(YourObject);
        }
        catch(FileNotFoundException ex)
        {
            ex.printStackTrace();
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            try
            {
                if(outputStream != null)
                {
                    outputStream.flush();
                    outputStream.close();
                }
            }
            catch(IOException ex)
            {
                ex.printStackTrace();
            }
        }
    }

    public static ObjectType loadGame(String filePath) throws IOException
    {
        try
        {
            FileInputStream fileIn = new FileInputStream(filePath);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            return (ObjectType) in.readObject();
        }
        catch(FileNotFoundException ex)
        {
            ex.printStackTrace();
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }
    }
}

تم تعديل هذه المشاركة بواسطة Eng.Fouad في 8 يوليو 2011 في 17:38

597657.png
#3

جزاك الله خيرا اخي الكريم، كيف يمكنني تحفيظ اللعبة عن طريق listener؟

هل هذا الكود صحيح؟

public class ActionSaveGame extends MenuListener{

   public ActionSaveGame(PuzzleIG jigsawFrame) {
		super(jigsawFrame);
	}


	public void actionPerformed(ActionEvent arg0) {
		int answer = JOptionPane.showConfirmDialog(
			jigsawFrame,
			"Etes-vous sûr de vouloir enregistrer?",
			null,
			JOptionPane.YES_NO_OPTION);

                if (answer == JOptionPane.YES_OPTION) {


                    ;(MyGame.saveGame(Mygame p, String filePath  


		}
	}
#4

أعتقد صحيح

هل هناك أي مشاكل؟

تحياتي

حزمة المحرك الإصدارة 0.8

أي أحد يجد أني ظلمته فليراسلني

وبإذن الله لو كان له حق سيأخذه

728x90.png

#5

يتم اظهار رسالة missing return statement فيما يخص الدالة: loadGame لماذا؟

#6
    public static ObjectType loadGame(String filePath) throws IOException,FileNotFoundException    {
            FileInputStream fileIn = new FileInputStream(filePath);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            return (ObjectType) in.readObject();
    }
}

تحياتي

حزمة المحرك الإصدارة 0.8

أي أحد يجد أني ظلمته فليراسلني

وبإذن الله لو كان له حق سيأخذه

728x90.png

#7

نفس المشكل اخي الكريم :(

 public static Piece loadGame(String filePath) throws IOException,FileNotFoundException    {
            FileInputStream fileIn = new FileInputStream(filePath);
            ObjectInputStream in = new ObjectInputStream(fileIn);
        try {
            return (Piece) in.readObject();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Piece.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
#8

بنفس الطريقة الذي قمت بها بحل المشكلة في الشيفرة الخاصة بالأخ فؤاد

أزيلي الـ try-catch واستبدليها بجزء من throw في تعريف الدالة

تحياتي

حزمة المحرك الإصدارة 0.8

أي أحد يجد أني ظلمته فليراسلني

وبإذن الله لو كان له حق سيأخذه

728x90.png

#9

هذه هي المصفوفة التي اقوم بتحفيظها، ولكن عندما اقوم بفتح الملف الذي قمت بتحفيظه لا يتم فتحه!!!!!

package puzzle;

import java.awt.*;
import java.awt.image.*;
import java.util.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;




/**
 * dans chaque piece on sait comment les bords doivent êtres dessiner et les pieces aussi voisines
 */
public class Piece implements Serializable
{


        //un id qui represente l'id de la piece suivante
	private static int nextId = 0;


        //une piece doit être proche de ca voisine par ce nombre de pixel
	public static final int posClose = 7;


        //une piece doit être comprise dans cette marge pour être considere comme alignée avec sa voisine
	public static final int rotClose = 5;


	/*
         * creation de nouveau piece
   	 * @param data        image data
   	 * @param imageX      position X de l'image par rapport au puzzle entier
   	 * @param imageY      position Y de l'image par rapport au puzzle entier
   	 * @param imageWidth  la largeur de l'image de la piece
   	 * @param imageHeight la hauteur de l'image de la piece
   	 * @param totalWidth  la largeur de l'image entiere
   	 * @param totalHeight la heuteur de l'image entiere
   	 */
	protected Piece(int[] data, int imageX, int imageY, int imageWidth, int imageHeight, int totalWidth, int totalHeight)
	{
		id = nextId++;
		neighbors = new HashSet();
		this.curWidth  = this.origWidth  = imageWidth;
		this.curHeight = this.origHeight = imageHeight;
		origData = data;    	
    	this.imageX = imageX;
    	this.imageY = imageY;
    	this.totalWidth = totalWidth;
    	this.totalHeight = totalHeight;

    	// calculer le hash code:
    	if (data != null) {
    		int temp = 0;
    		for(int i = 0; i < data.length; i++) {
	    		temp += data;
    		}
    		this.hash = temp;
    	} else {

    		this.hash = 0;
    	}
	}

	/** 
	 * @param rotation    initial rotation
	 */
	public Piece(int[] data, int imageX, int imageY, int imageWidth, int imageHeight, int totalWidth, int totalHeight, int rotation)
	{
		this (data, imageX, imageY, imageWidth, imageHeight, totalWidth, totalHeight);
    	forceSetRotation (rotation);
	}

	//constructeur de copie
	public Piece(Piece p) {
		this(p.getOrigData(), p.getImageX(), p.getImageY(), 
		p.getImageWidth(), p.getImageHeight(), p.getTotalWidth(), p.getTotalHeight(), p.getRotation());
	}

       /* public static void sauve(String fichier, Piece p) throws Exception {
            FileOutputStream fos = new FileOutputStream(fichier);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(p);
            oos.close();
            fos.close();
        }*/
        //Id de la piece
	protected int id;


        //Emplacement dans l'image
  	int imageX, imageY;


        // Taille de l'image.
  	int totalWidth, totalHeight;


        //Emplacement dans l'image ajuster par la rotation actuel
  	int rotatedX, rotatedY;


        //les pieces considerés comme voisin de celle-ci
        //Seulement les pieces qui peuvent être collée
  	protected Set neighbors;


        //la taille de l'image original
  	protected int origWidth, origHeight;


  	int[] origData;


        //la taille actuel apres totation
  	protected int curWidth, curHeight;
  	int[] curData;


        //emplacement dans le pannel
  	int puzzleX, puzzleY;


        //dernier point cliquer
	int transX, transY;

	/** constante hash code de la piece. */
	protected int hash;


        //image de la piece
  	Image image;


        //une rotation entre 0-359 dans le sens horlogique
  	int rotation;

  	//------------------------------------------------------------


        //retourner l'id de la piece
  	public int getId() {return id;}


         //retourne la rotation actuelle de la piece
   	 public int getRotation() { return rotation; }

  	/**si la rotation actuelle est differente, le data de l'image sera recalculer
  	 * @throws IllegalArgumentException si la rotation n'est pas entre [0,359]
  	 */
  	public void setRotation (int rot)
  	{
  		if (rot == rotation) return;
  		forceSetRotation (rot);
  	}

  	/** definir la rotation de la piece
         * cette methode force le recalcule de l'image
  	 * @throws IllegalArgumentException si la rotation n'est pas entre [0,359]
  	 */
  	protected void forceSetRotation (int rot)
  	{
  		if ((rot < 0) || (rot > 359)) throw new IllegalArgumentException("rotation invalide: "+rot);
  		// ne permettre qu'une roation de 0, 90, 180, 270.
  		if (rot % 90 != 0) {
  			int newRot = rot / 90;
  			System.out.println ("rotation invalide "+rot+"; utiliser plutot "+newRot);
  			rot = newRot;
  		}
  		rotation = rot;
  		recomputeImageData();
  		if (image != null) image.flush();
  		image = Toolkit.getDefaultToolkit().createImage (
  		new MemoryImageSource (curWidth,curHeight, curData, 0, curWidth));
  	}

  	// Fulshe sert a vider le buffer
  	public void flushImage() {
  		if (image!= null) {
  			image.flush();
  		}
		image = Toolkit.getDefaultToolkit().createImage (
				new MemoryImageSource (curWidth,curHeight, curData, 0, curWidth));
  	}

  	/*
         * la position des pieces par rapport au puzzle
  	 */
  	public void setPuzzlePosition (int x, int y)
  	{
  		this.puzzleX = x;
  		this.puzzleY = y;
  	}
        //************************
        //      Save Game
        //************************
  	public static void saveGame(Piece p, String filePath) throws IOException
    {
        ObjectOutputStream outputStream = null;
        try
        {
            outputStream = new ObjectOutputStream(new FileOutputStream(filePath));
            outputStream.writeObject(p);
        }
        catch(FileNotFoundException ex)
        {
            ex.printStackTrace();
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            try
            {
                if(outputStream != null)
                {
                    outputStream.flush();
                    outputStream.close();
                }
            }
            catch(IOException ex)
            {
                ex.printStackTrace();
            }
        }
    }

        //********************
        //  load Game
        //********************
 public static Piece loadGame(String fichier) throws Exception {
        FileInputStream fis = new FileInputStream(fichier);
        ObjectInputStream ois = new ObjectInputStream(fis);
        Piece p = (Piece) ois.readObject();
        ois.close();
        fis.close();
        return p;
    }






  	/*
         * retourne la hauteur actuelle de la piece en pixel
  	 */
  	public int getCurrentHeight() { return curHeight; }


        /*
         * retourne la largeur actuelle de la piece en pixel
  	 */
  	public int getCurrentWidth() { return curWidth; }

  	/** Retourne la largeur de toute l'image dans son orientation actuelle . */
  	public int getTotalWidth() { return totalWidth; }

  	/** Retourne la hauteur de toute l'image dans son orientation actuelle */
  	public int getTotalHeight() { return totalHeight; }

  	/*
         * Retourne la hauteur de la piece dans son orientation original.
  	 */
  	public int getImageHeight() { return origHeight; }

  	/*
         * Retourne la largeur de la piece dans son orientation original.
  	 */
  	public int getImageWidth() { return origWidth; }


        /**Retourne la position X de la piece dans l'image originale.*/
  	public int getImageX() { return imageX; }


         /**Retourne la position Y de la piece dans l'image originale.*/
  	public int getImageY() { return imageY; }


        /**Retourne la position X de la piece dans l'image originale modifier par sa rotation actuelle.*/
  	public int getRotatedX() { return rotatedX; }


         /**Retourne la position Y de la piece dans l'image originale modifier par sa rotation actuelle.*/
  	public int getRotatedY() { return rotatedY; }


        /*Retourne la position X  dans l'image originale modifier par la rotation donnée*/
  	public int getRotatedX(int rotation) { return rotatedX; }


        /*Retourne la position Y  dans l'image originale modifier par la rotation donnée*/
  	public int getRotatedY(int rotation) { return rotatedY; }


        /*Retourne la position X dans le puzzle*/
  	public int getPuzzleX() { return puzzleX; }

  	/*Retourne la position Y dans le puzzle*/
        public int getPuzzleY() { return puzzleY; }

  	/** Retourne thie Piece's transX  */
  	public int getTransX() {return transX; }
        //retourne la derniere position X du clique sur la piece
  	public void setTransX(int x) {transX = x;}

	/** Retourne Piece's transY */
	public int getTransY() {return transY; }
        //retourne la derniere position Y du clique sur la piece
	public void setTransY(int y) {transY = y;}

  	public HashSet getNeighbors() {
  		return (HashSet)neighbors;
  	}

  	public void setNeighbors(HashSet neighbors) {
  		this.neighbors = neighbors;
  	}
  	/*
         * retourne l'image de la piece actuelle.
  	 */
  	public Image getImage () { return image; }


        /*Retourne le data de la piece actuelle*/
  	public int[] getCurrData() {return curData;	}
  	public void setCurrData(int[] data) { curData = data; }

	/** retourne le data original de la piece */
  	public int[] getOrigData() {
  		return this.origData;
  	}
  	public void setOrigData(int[] data) {
  		this.origData = data;
  	}


  	public int hashCode() {
  		return hash+rotation;
  	}


  	/**
         * ajouter une piece au voisinage de ces pieces
  	 * @throws NullPointerException s il n existe pas de voisin
  	 */
  	public void addNeighbor (Piece neighbor)
  	{
  		if (neighbor == null) throw new NullPointerException ("pas de voisins");
  		neighbors.add (neighbor);
  	}


        //supprimer la piece donnée des voisins de la piece
  	public void removeNeighbor (Piece neighbor) 
  	{
  		neighbors.remove (neighbor); 
  	}


        // deplacer la piece en cours a la position indiquée sur le jpannel
  	public void moveTo (int x, int y)
  	{ 
  		setPuzzlePosition (x, y); 
  	}



        //dessiner la piece dans dans l'objet graphique donné
        //cette image sera dessiner dans la position en cours de la piece.
  	protected void draw (Graphics g)
  	{
  		Image img = getImage();
  		if (img != null) g.drawImage (img, getPuzzleX(), getPuzzleY(), null);
  	}


        //retourn si la piece en cours contient le point donné
  	public boolean contains (int x, int y)
  	{
  		int puzX = getPuzzleX();
  		int puzY = getPuzzleY();
  		int w = getCurrentWidth();
  		int h = getCurrentHeight();

  		return (puzX <= x) && (x <= (puzX+w-1)) && (puzY <= y) && (y <= (puzY+h-1)) &&
  			   (getAlpha(x-puzX, y-puzY) != 0);
  	}


        //retourne la valeur de alpha (transparence) du point donné de l'image en cours
  	protected int getAlpha (int x, int y)
  	{
  		int pixel = curData[y*curWidth + x];
  		return (pixel >> 24) & 0xff;
  	}


        //verifier si la piece en cours est situé et orienté assez proche de la piece donnée pour se coller
  	public boolean isCloseTo (Piece piece)
  	{

            //verifier si les pieces sont allignées
  		int rot = getRotation();
  		int rotD = Math.abs (piece.getRotation() - getRotation());
  		rotD = Math.min (rotD, 360-rotD);
  		if (rotD > rotClose) return false;

                //si on est ici alors c que les pieces sont bien allignées
  		int puzXD = getPuzzleX() - piece.getPuzzleX();
  		int puzYD = getPuzzleY() - piece.getPuzzleY();
  		int rotXD = getRotatedX() - piece.getRotatedX(rot);
  		int rotYD = getRotatedY() - piece.getRotatedY(rot);
  		return (Math.abs(puzXD-rotXD) <= posClose) && (Math.abs(puzYD-rotYD) <= posClose) ;

  	}

  	// joindre les pieces -------------------------------------------------------

  	/*
         * Vérifie si l'un des voisins de cette pièce sont situées et orientées
         * suffisament pour être joint à celui-ci.
         * @ retourne un tableau des pièces, ou nulle s'ils n'étaient pas assez de voisins proches;
         * si le tableau est non-nul, la premiere piece sera la nouvelle.
  	 */
  	public Piece[] join ()
  	{
  		ArrayList close = new ArrayList();
  		Iterator iter = neighbors.iterator();
  		while (iter.hasNext()) {
  			Piece piece = (Piece) iter.next();
  			if (piece.isCloseTo (this)) 
  			{
  				close.add (piece);
  			}
  		}
  		if (close.size() == 0) return null;

  		Piece newPiece = MultiPiece.join (this, close);
  		Piece[] ret = new Piece[close.size()+2];
  		ret[0] = newPiece;
  		ret[1] = this;
  		this.image.flush();
  		for (int i = 0; i < close.size(); i++) {
  			Piece piece = (Piece) close.get(i);
  			ret[i+2] = piece;
  			piece.image.flush();
  		}
  		System.gc();
  		return ret;
  	}


  	/*
         * 4 position de rotation
         * definir la position d'une piece en se basant sur sa rotaton actuelle
         *
  	 */
  	protected void setRotatedPosition()
  	{
  		int rot = getRotation();
  		switch (rot) {
  			case   0:	rotatedX =  imageX;
                                        rotatedY =  imageY;
  					curWidth = origWidth;
                                        curHeight = origHeight;
  						break;
  			case  90:       rotatedX = totalHeight-imageY-origHeight;
                                        rotatedY = imageX;
                                        curWidth = origHeight;
                                        curHeight = origWidth;
  						break;
  			case 180:	rotatedX = totalWidth -imageX-origWidth;
  					rotatedY = totalHeight-imageY-origHeight;
  					curWidth = origWidth;
                                        curHeight = origHeight;
  						break;
  			case 270:	rotatedX =  imageY;
  					rotatedY = totalWidth -imageX-origWidth;
  					curWidth = origHeight;
                                        curHeight = origWidth;
  						break;
  			default:    System.out.println ("rotation non permise: "+rot);
  		}
  	}

  	/*
         * recalculer les pixels de l'image et sa taille a partir des données original de l'image et sa rotation
  	 */

  	public void recomputeImageData()
  	{
  		setRotatedPosition();
  		if (rotation == 0) {
  			curData = (int[]) origData.clone();
  		} else if (rotation == 90) {
  			curData = new int[origData.length];
  			for (int i = 0; i < curWidth; i++) {
  				for (int j = 0; j < curHeight; j++) {
  					try {
  						curData[j*curWidth+i] = origData[(origHeight-i-1)*origWidth + j];
  					} catch (ArrayIndexOutOfBoundsException ex) {

  						throw new NullPointerException();
  					}
  				}
  			}
  		} else if (rotation == 180) {
  			curData = new int[origData.length];
  			for (int i = 0; i < curWidth; i++) {
  				for (int j = 0; j < curHeight; j++) {
  					curData[j*curWidth+i] = origData[(origHeight-j-1)*origWidth + (origWidth-i-1)];
  				}
  			}
  		} else if (rotation == 270) {
  			curData = new int[origData.length];
  			for (int i = 0; i < curWidth; i++) {
  				for (int j = 0; j < curHeight; j++) {
  					curData[j*curWidth+i] = origData[i*origWidth + (origWidth-j-1)];
  				}
  			}
  		} 

  		image = Toolkit.getDefaultToolkit().createImage (
  			new MemoryImageSource (curWidth,curHeight, curData, 0, curWidth));
  	}
}

اقوم باستدعاء الدوال المعرفة في مصفوفة Piece عن طريق:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package puzzle.gui.listeners;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JOptionPane;
import puzzle.Piece;

import puzzle.gui.*;


public class ActionSaveGame extends MenuListener{
    Piece p;

   public ActionSaveGame(PuzzleIG jigsawFrame) {
		super(jigsawFrame);
	}


	public void actionPerformed(ActionEvent arg0) {
		int answer = JOptionPane.showConfirmDialog(
			jigsawFrame,
			"Etes-vous sûr de vouloir enregistrer?",
			null,
			JOptionPane.YES_NO_OPTION);

                if (answer == JOptionPane.YES_OPTION) {
            try {
                Piece.saveGame(p, "monFichier.svg");
            } catch (IOException ex) {
                Logger.getLogger(ActionSaveGame.class.getName()).log(Level.SEVERE, null, ex);
            }


		}
	}



}

و

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package puzzle.gui.listeners;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JOptionPane;
import puzzle.Piece;
import puzzle.gui.*;

/
public class ActionOpenGame extends MenuListener{

    Piece p;

   public ActionOpenGame(PuzzleIG jigsawFrame) {
		super(jigsawFrame);
	}


public void actionPerformed(ActionEvent arg0) {
		int answer = JOptionPane.showConfirmDialog(
			jigsawFrame,
			"Etes-vous sûr de vouloir ouvrir le jeu?",
			null,
			JOptionPane.YES_NO_OPTION);

                if (answer == JOptionPane.YES_OPTION) {

                        Piece.loadGame("monFichier.svg");

                }




}



}
#10

السلام عليكم ورحمة الله وبركاته،

لقد وجدت هذه الطريقة لكن لاأعرف كيف استعملها عن طريق listeners

private class PieceData implements Serializable {
			public int[] origData;
			public int[] curData; 
        }

	private void writeObject(ObjectOutputStream out) throws IOException {
		out.writeInt(this.getId());
		out.writeInt(this.getImageX());
		out.writeInt(this.getImageY());
		out.writeInt(this.getTotalWidth());
		out.writeInt(this.getTotalHeight());
		out.writeInt(this.getRotatedX());
		out.writeInt(this.getRotatedY());
		out.writeInt(this.origWidth);
		out.writeInt(this.origHeight);
		out.writeInt(this.curWidth);
		out.writeInt(this.curHeight);

		// #$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#		
		// That is the way I found to send the int[] piece's data:
		PieceData pd = new PieceData();
		pd.origData = this.origData;
		pd.curData = this.curData;
		out.writeObject(pd);
		// #$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#

		out.writeInt(this.puzzleX);
		out.writeInt(this.puzzleY);
		out.writeInt(this.transX);
		out.writeInt(this.transY);
		out.writeInt(this.rotation);

		out.writeInt(this.hash);

		out.writeObject(this.neighbors);
		return;
	}

	private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
		this.id = in.readInt();
		this.imageX = in.readInt();
		this.imageY = in.readInt();
		this.totalWidth = in.readInt();
		this.totalHeight = in.readInt();
		this.rotatedX = in.readInt();
		this.rotatedY = in.readInt();
		this.origWidth = in.readInt();
		this.origHeight = in.readInt();
		this.curWidth = in.readInt();
		this.curHeight = in.readInt();


		// #$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#		
		// That is the way I found to send the int[] piece's data:		
		PieceData pd = (PieceData)in.readObject();
		this.origData = pd.origData;
		this.curData = pd.curData;
		// #$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#$%#

		this.puzzleX = in.readInt();
		this.puzzleY = in.readInt();
		this.transX = in.readInt();
		this.transY = in.readInt();
		this.rotation = in.readInt();

		this.hash = in.readInt();

		this.neighbors = (Set)in.readObject();

		this.image = Toolkit.getDefaultToolkit().createImage(
				new MemoryImageSource (curWidth,curHeight, curData, 0, curWidth));
		if(image!=null) image.flush();
	}
#11

السلام عليكم

هل لابد من ان تكون الدالة writobjet() و readobjet() معا static حتى اتمكن من تنفيدها عن طريق listener؟

شكرا

مواضيع مشابهة