Android Heroes-puzzle game puzzle-code design and implementation

Source: Internet
Author: User

Last weekend, 3 hours in general read the "Android Heroes", this week mainly in the design and implementation of the code level.
Compiled and installed on the phone, played a few, combined with code, a week to master the overall idea.
Most of the time, it's actually spent on refactoring.
The process of reconstruction is the process of learning and thinking.

This article, is a study summary, the overall introduction of the implementation of this small game ideas.
The back of the time, and then transform the game unreasonable design method, that is, lattice is n*n+1, not n*n.

Write to vomit: In the hundreds of written articles, which have many cases, the more the number of written, the more found that many processes and ideas are consistent.
Therefore, it is necessary to summarize some general knowledge. Write clearly, and then the introduction is much clearer.
The article was initially named "Visual Interface GUI application Development summary: Android, IOS, Web, Swing, Windows development, etc." and is expected to be published before December 7, 2015.

Code Explanation

1. Package Structure

Cn.fansunion.puzzle
--activity
Globalconst.java several global constants
Mainactivity.java Game's entry activity
Activity of the Puzzleactivity.java jigsaw game process
--adapter
Maingridviewadapter.java Game Portal Interface for the GridView adapter that can be understood as a GridView data provider
Puzzlegridviewadapter.java Puzzle Interface for the GridView adapter
--bean
Griditem.java 1 elements in a table
--util
Gameutil.java encapsulates the rules of the game
Imageutil.java Image Processing Tool
Screenutil.java Screen Tools

2. Basic class explanation
Gameutil.java

Ismoveable: Determine whether the picture can be moved, or called "can be exchanged with the space", according to the position in the GridView, determine whether and the space is "adjacent" to it.
Swapitems: Swap the position of 2 GridItem, after judging can be moved
Issuccess: Determine if the current puzzle is complete
Getpuzzlegenerator: Generates a random item, which is the position of the n*n number, disrupting
Cansolve: Determine whether the randomly generated item has a solution, that is, can be moved to swap pictures, restore the "original".
(The design of this place is also more pits.) I currently think that you can generate the initial puzzle in a different way, that is, randomly swapping spaces and surrounding pictures n times. Because "the exchange is reversible", so there is always a solution)

Imageutil.java: 1 pictures, cut into n*n; enlarge the picture.
Screenutil.java: Gets the size and density of the screen.

Griditem.java: The core model of the game puzzle, 1 items in the table, ID, image resource ID, picture resource, easy to draw and game rules implementation.
Maingridviewadapter.java and Puzzlegridviewadapter.java: Inherit Android.widget.BaseAdapter, overloading several methods.

Globalconst.java: Some constants, it's too easy.

3. Process of the game
Game Entrance Mainactivity.java

Core processes:
A. Setting the Body interface
Setcontentview (R.layout.xpuzzle_main);
B. Initializing other interfaces, buttons, etc.
Initviews ();
C. Data adapter
Gridview.setadapter (New Maingridviewadapter (
Mainactivity.this, bitmaplist));
D. Binding events such as buttons, interfaces, etc.
Gridview.setonitemclicklistener
E. Incident response

Important Events
A. Select the game difficulty and save to the Type field. Give the user a "pop-up Dialog" selection.
Selectedtypetextview.setonclicklistener (                new Onclicklistener () {                    @Override public                    void OnClick (View v) {                        //Popup popup window                        popupshow (v);}}                );    }


B. The game comes with several pictures and uses system pictures.
The table shows, item Click Listen, the last 1 pictures, the choice of "This map library or camera shooting", the other pictures directly selected.
Gridview.setonitemclicklistener (New Onitemclicklistener () {            @Override public            void Onitemclick (Adapterview <?> arg0, view view,                                    int position, long Arg3) {                if (position = = photoresourceidarray.length-1) {                    //Select This map library camera                    Showdialogcustom ();                } else {                    //select default Picture                    Intent Intent = new Intent (                            mainactivity.this,                            puzzlemain.class);                    Intent.putextra (globalconst.select_photo_id, photoresourceidarray[position]);                    Intent.putextra (Globalconst.type, TYPE);                    StartActivity (intent);}}        );


This map library and camera take pictures, is 2 sets of similar logic. After the user chooses, call the library camera callback method to save the user's selected picture.
Then it goes to the "puzzle game main Screen".

puzzle Game Main interface Puzzleactivity.java
Core processes:
A. Setting the body layout
Setcontentview (R.layout.xpuzzle_puzzle_detail_main);
B. Get the user-selected picture, and cut the image
Getintent (). Getextras (). GetInt (globalconst.select_photo_id);
C. Initializing other views
Initviews ();
D. Call Gameutil to generate the game's initial data and start the timer. (written here suddenly found, and unreasonable, the timer, should be fully initialized after the completion of the program, and then open.) )
Generategame ();
E. Event binding.
Back button click event
Backbutton.setonclicklistener (this);
Show Original button click event
Imagebutton.setonclicklistener (this);
Reset button Click event
Restartbutton.setonclicklistener (this);

The GridView Click event (In fact this is the most important), the picture can be moved, in the case of being able to move, you need to "swap pictures," "Update the Drawing", "Update steps."
In case of success, subsequent processing (stop timing, etc.)
  Gridview.setonitemclicklistener (New Onitemclicklistener () {@Override public void Onitemclick (ADAP                Terview<?> arg0, view view, int position, long Arg3) {//To determine if movable if (gameutil.ismoveable (position)) {//Exchange click the position of item with space Gameutil.swapi                    TEMs (GameUtil.gridItemList.get (position), gameutil.blankgriditem);                    Re-get Picture Recreatedata ();                    Notifies the GridView to change UI puzzlegridviewadapter.notifydatasetchanged ();                    Update step number stepcount++;                    Stepcounttextview.settext ("" + Stepcount); Determine if successful if (Gameutil.issuccess ()) {//The last picture shows the full recre                        Atedata ();           Bitmapitemlist.remove (TYPE * TYPE-1);             Bitmapitemlist.add (LASTBITMAP);                        Notifies the GridView to change UI puzzlegridviewadapter.notifydatasetchanged ();                        Toast.maketext (Puzzlemain.this, "jigsaw success!", Toast.length_long). Show ();                        Gridview.setenabled (FALSE);                        Timer.cancel ();                    Timertask.cancel (); }                }            }        });


4. Resources
layouts, menus, strings, combined with Java code, are easy to read.


Code Address:
Https://git.oschina.net/fansunion/puzzle

Personal view
The current technology, getting started, to reach the intermediate level, to work and make money, or relatively easy.
After reaching a certain level, to continue to advanced, it is necessary to see the individual understanding of technology.
As for refactoring, code specification, game design, everyone has their own understanding.
Combine the actual situation, and then do the specific consideration.

Android Heroes-puzzle game puzzle-code design and implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.