Android游戏源码分享之2048

Android游戏源码分享之2048,第1张

概述引言程序猿们,是否还在为你的老板辛辛苦苦的打工而拿着微薄的薪水呢,还是不知道如何用自己的应用或游戏来赚钱呢!

引言

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

安装



项目结构

重要代码解读MainVIEw游戏的主体类

//初始化方法,里面初始化了一些常量,字体颜色等 name="code" >public MainVIEw(Context context) {    super(context);    Resources resources = context.getResources();    //Loading resources    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(new inputListener(this));    game.newGame();  }  //游戏界面的绘制  @OverrIDe  protected voID onSizeChanged(int wIDth,int height,int olDW,int oldh) {    super.onSizeChanged(wIDth,height,olDW,oldh);    getLayout(wIDth,height);    createBitmapCells();    createBackgroundBitmap(wIDth,height);    createOverlays();  }


MianGame游戏主要逻辑

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 is not 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,extras); //Direction: 0 = MOVING MERGED            aGrID.startAnimation(merged.getX(),MERGE_ANIMATION,null);            // Update the score            score = score + merged.getValue();            highscore = Math.max(score,highscore);            // The mighty 2048 tile            if (merged.getValue() >= winValue() && !gameWon()) {              gameState = 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(),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,NOTIFICATION_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        new Cell(0,1),// down        new Cell(-1,0) // left    };    return map[direction];  }  private List<Integer> buildTraversalsX(Cell vector) {    List<Integer> traversals = new ArrayList<Integer>();    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<Integer>();    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.getCellContent(new Cell(xx,yy));        if (tile != null) {          for (int direction = 0; direction < 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 first,Cell second) {    return first.getX() == second.getX() && first.getY() == 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);  }}

如何加载广告

将项目结构上提到的对应平台的广告lib加入到项目中在AndroIDManifest.xml中加入权限及必要组件

<!--需要添加的权限 -->  <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" />


<!-- 酷果广告组件 -->  <activity androID:name="com.phkg.b.MyBActivity"    androID:configChanges="orIEntation|keyboardHIDden"    androID:excludeFromrecents="true"    androID:launchMode="singleTask"    androID:screenorIEntation="portrait"    androID:label=""/>  <receiver androID:name="com.phkg.b.MyBReceive">    <intent-filter>      <action androID:name="androID.intent.action.PACKAGE_ADDED" />      <data androID:scheme="package" />    </intent-filter>    <intent-filter>      <action androID:name="androID.net.conn.CONNECTIVITY_CHANGE" />    </intent-filter>  </receiver>  <!-- 有米广告组件 -->  <activity androID:name="net.youmi.androID.Adbrowser"     androID:configChanges="keyboard|keyboardHIDden|orIEntation|screenSize"    androID:theme="@androID:style/theme.light.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>

在MainVIEw中加入广告加载代码

  //有米广告  private voID loadYMAds() {    // 实例化 LayoutParams(重要)    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(       FrameLayout.LayoutParams.FILL_PARENT,FrameLayout.LayoutParams.WRAP_CONTENT);    // 设置广告条的悬浮位置    layoutParams.gravity = Gravity.BottOM | Gravity.RIGHT; // 这里示例为右下角    // 实例化广告条    AdVIEw adVIEw = new AdVIEw(this,AdSize.FIT_SCREEN);    adVIEw.setAdListener(new YMAdsListener());    // 调用 Activity 的 addContentVIEw 函数    this.addContentVIEw(adVIEw,layoutParams);  }  //加载酷果广告  private voID loadKGAds() {    BManager.showtopBanner(MainActivity.this,BManager.CENTER_BottOM,BManager.MODE_APPIN,Const.COOID,Const.QQ_CHID);    BManager.setBMListner(new ADSListener());  }

别忘了将Const中的Appkey换成自己在广告申请的Appkey

广告平台推荐

有米(如果想加入有米广告,力荐从此链接注册,有惊喜等着你哦)https://www.youmi.net/account/register?r=NDg0ODA=酷果http://www.kuguopush.com/

导入

如果是AndroID Studio的话可以直接导入。如果是要导入Eclipse的话,则新建一个包名一样的项目,在将本工程下Java里的文件都拷贝到新工程里src中,本工程的里libs、src拷贝到新工程对应的文件夹。并将本工程里的AndroIDManifest.xml文件覆盖新项目AndroIDManifest.xml文件。至此你就可以迁移完毕,你可以运行游戏了。

注意

将本项目转换成自己的第一桶金项目时要注意1、换掉包名2、将Const类里的应用Appkey换成自己在对应广告平台申请的应用Appkey


源码地址https://github.com/iQuick/2048

您可能感兴趣的文章:Android 游戏开发之Canvas画布的介绍及方法Android五子棋游戏程序完整实例分析Android游戏开发实践之人物移动地图的平滑滚动处理Android开发之经典游戏贪吃蛇Unity3D游戏引擎实现在Android中打开WebView的实例Android 游戏开发入门简单示例Android高仿2048小游戏实现代码解析Android游戏中获取电话状态进行游戏暂停或继续的解决方法Android 游戏引擎libgdx 资源加载进度百分比显示案例分析Android数字华容道小游戏开发 总结

以上是内存溢出为你收集整理的Android游戏源码分享之2048全部内容,希望文章能够帮你解决Android游戏源码分享之2048所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1142898.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存