当前位置:   article > 正文

教你如何赚你的第一桶金 - 2048(包括源代码)

if (!self.positionsequal(cell, tile))是什么意思

引言

  1. 程序员们,是否还在为你的老板辛辛苦苦的打工而拿着微薄的薪水呢。还是不知道怎样用自己的应用或游戏
  2. 来赚钱呢!

在这里IQuick将教您怎样同过自己的应用来赚取自己的第一桶金! 你是说自己的应用还没有做出来? 不。在這里已经为你提供好了一个完整的游戏应用了,在文章的以下有源代码的地址哦。你仅仅要稍做改动就能够 变成一个全然属于自己的应用了,比方将4*4换成5*5,甚至是其他的。

假设你实在是慵懒至极的话,你仅仅要将本应 用的包名及广告换成自己的。就能够上传到市场上轻轻松松赚取自己的第一桶金了。

假设你认为本文非常赞的话。就顶一下作者吧,从以下的安装地址中下载应用,或者在导入本project执行的时候, 从广告中安装一个应用。

动一动你的手指。就能让作者更进一步,也能让作者以后更加有动力来分享吧。

安装

   安智

预览



项目结构


重要代码解读

MainView游戏的主体类
  1. //初始化方法。里面初始化了一些常量。字体颜色等
  2. name="code" class="java">public MainView(Context context) {
  3. super(context);
  4. Resources resources = context.getResources();
  5. //Loading resources
  6. game = new MainGame(context, this);
  7. try {
  8. //Getting assets
  9. backgroundRectangle = resources.getDrawable(R.drawable.background_rectangle);
  10. lightUpRectangle = resources.getDrawable(R.drawable.light_up_rectangle);
  11. fadeRectangle = resources.getDrawable(R.drawable.fade_rectangle);
  12. TEXT_WHITE = resources.getColor(R.color.text_white);
  13. TEXT_BLACK = resources.getColor(R.color.text_black);
  14. TEXT_BROWN = resources.getColor(R.color.text_brown);
  15. this.setBackgroundColor(resources.getColor(R.color.background));
  16. Typeface font = Typeface.createFromAsset(resources.getAssets(), "ClearSans-Bold.ttf");
  17. paint.setTypeface(font);
  18. paint.setAntiAlias(true);
  19. } catch (Exception e) {
  20. System.out.println("Error getting assets?");
  21. }
  22. setOnTouchListener(new InputListener(this));
  23. game.newGame();
  24. }
  25. //游戏界面的绘制
  26. @Override
  27. protected void onSizeChanged(int width, int height, int oldw, int oldh) {
  28. super.onSizeChanged(width, height, oldw, oldh);
  29. getLayout(width, height);
  30. createBitmapCells();
  31. createBackgroundBitmap(width, height);
  32. createOverlays();
  33. }

MianGame游戏主要逻辑
  1. package com.tpcstld.twozerogame;
  2. import android.content.Context;
  3. import android.content.SharedPreferences;
  4. import android.preference.PreferenceManager;
  5. import java.util.ArrayList;
  6. import java.util.Collections;
  7. import java.util.List;
  8. public class MainGame {
  9. public static final int SPAWN_ANIMATION = -1;
  10. public static final int MOVE_ANIMATION = 0;
  11. public static final int MERGE_ANIMATION = 1;
  12. public static final int FADE_GLOBAL_ANIMATION = 0;
  13. public static final long MOVE_ANIMATION_TIME = MainView.BASE_ANIMATION_TIME;
  14. public static final long SPAWN_ANIMATION_TIME = MainView.BASE_ANIMATION_TIME;
  15. public static final long NOTIFICATION_ANIMATION_TIME = MainView.BASE_ANIMATION_TIME * 5;
  16. public static final long NOTIFICATION_DELAY_TIME = MOVE_ANIMATION_TIME + SPAWN_ANIMATION_TIME;
  17. private static final String HIGH_SCORE = "high score";
  18. public static final int startingMaxValue = 2048;
  19. public static int endingMaxValue;
  20. //Odd state = game is not active
  21. //Even state = game is active
  22. //Win state = active state + 1
  23. public static final int GAME_WIN = 1;
  24. public static final int GAME_LOST = -1;
  25. public static final int GAME_NORMAL = 0;
  26. public static final int GAME_NORMAL_WON = 1;
  27. public static final int GAME_ENDLESS = 2;
  28. public static final int GAME_ENDLESS_WON = 3;
  29. public Grid grid = null;
  30. public AnimationGrid aGrid;
  31. final int numSquaresX = 4;
  32. final int numSquaresY = 4;
  33. final int startTiles = 2;
  34. public int gameState = 0;
  35. public boolean canUndo;
  36. public long score = 0;
  37. public long highScore = 0;
  38. public long lastScore = 0;
  39. public int lastGameState = 0;
  40. private long bufferScore = 0;
  41. private int bufferGameState = 0;
  42. private Context mContext;
  43. private MainView mView;
  44. public MainGame(Context context, MainView view) {
  45. mContext = context;
  46. mView = view;
  47. endingMaxValue = (int) Math.pow(2, view.numCellTypes - 1);
  48. }
  49. public void newGame() {
  50. if (grid == null) {
  51. grid = new Grid(numSquaresX, numSquaresY);
  52. } else {
  53. prepareUndoState();
  54. saveUndoState();
  55. grid.clearGrid();
  56. }
  57. aGrid = new AnimationGrid(numSquaresX, numSquaresY);
  58. highScore = getHighScore();
  59. if (score >= highScore) {
  60. highScore = score;
  61. recordHighScore();
  62. }
  63. score = 0;
  64. gameState = GAME_NORMAL;
  65. addStartTiles();
  66. mView.refreshLastTime = true;
  67. mView.resyncTime();
  68. mView.invalidate();
  69. }
  70. private void addStartTiles() {
  71. for (int xx = 0; xx < startTiles; xx++) {
  72. this.addRandomTile();
  73. }
  74. }
  75. private void addRandomTile() {
  76. if (grid.isCellsAvailable()) {
  77. 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()) { 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(), 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, 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); } }





