Android Game source Sharing 2048_android

Source: Internet
Author: User
Tags getcolor gety

Introduction

  程序猿们,是否还在为你的老板辛辛苦苦的打工而拿着微薄的薪水呢,还是不知道如何用自己的应用或游戏来赚钱呢!  
在这里IQuick将教您如何同过自己的应用来赚取自己的第一桶金!  
你是说自己的应用还没有做出来?  
不,在這里已经为你提供好了一个完整的游戏应用了,在文章的下面有源码的地址哦。你只要稍做修改就可以变成一个完全属于自己的应用了,比如将4*4换成5*5,甚至是其它的。如果你实在是慵懒至极的话,你只要将本应用的包名及广告换成自己的,就可以上传到市场上轻轻松松赚取自己的第一桶金了。  
如果你觉得本文很赞的话,就顶一下作者吧,从下面的安装地址中下载应用,或者在导入本工程运行的时候,从广告中安装一个应用。动一动你的手指,就能让作者更进一步,也能让作者以后更加有动力来分享吧。

Installation



Project structure

Important Code Interpretation Mainview game's main class

Initialization method, which initializes a number of constants, font color, such as name= "code" class= "Java" >public Mainview (context) {super (context);
    Resources of resources = context.getresources ();
    Loading game = new Maingame (context, this);
      try {//getting Assets backgroundrectangle = resources.getdrawable (R.drawable.background_rectangle);
      Lightuprectangle = resources.getdrawable (R.drawable.light_up_rectangle);
      Faderectangle = resources.getdrawable (R.drawable.fade_rectangle);
      Text_white = Resources.getcolor (r.color.text_white);
      Text_black = Resources.getcolor (R.color.text_black);
      Text_brown = Resources.getcolor (R.color.text_brown);
      This.setbackgroundcolor (Resources.getcolor (R.color.background));
      typeface font = Typeface.createfromasset (Resources.getassets (), "Clearsans-bold.ttf");
      Paint.settypeface (font);
    Paint.setantialias (TRUE);
    catch (Exception e) {System.out.println ("Error getting assets?"); } SetontouchlisTener (This) (new Inputlistener);
  Game.newgame (); ///game interface drawing @Override protected void onsizechanged (int width, int height, int oldw, int oldh) {Super.onsizecha
    Nged (width, height, oldw, OLDH);
    GetLayout (width, height);
    Createbitmapcells ();
    Createbackgroundbitmap (width, height);
  Createoverlays ();
 }


miangame Game primary logic

Package com.tpcstld.twozerogame;
Import Android.content.Context;
Import android.content.SharedPreferences;

Import Android.preference.PreferenceManager;
Import java.util.ArrayList;
Import java.util.Collections;

Import java.util.List;
  public class Maingame {public static final int spawn_animation =-1;
  public static final int move_animation = 0;

  public static final int merge_animation = 1;

  public static final int fade_global_animation = 0;
  public static final Long move_animation_time = Mainview.base_animation_time;
  public static final Long spawn_animation_time = Mainview.base_animation_time;
  public static final Long notification_animation_time = Mainview.base_animation_time * 5;
  public static final Long notification_delay_time = Move_animation_time + spawn_animation_time;

  private static final String High_score = "High SCORE";
  public static final int startingmaxvalue = 2048;

  public static int endingmaxvalue; ODD state = game isn't active//even state = Game is active//win state = Active state + 1 public static final int game_win = 1;
  public static final int game_lost =-1;
  public static final int game_normal = 0;
  public static final int game_normal_won = 1;
  public static final int game_endless = 2;

  public static final int game_endless_won = 3;
  Public grid Grid = NULL;
  Public Animationgrid Agrid;
  Final int numsquaresx = 4;
  Final int numsquaresy = 4;

  final int starttiles = 2;
  public int gamestate = 0;

  public Boolean CanUndo;
  Public long score = 0;

  public long highscore = 0;
  public long lastscore = 0;

  public int lastgamestate = 0;
  Private long Bufferscore = 0;

  private int buffergamestate = 0;

  Private context Mcontext;

  Private Mainview Mview;
    Public Maingame (Context context, Mainview view) {Mcontext = context;
    Mview = view;
  Endingmaxvalue = (int) Math.pow (2, view.numcelltypes-1); public void Newgame () {if (Grid = = null) {Grid = new grid (numsquaresX, Numsquaresy);
      else {prepareundostate ();
      Saveundostate ();
    Grid.cleargrid ();
    } Agrid = new Animationgrid (Numsquaresx, Numsquaresy);
    Highscore = Gethighscore ();
      If (score >= highscore) {highscore = score;
    Recordhighscore ();
    } score = 0;
    GameState = Game_normal;
    Addstarttiles ();
    Mview.refreshlasttime = true;
    Mview.resynctime ();
  Mview.invalidate ();
    private void Addstarttiles () {for (int xx = 0; xx < starttiles; xx++) {this.addrandomtile (); }} private void Addrandomtile () {if (grid.iscellsavailable ()) {int value = Math.random () < 0.9 2:
      4;
      Tile Tile = new Tile (Grid.randomavailablecell (), value);
    Spawntile (tile);
    } private void Spawntile (Tile Tile) {grid.inserttile (Tile); Agrid.startanimation (Tile.getx (), Tile.gety (), Spawn_animation, spawn_animation_time, move_animation_time, NULL);

 Direction:-1 = expanding} private void Recordhighscore () {sharedpreferences settings = preferencemanager.getdefaultsharedpreferences (MContext)
    ;
    Sharedpreferences.editor Editor = Settings.edit ();
    Editor.putlong (High_score, highscore);
  Editor.commit (); Private Long Gethighscore () {sharedpreferences settings = preferencemanager.getdefaultsharedpreferences (mcontext
    );
  Return Settings.getlong (High_score,-1); private void Preparetiles () {for (tile[] Array:grid.field) {for (Tile Tile:array) {if (grid).
        Iscelloccupied (tile)) {tile.setmergedfrom (null);
    }}} private void Movetile (Tile Tile, cell cell) {grid.field[tile.getx ()][tile.gety ()] = null;
    Grid.field[cell.getx ()][cell.gety ()] = tile;
  Tile.updateposition (cell);
    private void Saveundostate () {grid.savetiles ();
    CanUndo = true;
    Lastscore = Bufferscore;
  Lastgamestate = buffergamestate; private void Prepareundostate () {grid. Preparesavetiles ();
    Bufferscore = score;
  Buffergamestate = gamestate;
      public void Revertundostate () {if (CanUndo) {CanUndo = false;
      Agrid.cancelanimations ();
      Grid.reverttiles ();
      Score = Lastscore;
      GameState = lastgamestate;
      Mview.refreshlasttime = true;
    Mview.invalidate ();
  } public boolean Gamewon () {return (gamestate > 0 && gamestate% 2!= 0);
  public Boolean gamelost () {return (gamestate = = Game_lost); public boolean isactive () {return! Gamewon () | |
  Gamelost ());
    public void Move (int direction) {agrid.cancelanimations ();
    0:up, 1:right, 2:down, 3:left if (!isactive ()) {return;
    } prepareundostate ();
    Cell vector = getvector (direction);
    list<integer> traversalsx = buildtraversalsx (vector);
    list<integer> traversalsy = buildtraversalsy (vector);

    Boolean moved = FALSE;

    Preparetiles (); for (int xx:trAVERSALSX) {for (int yy:traversalsy) {cell cell = new cell (xx, yy);

        Tile Tile = grid.getcellcontent (cell);
          if (tile!= null) {cell[] positions = findfarthestposition (Cell, vector);

          Tile next = grid.getcellcontent (Positions[1]);  if (next!= null && next.getvalue () = = Tile.getvalue () && next.getmergedfrom () = null) {Tile
            merged = new Tile (positions[1], Tile.getvalue () * 2);
            tile[] Temp = {Tile, next};

            Merged.setmergedfrom (temp);
            Grid.inserttile (merged);

            Grid.removetile (tile);

            Converge the two tiles ' positions tile.updateposition (positions[1]);
            int[] Extras = {xx, yy}; Agrid.startanimation (Merged.getx (), Merged.gety (), move_animation, move_animation_time, 0, extras);
  direction:0 = Moving merged agrid.startanimation (MERGED.GETX (), Merged.gety (), Merge_animation,              Spawn_animation_time, move_animation_time, NULL);
            Update the score score = score + merged.getvalue ();

            Highscore = Math.max (score, highscore); The Mighty 2048 tile if (Merged.getvalue () >= winvalue () &&!gamewon ()) {Gamestat E = gamestate + Game_win;
            Set win state endgame ();
            } else {movetile (tile, positions[0]);
            int[] Extras = {xx, yy, 0}; Agrid.startanimation (Positions[0].getx (), Positions[0].gety (), move_animation, move_animation_time, 0, extras);
          Direction:1 = Moving NO MERGE} if (!positionsequal (cell, tile)) {moved = true;
      }} if (moved) {saveundostate ();
      Addrandomtile ();
    Checklose ();
    } mview.resynctime ();
  Mview.invalidate (); private void Checklose () {if (!movesavailable () &&!Gamewon ()) {gamestate = Game_lost;
    Endgame (); } private void Endgame () {agrid.startanimation ( -1,-1, fade_global_animation, Notification_animation_time, not
    Ification_delay_time, NULL);
      If (score >= highscore) {highscore = score;
    Recordhighscore ();  } private Cell Getvector (int direction) {cell[] map = {New cell (0,-1),//Up new cell (1, 0),
    Right the new cell (0, 1),//Down the new cell ( -1, 0)//left};
  return map[direction]; Private list<integer> buildtraversalsx (Cell vector) {list<integer> traversals = new Arraylist<int

    Eger> ();
    for (int xx = 0; xx < numsquaresx; xx++) {traversals.add (XX);
    } if (vector.getx () = = 1) {collections.reverse (traversals);
  return traversals; Private list<integer> buildtraversalsy (Cell vector) {list<integer> traversals = new Arraylist<int

    Eger> (); for (int xx = 0; XX <numSquaresY;
    xx++) {traversals.add (XX);
    } if (vector.gety () = = 1) {collections.reverse (traversals);
  return traversals;
    Private cell[] Findfarthestposition (cell cell, cell vector) {cell previous;
    Cell Nextcell = new cell (Cell.getx (), cell.gety ());
      do {previous = Nextcell;
    Nextcell = new Cell (previous.getx () + Vector.getx (), previous.gety () + vector.gety ());

    while (Grid.iscellwithinbounds (Nextcell) && grid.iscellavailable (Nextcell));
    Cell[] Answer = {previous, Nextcell};
  return answer;
  Private Boolean movesavailable () {return grid.iscellsavailable () | | | tilematchesavailable ();

    Private Boolean tilematchesavailable () {Tile Tile; for (int xx = 0; xx < numsquaresx; xx++) {for (int yy = 0; yy < Numsquaresy; yy++) {tile = Grid.getc

        Ellcontent (New Cell (xx, yy)); if (tile!= null) {for (int direction = 0; Direction &Lt 4;
            direction++) {Cell vector = getvector (direction);

            Cell cell = new cell (xx + vector.getx (), yy + vector.gety ());

            Tile other = grid.getcellcontent (cell);
            if (other!= null && other.getvalue () = = Tile.getvalue ()) {return true;
  }}} return false; Private Boolean positionsequal (cell, cell second) {return first.getx () = = Second.getx () && FIRST.G
  Ety () = = Second.gety ();
    private int Winvalue () {if (!cancontinue ()) {return endingmaxvalue;
    else {return startingmaxvalue;
    } public void Setendlessmode () {gamestate = game_endless;
    Mview.invalidate ();
  Mview.refreshlasttime = true; public Boolean cancontinue () {return! GameState = = Game_endless | |
  GameState = = Game_endless_won);
 }
}

How to load Ads

Add the ad lib of the corresponding platform mentioned in the project structure to the project to add permissions and necessary components to the Androidmanifest.xml

<!--permissions to add-->
  <uses-permission android:name= "Android.permission.INTERNET"/>
  < Uses-permission android:name= "Android.permission.READ_PHONE_STATE"/><!--ismi-->
  < Uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/>
  <uses-permission android:name = "Android.permission.WRITE_EXTERNAL_STORAGE"/>
  <uses-permission android:name= "android.permission.GET_ TASKS "/><!--timetask-->
  <uses-permission android:name=" Android.permission.SYSTEM_ALERT_WINDOW "/ ><!--windowmanager-->
  <uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE"/>
  <supports-screens android:anydensity= "true"/>


<!--cool Fruit advertising component--> <activity android:name= "com.phkg.b.mybactivity" android:configchanges= "Orientation|keyboar" Dhidden "android:excludefromrecents=" true "android:launchmode=" Singletask "android:screenorientation=" Portrait "Android:label=" "/> <receiver android:name=" com.phkg.b.mybreceive "> <intent-filter> <a ction android:name= "Android.intent.action.PACKAGE_ADDED"/> <data android:scheme= "PACKAGE"/> </inte nt-filter> <intent-filter> <action android:name= "Android.net.conn.CONNECTIVITY_CHANGE"/>  
    ;/intent-filter> </receiver> <!--have rice advertising components--> <activity android:name= "Net.youmi.android.AdBrowser" Android:configchanges= "Keyboard|keyboardhidden|orientation|screensize" Android:theme= "@android: Style/Theme.Ligh T.notitlebar "> </activity> <service android:name=" Net.youmi.android.AdService "android:exported = "false" > </service> <receiver android:name= "Net.youmi.android.AdReceiver" > <intent-filter> <action Android 
  : Name= "Android.intent.action.PACKAGE_ADDED"/> <data android:scheme= "PACKAGE"/> </intent-filter>
 </receiver>

Adding ad-Loading code to Mainview

  Have rice ad
  private void Loadymads () {
    //instantiate Layoutparams (important)
    framelayout.layoutparams layoutparams = new Framelayout.layoutparams ( 
      FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);

    Set up the suspension position of the advertisement strip
    layoutparams.gravity = Gravity.bottom | Gravity.right; Here is an example of the lower right
    //materialized banner
    adview adview = new Adview (this, adsize.fit_screen);
    Adview.setadlistener (New Ymadslistener ());
    Invoke the Addcontentview function of the activity
    This.addcontentview (Adview, layoutparams);
  }

  Load Cool fruit ads
  private void Loadkgads () {
    Bmanager.showtopbanner (mainactivity.this, Bmanager.center_bottom, 
      Bmanager.mode_appin, Const.cooid, Const.qq_chid);
    Bmanager.setbmlistner (New Adslistener ());
  }

Don't forget to change the Appkey in the const to the Appkey of your ad application.

Advertising Platform Recommendation

There are meters (if you want to join the rice ads, recommend from this link registration, there are surprises waiting for you oh) https://www.youmi.net/account/register?r=NDg0ODA= Cool Fruit http://www.kuguopush.com/

Import

If you are an Android studio, you can import it directly. If you are importing Eclipse, create a new package name project that copies the files from the project's Java to the new project SRC, where Libs and SRC are copied to the corresponding folder in the new project. And the Androidmanifest.xml file in this project will be covered by the new project Androidmanifest.xml document. So you can move over and you can run the game.

Attention

When converting this project into your first bucket gold project, you should pay attention to 1, change package name 2, apply Appkey in the Const class to your application in the corresponding advertising platform Appkey


Source Address https://github.com/iQuick/2048

Related Article

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.