سورس بازی Buble Wrap

شنبه 23 بهمن 1395

در این بازی یک صفحه تشکیل شده است که دارای 3 مرحله ساده و متوسط و سخت است که شما باید حباب را ضربه بزنید دقیقا بازی حباب که برای ضربه گیر وسایل برقی استفاده می شود این بازی شبیه سازی آن شده است.

سورس بازی Buble Wrap

ابتدا در مورد طراحی این اپ بگم که شما از یک گرید ویو برای قرار دادن آیتم ها استفاده می نمایید و داخل پوشه ی drawable از چند تا عکس استفاده می شود زمانی که حباب سالم است از عکس حباب سالم استفاده می کنید و زمانی که حباب را ضربه زدید از حباب که خراب شده است استفاده می کنید یعنی در وافع داخل گرید ویو ها از Imageview استفاده می کنید که با زدن هر کدام عکس تغییر می کند.

از پوشه ای raw هم برای صدا ضربه ی حباب ها استفاده می شود.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"    
    >



        <GridView  xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/gridview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/poppedNumber"
            android:columnWidth="74dp"
            android:gravity="center"
            android:horizontalSpacing="0dp"
            android:numColumns="auto_fit"
            android:stretchMode="spacingWidthUniform"
            android:verticalSpacing="0dp" >
        </GridView>

        <TextView  xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/poppedNumber"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize = "32sp"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:text="@string/popped_number" />

</RelativeLayout>

یک کلاس برای تعریف منوها داریم که سطح بازی را مشخص می کند

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends Activity {

	BubbleGame game;

	public final static String EXTRA_MESSAGE = "com.example.bubblewrap.MESSAGE";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		game = (BubbleGame) this.getApplication();
		game.initializeUi(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.new_game:
			game.newGame(game.currentWrap);
			return true;
		case R.id.large_wrap:
			game.newGame(game.LARGE_WRAP);
			game.currentWrap = game.LARGE_WRAP;
			return true;
		case R.id.medium_wrap:
			game.newGame(game.MEDIUM_WRAP);
			game.currentWrap = game.MEDIUM_WRAP;
			return true;
		case R.id.small_wrap:
			game.newGame(game.SMALL_WRAP);
			game.currentWrap = game.SMALL_WRAP;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/** Called when the user clicks the Send button */
	public void sendMessage(View view) {
		Intent intent = new Intent(this, DisplayMessageActivity.class);
		// EditText editText = (EditText) findViewById(R.id.edit_message);
		// String message = editText.getText().toString();
		// intent.putExtra(EXTRA_MESSAGE, message);
		startActivity(intent);

		// Do something in response to button
	}

}

کلاس دوم برای نمایش عکس هااستفاده می شود:

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {
	private Context mContext;
	private Integer[] bubble_images;

	public ImageAdapter(Context c, Integer[] bubble_images) {
		mContext = c;
		this.bubble_images = bubble_images;
	}

	public int getCount() {
		return bubble_images.length;
	}

	public Object getItem(int position) {
		return null;
	}

	public long getItemId(int position) {
		return 0;
	}

	// create a new ImageView for each item referenced by the Adapter
	public View getView(int position, View convertView, ViewGroup parent) {
		ImageView imageView;
		if (convertView == null) { // if it's not recycled, initialize some
									// attributes
			imageView = new ImageView(mContext);
			imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
			imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
			imageView.setPadding(0, 0, 0, 0);
		} else {
			imageView = (ImageView) convertView;
		}

		imageView.setImageResource(bubble_images[position]);
		return imageView;
	}

	// references to our images

}

کلاس بعدی برای نمایش پیغام ها در هر اکتیویتی است:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class DisplayMessageActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Get the message from the intent
		Intent intent = getIntent();
		String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

		// Create the text view
		TextView textView = new TextView(this);
		textView.setTextSize(40);
		textView.setText(message);

		// Set the text view as the activity layout
		setContentView(textView);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_display_message, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}

کلاس بعدی در مورد دریافت buble ها یا به عبارتی دریافت آیتم است.

public class BubbleWrap {

	private int numberOfBubbles;
	private int poppedBubbles;
	private Integer[] bubbles;

