Home Discussion Discuss: Creating a ZIP file in Java

  • anwerraj September 19, 2011 at 11:06 AM

    package com.Tutorial; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Random; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.media.AudioManager; import android.media.SoundPool; import android.util.Log; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; /** * Custom SurfaceView to handle everything we need from physics to drawings. * * @author martin */ public class Panel extends SurfaceView implements SurfaceHolder.Callback { /** * Thread which contains our game loop. */ private RockScissorsPaperThread _thread; /** * List of graphics we already have to handle. */ private ArrayList<Graphic> _graphics = new ArrayList<Graphic>(); /** * List of explosions we have to draw. */ private ArrayList<Graphic> _explosions = new ArrayList<Graphic>(); /** * The graphic we have while our finger touches the screen. */ private Graphic _currentGraphic; /** * Last coordinates to store the point we first touched the screen. */ private Graphic.Coordinates _lastCoords; /** * Sound pool which allows us to play multiple sounds at once. */ private SoundPool _soundPool; /** * Id of our explosion sound. */ private int _playbackFile = 0; /** * Cache variable for all used images. */ private Map<Integer, Bitmap> _bitmapCache = new HashMap<Integer, Bitmap>(); /** * Constructor called on instantiation. * @param context Context of calling activity. */ public Panel(Context context) { super(context); fillBitmapCache(); _soundPool = new SoundPool(16, AudioManager.STREAM_MUSIC, 100); _playbackFile = _soundPool.load(getContext(), R.raw.explosion, 0); getHolder().addCallback(this); _thread = new RockScissorsPaperThread(this); setFocusable(true); } /** * Fill the bitmap cache. */ private void fillBitmapCache() { _bitmapCache.put(R.drawable.icon, BitmapFactory.decodeResource(getResources(), R.drawable.icon)); _bitmapCache.put(R.drawable.abstrakt, BitmapFactory.decodeResource(getResources(), R.drawable.abstrakt)); _bitmapCache.put(R.drawable.wallpaper, BitmapFactory.decodeResource(getResources(), R.drawable.wallpaper)); _bitmapCache.put(R.drawable.scissors, BitmapFactory.decodeResource(getResources(), R.drawable.scissors)); _bitmapCache.put(R.drawable.paper, BitmapFactory.decodeResource(getResources(), R.drawable.paper)); _bitmapCache.put(R.drawable.rock, BitmapFactory.decodeResource(getResources(), R.drawable.rock)); _bitmapCache.put(R.drawable.smaller, BitmapFactory.decodeResource(getResources(), R.drawable.smaller)); _bitmapCache.put(R.drawable.small, BitmapFactory.decodeResource(getResources(), R.drawable.small)); _bitmapCache.put(R.drawable.big, BitmapFactory.decodeResource(getResources(), R.drawable.big)); } /** * Process the MotionEvent. */ @Override public boolean onTouchEvent(MotionEvent event) { synchronized (getHolder()) { Graphic graphic = null; if (event.getAction() == MotionEvent.ACTION_DOWN) { Random random = new Random(); int rand = Math.abs(random.nextInt() % 3); switch (rand) { case 0: graphic = new Graphic(_bitmapCache.get(R.drawable.scissors)); graphic.setType("scissors"); break; case 1: graphic = new Graphic(_bitmapCache.get(R.drawable.rock)); graphic.setType("rock"); break; case 2: graphic = new Graphic(_bitmapCache.get(R.drawable.paper)); graphic.setType("paper"); break; default: throw new RuntimeException("RANDOM not between 0 and 2: " + rand); } graphic.getCoordinates().setTouchedX((int) event.getX()); graphic.getCoordinates().setTouchedY((int) event.getY()); _lastCoords = new Graphic(_bitmapCache.get(R.drawable.icon)).getCoordinates(); _lastCoords.setTouchedX(graphic.getCoordinates().getTouchedX()); _lastCoords.setTouchedY(graphic.getCoordinates().getTouchedY()); _currentGraphic = graphic; } else if (event.getAction() == MotionEvent.ACTION_MOVE) { _currentGraphic.getCoordinates().setTouchedX((int) event.getX()); _currentGraphic.getCoordinates().setTouchedY((int) event.getY()); } else if (event.getAction() == MotionEvent.ACTION_UP) { // calculating speed calculatingSpeedX((int) event.getX()); calculatingSpeedY((int) event.getY()); _graphics.add(_currentGraphic); _currentGraphic = null; } return true; } } /** * Calculating the speed of the item. * Using the difference between start point and release point with smoothing factor. * * @param currentX X coordinate which represent the last point. */ private void calculatingSpeedX(int currentX) { if (currentX != _lastCoords.getTouchedX()) { int diff = currentX - _lastCoords.getTouchedX(); int amplitude = diff / 10; _currentGraphic.getSpeed().setX(amplitude); } else { _currentGraphic.getSpeed().setX(0); } } /** * Calculating the speed of the item. * Using the difference between start point and release point with smoothing factor. * * @param currentY Y coordinate which represent the last point. */ private void calculatingSpeedY(int currentY) { if (currentY != _lastCoords.getTouchedY()) { int diff = currentY - _lastCoords.getTouchedY(); int amplitude = diff / 10; _currentGraphic.getSpeed().setY(amplitude); } else { _currentGraphic.getSpeed().setY(0); } } /** * Update the physics of each item already added to the panel. * Not including items which are currently exploding and moved by a touch event. */ public void updatePhysics() { Graphic.Coordinates coord; Graphic.Speed speed; for (Graphic graphic : _graphics) { coord = graphic.getCoordinates(); speed = graphic.getSpeed(); // Direction coord.setX(coord.getX() + speed.getX()); coord.setY(coord.getY() + speed.getY()); // borders for x... if (coord.getX() < 0) { speed.setX(-speed.getX()); coord.setX(-coord.getX()); } else if (coord.getX() + graphic.getBitmap().getWidth() > getWidth()) { speed.setX(-speed.getX()); coord.setX(coord.getX() + getWidth() - (coord.getX() + graphic.getBitmap().getWidth())); } // borders for y... if (coord.getY() < 0) { speed.setY(-speed.getY()); coord.setY(-coord.getY()); } else if (coord.getY() + graphic.getBitmap().getHeight() > getHeight()) { speed.setY(-speed.getY()); coord.setY(coord.getY() + getHeight() - (coord.getY() + graphic.getBitmap().getHeight())); } } } /** * Check all items on the panel for collisions and find the winner. * The loser will added to the list of explosions. */ public void checkForWinners() { ArrayList<Graphic> toExplosion = new ArrayList<Graphic>(); for (Graphic grapics : _graphics) { for (Graphic battleGraphic : _graphics) { if (battleGraphic != grapics && !(toExplosion.contains(battleGraphic) || toExplosion.contains(grapics))) { if (!battleGraphic.getType().equals(grapics.getType()) && checkCollision(battleGraphic, grapics)) { if (firstWins(battleGraphic.getType(), grapics.getType())) { toExplosion.add(grapics); _soundPool.play(_playbackFile, 1, 1, 0, 0, 1); } } } else { continue; } } } if (!toExplosion.isEmpty()) { _explosions.addAll(toExplosion); _graphics.removeAll(toExplosion); } } /** * Mathematical calculation of a collision between two items. * * @param first First item. * @param second Second item. * @return Returns true if first and second item hit each other. */ private boolean checkCollision(Graphic first, Graphic second) { boolean retValue = false; int width = first.getBitmap().getWidth(); int height = first.getBitmap().getHeight(); int firstXRangeStart = first.getCoordinates().getX(); int firstXRangeEnd = firstXRangeStart + width; int firstYRangeStart = first.getCoordinates().getY(); int firstYRangeEnd = firstYRangeStart + height; int secondXRangeStart = second.getCoordinates().getX(); int secondXRangeEnd = secondXRangeStart + width; int secondYRangeStart = second.getCoordinates().getY(); int secondYRangeEnd = secondYRangeStart + height; if ((secondXRangeStart >= firstXRangeStart && secondXRangeStart <= firstXRangeEnd) || (secondXRangeEnd >= firstXRangeStart && secondXRangeEnd <= firstXRangeEnd)) { if ((secondYRangeStart >= firstYRangeStart && secondYRangeStart <= firstYRangeEnd) || (secondYRangeEnd >= firstYRangeStart && secondYRangeEnd <= firstYRangeEnd)) { retValue = true; } } return retValue; } /** * True if first type wins, false if second type wins. * * @param firstType Type of the first object. * @param secondType Type of the second object. * @return Returns who wins. */ private boolean firstWins(String firstType, String secondType) { if (firstType.equals("explosion") || secondType.equals("explosion")) { return false; } else if (firstType.equals("scissors") && secondType.equals("paper")) { return true; } else if (firstType.equals("scissors") && secondType.equals("rock")) { return false; } else if (firstType.equals("paper") && secondType.equals("scissors")) { return false; } else if (firstType.equals("paper") && secondType.equals("rock")) { return true; } else if (firstType.equals("rock") && secondType.equals("paper")) { return false; } else if (firstType.equals("rock") && secondType.equals("scissors")) { return true; } else { throw new RuntimeException("Fight not possible!"); } } /** * Draw on the SurfaceView. * Order: * <ul> * <li>Background image</li> * <li>Items on the panel</li> * <li>Explosions</li> * <li>Item moved by hand</li> * </ul> */ @Override public void onDraw(Canvas canvas) { // draw the background canvas.drawBitmap(_bitmapCache.get(R.drawable.abstrakt), 0, 0, null); Bitmap bitmap; Graphic.Coordinates coords; // draw the normal items for (Graphic graphic : _graphics) { bitmap = graphic.getBitmap(); coords = graphic.getCoordinates(); canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null); } // draw the explosions ArrayList<Graphic> finishedExplosion = new ArrayList<Graphic>(); for (Graphic graphic : _explosions) { if (!graphic.getType().equals("explosion")) { graphic.setType("explosion"); graphic.setExplosionStep(0); graphic.getSpeed().setX(0); graphic.getSpeed().setY(0); graphic.setBitmap(_bitmapCache.get(R.drawable.smaller)); bitmap = graphic.getBitmap(); coords = graphic.getCoordinates(); canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null); } else { switch (graphic.getExplosionStep()) { case 10: bitmap = _bitmapCache.get(R.drawable.small); graphic.setBitmap(bitmap); break; case 20: bitmap = _bitmapCache.get(R.drawable.big); graphic.setBitmap(bitmap); break; case 30: bitmap = _bitmapCache.get(R.drawable.small); graphic.setBitmap(bitmap); break; case 40: bitmap = _bitmapCache.get(R.drawable.smaller); graphic.setBitmap(bitmap); break; default: bitmap = graphic.getBitmap(); } coords = graphic.getCoordinates(); canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null); graphic.setExplosionStep(graphic.getExplosionStep() + 1); } if (graphic.getExplosionStep() > 50) { finishedExplosion.add(graphic); } } // remove all Objects who are already fully exploded... if (!finishedExplosion.isEmpty()) { _explosions.removeAll(finishedExplosion); } // draw current graphic at last... if (_currentGraphic != null) { bitmap = _currentGraphic.getBitmap(); coords = _currentGraphic.getCoordinates(); canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null); } } /** * Called if you change the configuration like open the keypad. */ @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } /** * Called on creation of the SurfaceView. * Which could be on first start or relaunch. */ @Override public void surfaceCreated(SurfaceHolder holder) { if (!_thread.isAlive()) { _thread = new RockScissorsPaperThread(this); } _thread.setRunning(true); _thread.start(); } /** * Called if the SurfaceView should be destroyed. * We try to finish the game loop thread here. */ @Override public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; _thread.setRunning(false); while (retry) { try { _thread.join(); retry = false; } catch (InterruptedException e) { // we will try it again and again... } } Log.i("thread", "Thread terminated..."); } }

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
Related Articles
JSP Servlet Questions

convert a file .doc to .zip
language="java" %> <HTml> <HEAD><TITLE>Display file upload form...convert a file .doc to .zip  hiii, I uploaded a file with extension .doc now i required with .zip   Hi Friend, Try the following code 

Java Technology Tutorials

Java file zip
Java file zip In this section, you will learn how to create a zip file. The ZIP file format is used for the distribution and storage of files... the zip file. Now to create a zip file, we have used the package java..util.zip. 


Creating a ZIP file in Java
Creating a ZIP file in Java       Zip File: Zip file format is the popular method of data compression. Zip file contains many files in compressed format. You can 


Create zip file in Java
Create zip file in Java     .... You will also learn how to create a zip file from any file through the java... applications. This program shows you how to zip any file through your java 


Unzip a ZIP File
the zip file. ZipEntry: This is the class of java.util.zip.*; package of Java... Unzip a ZIP File       How to unzip (extract) a zip file? How to retrieve elements from 


How to extract zip file in java.
How to extract zip file in java. In this Example, we will discuss how to extract a ZIP file. We will use ZipInputStream class for creating input stream that take input from ZIP file. The ZipInputStream class is available 


Create zip file in Java

Java Tips and Examples

Zip File Using Java
; This example shows how to create a zip file in java. In other words, we..., WinZip etc. It is also possible to zip and unzip the files from your Java applications. This example shows how we zip a file through a java program 


Listing Contents of a ZIP File
of a zip file through the java code. Following program helps you for the appropriate... Listing Contents of a ZIP File     ... list of elements present in the zip file format. Program Result: This program 

Programming Tutorials

How to make a zip file in java
Description: In this example we will discuss about how to create zip file from the text file. In the following code  ZipOutputStream class from... zip file. Code: import java.io.*; import java.util.zip. 

Java Beginners

How to create a zip file and how to compare zip size with normal text file
How to create a zip file and how to compare zip size with normal text file .../ZipCreateExample.shtml but when i verified the size of zip and normal file,normal file is showing as 12 bytes and zip file was showing 150bytes in Dos prompt.Is there any error 

Programming Tutorials

Show all the entries of zip file.
Show all the entries of zip file. In this tutorial, We will  discuss how to show all the entries of a zip file.  The ZipFile   class is used...; returns enumeration of zip file entries. The getName() method 

Core Java

Java Zip Package
Java Zip Package      ... and writing the standard and compressed files or archives in the ZIP and GZIP file formats. Basically, ZIP file forms for the JAR file format, so it is easier 

JDK 6 Tutorials

Changes in Jar and Zip
in the file you get the different result. ZIP File Names - Java SE 6...; At the time of creating a jar, we have the ability in executable jar file... value in the jar file's manifest. There are some changes in ZIP File also 

Programming Tutorials

How to generate hash code of Zip file.
C:\>java ZipHashCode Name of Zip file : bharat.txt...How to generate hash code of Zip file. In this tutorial, we will see how to generate hash code of zip file entries. The ZipFile   class is used to read 

JSP Servlet Questions

sending a zip file to servlet
sending a zip file to servlet  I have created a .zip file in a servlet on the local system(no static ip). The .zip file contains xml files. I have to send it to another servlet which is in a server(has a static ip). I have done 

Java Beginners

schedule zip
schedule zip  Java Code to automatically get and zip only .txt files from folders for every 5 days and also to send the zip files to database tables 

Programming Tutorials

Java zip package - Learn how to use java zip package.
Java zip package In this section we will learn about java.util.zip package of java library. We will also learn how to use the zip API to create and read the zip and gzip files within java program. The zip format is very easy method 

PHP Tutorial

Read a zip file.
in reading a zip file. First select a file to be opened. Name that file into zip file and direct the zipread command to read it through while loop. The zip_entry..., it will executed and file will be closed.  <?php $zipname = zip_open(" 

Java Beginners

How to convert multiple files in java to .zip format
How to convert multiple files in java to .zip format  i receive...(); } out.close(); fout.close(); System.out.println("Zip File is created...); } i want to convert the data from inputStream into Zip Stream and so 

Java Beginners

convert zip file to byte array
convert zip file to byte array  Hi,How to convert zip file to byte array,can you please provide program?? Thanks, Ramanuja 

HTML Questions

How to zip a file using javascrip?
How to zip a file using javascrip?  hi.. can anyone tell me How to zip a file using javascrip 

PHP Tutorial

Create a new zip file in ZipArchive.
Creating a new Zip file in ZipArchive For creating zip file, use zipArchive () class. Create a new zip file in ZipArchive. Use the conditional statement... will generate a new zip file, in case of failure, it will print failed in creating 

Java Beginners

Java Util Zip. Zip files/folders inside a folder, without zipping the original source folder.
Java Util Zip. Zip files/folders inside a folder, without zipping the original... srcFile, ZipOutputStream zip) throws Exception { File folder = new File... TEMP and zip into a file named Final.jar located in the folder Final. Now 

WebSevices Questions

zip file upload in php - WebSevices
zip file upload in php  This is not a normal upload. we know the code for normal upload. i need the zip file upload code in php. how to upload zipfile using php? and how to unzip using php? please i dont 

Mobile Applications Questions

Read file zip in J2ME - MobileApplications
Read file zip in J2ME  I would like to read file.zip in J2ME,I don't know how to extract it. Please help me 

Java Beginners

Issue in Converting .zip file to .jar file?
Issue in Converting .zip file to .jar file?  I have a folder called "printpdf.jar". I have changed the .jar to .zip and did some customizations. After which i had "zipped" it again and made as ".jar". Now the final file 

Spring Framework Questions

Where to download spring framework zip file?
Where to download spring framework zip file?  Hi, I am trying to find the link to download the full distribution zip file of the Spring Framework.... Can anyone tell me the url from where I can download the full zip file 

Development process Questions

find zip file length lessthen 5MB
find zip file length lessthen 5MB  import java.io.BufferedReader...(); } else{ System.out.println("zip file...; } } System.out.println("Zip File 

JSP Servlet Questions

password protected zip file creation exmpale coded neaded - JSP-Servlet
password protected zip file creation exmpale coded neaded  am able to create a zip file and able to read the file but password protection need please help