Android 게임 소스 공유 2048
, , !
IQuick !
?
, @ , 。 , 4*4 5*5, 。 , , 。
, , , , 。 , , 。
설치 하 다.![](https://s1.md5.ltd/image/0a06712e0643efc52d9612438bc1bf55.png)
![](https://s1.md5.ltd/image/9ef59401801d1a2156cdbb1a12a5a13b.png)
![](https://s1.md5.ltd/image/d50b0d58ab43ea4ff6aae8f618ae238c.png)
![](https://s1.md5.ltd/image/b1b8e78ff46ab0df51b18d99567aa981.png)
프로젝트 구조
![](https://s1.md5.ltd/image/fe2622db9b548a00b08348315084f1a2.png)
중요 코드 판독 MainView 게임 의 주체 클래스
// , ,
name="code" class="java">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,
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);
}
}
어떻게 광 고 를 불 러 옵 니까?프로젝트 구조 에 언급 된 해당 플랫폼 의 광고 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 를 가 져 오 려 면 패키지 이름 과 같은 항목 을 새로 만 듭 니 다.이 프로젝트 에서 자바 의 파일 을 모두 새 프로젝트 에 복사 합 니 다.src 에 서 는 이 프로젝트 의 libs,src 를 새 프로젝트 에 대응 하 는 폴 더 로 복사 합 니 다.이 프로젝트 의 AndroidManifest.xml 파일 을 새 프로젝트 AndroidManifest.xml 파일 로 덮어 씁 니 다.이로써 당신 은 이 사 를 마 칠 수 있 습 니 다.당신 은 게임 을 실행 할 수 있 습 니 다.
주의 하 다.
본 프로젝트 를 자신의 첫 번 째 통 금 프로젝트 로 전환 할 때 1.바 꾸 기 2.Const 류 의 앱 키 를 광고 플랫폼 에서 신청 한 앱 키 로 바 꾸 기
원본 주소https://github.com/iQuick/2048
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Bitrise에서 배포 어플리케이션 설정 테스트하기이 글은 Bitrise 광고 달력의 23일째 글입니다. 자체 또는 당사 등에서 Bitrise 구축 서비스를 사용합니다. 그나저나 며칠 전 Bitrise User Group Meetup #3에서 아래 슬라이드를 발표했...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.