	/*
	 *Constructs a new BubbleWrap
	 *
	 *@param numberOfBubbles the number of bubbles
	 *@param bubble the resource id of unpopped bubble image
	 */
	public BubbleWrap(int numberOfBubbles, int bubble) {
		this.numberOfBubbles = numberOfBubbles;
		this.poppedBubbles = 0;
		this.bubbles = new Integer[numberOfBubbles];
		for (int i = 0; i < numberOfBubbles; i++) {
			bubbles[i] = bubble;
		}

	}
    
	/*
	 * Pops a bubble
	 * @param index the index of the bubble
	 * @param resource id of the image to replace with
	 */
	public void popBubble(int index, int bubble) {

		bubbles[index] = bubble;
		poppedBubbles++;
	}

	/*
	 * @return the number of popped bubbles
	 */
	public int getNumberOfPopped() {
		return poppedBubbles;
	}

	/*
	 * @return the number of bubbles
	 */
	public int getNumberOfBubbles() {
		return numberOfBubbles;
	}

	/*
	 * @return the bubbles
	 */
	public Integer[] getBubbles() {

		return bubbles;

	}

	/*
	 * 
	 * @param the index of a bubble
	 * @param the resource id of the image used
	 * 
	 * @return true if the bubble is not popped 
	 */
	public boolean isBubble(int index, int bubble) {
		if (bubbles[index] == bubble) {
			return true;
		}

		return false;
	}

}

و کلاس آخر هم تعریف تمام متغییر های استفاده شده است و منو های بازی و شروع بازی جدید از اول و تغییر دادن حباب ها است

import java.util.Random;

import android.app.Application;
import android.content.Context;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Vibrator;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;

/*
 * BubbleGame.java  is a the class the handles the gaming action (Popping Bubble Wraps) 
 * 
 * @author Amente Bekele
 * @version 0.1
 * 
 */