怎样载入广告

  1. 将项目结构上提到的相应平台的广告Lib增加到项目中
  2. 在AndroidManifest.xml中增加权限及必要组件
  1. <!--须要加入的权限 -->
  2. <uses-permission android:name="android.permission.INTERNET" />
  3. <uses-permission android:name="android.permission.READ_PHONE_STATE" /><!-- ismi -->
  4. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  5. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  6. <uses-permission android:name="android.permission.GET_TASKS" /><!-- TimeTask -->
  7. <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /><!-- WindowManager -->
  8. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
  9. <supports-screens android:anyDensity="true" />

  1. <!-- 酷果广告组件 -->
  2. <activity android:name="com.phkg.b.MyBActivity"
  3. android:configChanges="orientation|keyboardHidden"
  4. android:excludeFromRecents="true"
  5. android:launchMode="singleTask"
  6. android:screenOrientation="portrait"
  7. android:label=""/>
  8. <receiver android:name="com.phkg.b.MyBReceive">
  9. <intent-filter>
  10. <action android:name="android.intent.action.PACKAGE_ADDED" />
  11. <data android:scheme="package" />
  12. </intent-filter>
  13. <intent-filter>
  14. <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
  15. </intent-filter>
  16. </receiver>
  17. <!-- 有米广告组件 -->
  18. <activity android:name="net.youmi.android.AdBrowser"
  19. android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
  20. android:theme="@android:style/Theme.Light.NoTitleBar" >
  21. </activity>
  22. <service
  23. android:name="net.youmi.android.AdService"
  24. android:exported="false" >
  25. </service>
  26. <receiver android:name="net.youmi.android.AdReceiver" >
  27. <intent-filter>
  28. <action android:name="android.intent.action.PACKAGE_ADDED" />
  29. <data android:scheme="package" />
  30. </intent-filter>
  31. </receiver>

在MainView中增加广告载入代码
  1. //有米广告
  2. private void loadYMAds() {
  3. // 实例化 LayoutParams(重要)
  4. FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
  5. FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
  6. // 设置广告条的悬浮位置
  7. layoutParams.gravity = Gravity.BOTTOM | Gravity.RIGHT; // 这里演示样例为右下角
  8. // 实例化广告条
  9. AdView adView = new AdView(this, AdSize.FIT_SCREEN);
  10. adView.setAdListener(new YMAdsListener());
  11. // 调用 Activity 的 addContentView 函数
  12. this.addContentView(adView, layoutParams);
  13. }
  14. //载入酷果广告
  15. private void loadKGAds() {
  16. BManager.showTopBanner(MainActivity.this, BManager.CENTER_BOTTOM,
  17. BManager.MODE_APPIN, Const.COOID, Const.QQ_CHID);
  18. BManager.setBMListner(new ADSListener());
  19. }

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

广告平台推荐

  1. 有米(假设想增加有米广告,力荐从此链接注冊,有惊喜等着你哦)
  2. https://www.youmi.net/account/register?

r=NDg0ODA=

酷果 http://www.kuguopush.com/

导入

  1. 假设是Android Studio的话能够直接导入。
  2. 假设是要导入Eclipse的话。则新建一个包名一样的项目,在将本project下Java里的文件都复制到新project里src
  3. 中,本project的里libs、src复制到新project相应的目录。
  4. 并将本project里的AndroidManifest.xml文件覆盖新项目AndroidManifest.xml文件。
  5. 至此你就能够迁移完成,你能够执行游戏了。

注意

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

源代码地址

https://github.com/iQuick/2048

版权声明:本文博客原创文章。博客,未经同意,不得转载。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/43477
推荐阅读
相关标签
  

闽ICP备14008679号