1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
|
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[i];
}
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));
}
} |
Partager