public class BubbleGame extends Application implements OnItemClickListener,
		OnScrollListener, OnTouchListener {

	// BubbleWrap sizes
	public int SMALL_WRAP = 100; 
	public int MEDIUM_WRAP = 500;
	public int LARGE_WRAP = 1000;

		
	public int DEFAULT_WRAP = SMALL_WRAP; // The default size (Application starts)
	public int currentWrap = DEFAULT_WRAP;//The currently selected size (Application restored from background) 

	// Sound resources
	private int[] POP_SOUNDS = { R.raw.pop_sound_1, R.raw.pop_sound_2,
			R.raw.pop_sound_3, R.raw.pop_sound_4 };
	private int DRAG_SOUND = R.raw.drag_sound;

	//Image resources
	private int UNPOPPED_BUBBLE = R.drawable.un_popped;
	private int[] POPPED_BUBBLES = { R.drawable.popped_1, R.drawable.popped_2,
			R.drawable.popped_3, R.drawable.popped_4 };

	private Random random = new Random(); // Use for randomly selecting sound and popped images
	private SoundPool sound; // Sound pool used for drag sound
	int[] popSounds; // popSounds
	int dragSound;  // drag Sounds
	int dragSoundStream = 0; 
	private boolean scrollStarted = false;// Is the view bieng scrolled
	Vibrator vibrator; // Device vibrator reference

	private int score; // Score (Number of popped bubbles
	private BubbleWrap bubbleWrap; // BubbleWrap reference

	// UI Elements
	private MainActivity activity; // Main App activity
	private TextView scoreText; 
	private GridView bubbleGrid; 
	

	private ImageAdapter adapter;// Image adapter used for rendering and updating images 

	/* 
	 * Gets the current score  
	 * @return score
	 */
	public int getScore() {
		return bubbleWrap.getNumberOfBubbles() - score;
	}

	/*
	 * Gets the bubble wrap
	 * @return bubbleWrap
	 */
	public BubbleWrap getBubbleWrap() {
		return bubbleWrap;
	}

	@Override
	/*
	 * (non-Javadoc)
	 * @see android.app.Application#onCreate()
	 */
	public void onCreate() {
		super.onCreate();
		bubbleWrap = new BubbleWrap(DEFAULT_WRAP, UNPOPPED_BUBBLE);

	}
     
	/*
	 * (non-Javadoc)
	 * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
	 */
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

		vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

		if (bubbleWrap.isBubble(position, UNPOPPED_BUBBLE)) {
			int n = random.nextInt(POPPED_BUBBLES.length);
			bubbleWrap.popBubble(position, POPPED_BUBBLES[n]);
			vibrator.vibrate(50);
			n = random.nextInt(popSounds.length);
			sound.play(popSounds[n], (float) 1.0, (float) 1.0, 1, 0,
					(float) 1.0);

			score = bubbleWrap.getNumberOfPopped();
			updateUi();
		}

	}

	/*
	 * Initialises the main activity (Renders views)
	 * 
	 */
	public void initializeUi(MainActivity activity) {
		//Get the activity
		this.activity = activity;

		//New image adapter, for the bubbles from the Wrap's GridView
		adapter = new ImageAdapter(activity, bubbleWrap.getBubbles());

		// Set the score text and font
		scoreText = (TextView) activity.findViewById(R.id.poppedNumber);
		scoreText.setText(this.getScore() + "");
		Typeface lcdFont = Typeface.createFromAsset(getAssets(),
				"fonts/LCDM2N__.TTF");
		scoreText.setTypeface(lcdFont);

		
		// Get the grid and attach listeners
		bubbleGrid = (GridView) activity.findViewById(R.id.gridview);
		bubbleGrid.setAdapter(adapter);
		bubbleGrid.setOnItemClickListener(this);
		bubbleGrid.setOnScrollListener(this);
		bubbleGrid.setOnTouchListener(this);
		bubbleGrid.setBackgroundResource(R.color.back_ground);

		// Create the sound pool
		sound = new SoundPool(POP_SOUNDS.length + 1, AudioManager.STREAM_MUSIC,
				0);
		popSounds = new int[POP_SOUNDS.length];

		// Keep reference of the sounds
		for (int i = 0; i < popSounds.length; i++) {
			popSounds[i] = sound.load(activity, POP_SOUNDS[i], 1);
		}

		//Keep reference for the drag sound (Currently Buggy)
		dragSound = sound.load(activity, DRAG_SOUND, 1);

		
	}

	/*
	 * Updates the the user interface 
	 */
	public void updateUi() {

		//Notify the adapter to replace images
		adapter.notifyDataSetChanged();
		//Update the score
		scoreText.setText(this.getScore() + "");
		//Check all bubbles are popped
		checkDone();

	}

	/*
	 * Creates a new game
	 * 
	 * @param size the size of the bubble wrap
	 */
	public void newGame(int size) {
		bubbleWrap = new BubbleWrap(size, UNPOPPED_BUBBLE);
		score = bubbleWrap.getNumberOfPopped();
		adapter = new ImageAdapter(activity, bubbleWrap.getBubbles());
		bubbleGrid.setAdapter(adapter);
		updateUi();

	}
	
	
    /*
     * Checks if the game is over
     */
	public void checkDone() {
		if (this.getScore() == 0) {
			scoreText.setText(R.string.done_text);
		}
	}

	@Override
	/*
	 * (non-Javadoc)
	 * @see android.widget.AbsListView.OnScrollListener#onScroll(android.widget.AbsListView, int, int, int)
	 */
	public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		dragSoundStream = 0;

	}

	@Override
	/*
	 * (non-Javadoc)
	 * @see android.widget.AbsListView.OnScrollListener#onScrollStateChanged(android.widget.AbsListView, int)
	 */
	public void onScrollStateChanged(AbsListView arg0, int arg1) {
		// TODO Auto-generated method stub
		scrollStarted = true;

	}

	@Override
	/*
	 * (non-Javadoc)
	 * @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent)
	 */
	public boolean onTouch(View v, MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_MOVE) {

			dragSoundStream = sound.play(dragSound, (float) 1.0, (float) 1.0,
					1, 0, (float) 1.0);

			return false;
		}
		return false;
	}

}

در آخر خروجی به شکل زیر خواهد بود:

فایل های ضمیمه

برنامه نویسان

نویسنده 3355 مقاله در برنامه نویسان

کاربرانی که از نویسنده این مقاله تشکر کرده اند

در صورتی که در رابطه با این مقاله سوالی دارید، در تاپیک های انجمن مطرح کنید