Android项目开发实战-2048游戏
《2048》是一款比较流行的数字游戏,最早于2014年3月20日发行。原版2048首先在GitHub上发布,原作者是Gabriele Cirulli,后被移植到各个平台。这款游戏是基于《1024》和《小3传奇》的玩法开发而成的新型数字游戏。游戏源地址:http://gabrielecirulli.github.io/2048/
1、新建android项目game2048
修改activity_main.xml文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" > <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" /> </LinearLayout>
2、设计2048游戏布局
继续修改activity_main.xml文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" > <LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" > <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/score" /> <TextView
android:id="@+id/tvScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout> <GridLayout
android:id="@+id/gameView"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" >
</GridLayout> </LinearLayout>
3、实现2048游戏主类GameView
新建类GameView,继承自GridLayout
package com.wuyudong.game2048; import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridLayout; public class GameView extends GridLayout { public GameView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initGameView();
} public GameView(Context context, AttributeSet attrs) {
super(context, attrs);
initGameView();
} public GameView(Context context) {
super(context);
initGameView();
} private void initGameView() { } }
继续修改activity_main.xml文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" > <LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" > <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/score" /> <TextView
android:id="@+id/tvScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout> <!-- 把类GameView绑定到一起 -->
<com.wuyudong.game2048.GameView
android:id="@+id/gameView"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" >
</com.wuyudong.game2048.GameView> </LinearLayout>
4、游戏2048在Android平台的触控交互设计
添加触控交互相关代码
private void initGameView() {
setOnTouchListener(new OnTouchListener() {
//记录起始位置和偏移坐标
private float startX, startY, offsetX, offsetY; @Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: //监听手指按下的初始位置坐标
startX = event.getX();
startY = event.getY();
break; case MotionEvent.ACTION_UP: //监听手指离开时的位置坐标
offsetX = event.getX() - startX;
offsetY = event.getY() - startY; if (Math.abs(offsetX) > Math.abs(offsetY)) {
if (offsetX < -5) {
System.out.println("left");
} else if (offsetX > 5) {
System.out.println("right");
}
} else {
if (offsetY < -5) {
System.out.println("up");
} else if (offsetY > 5) {
System.out.println("down");
}
}
break;
default:
break;
} return true;
}
}); }
5、实现2048游戏的卡片类
编写卡片类Card.java
package com.wuyudong.game2048; import android.content.Context;
import android.widget.FrameLayout;
import android.widget.TextView; public class Card extends FrameLayout { public Card(Context context) {
super(context);
lable = new TextView(getContext());
lable.setTextSize(32); LayoutParams lp = new LayoutParams(-1, -1);
addView(lable, lp);
setNum(0);
} private int num = 0; public int getNum() {
return num;
} public void setNum(int num) {
this.num = num;
lable.setText(num + "");
} public boolean equals(Card o) {
return getNum() == o.getNum();
} private TextView lable; }
6、添加2048游戏卡片
先添加相关代码看看效果
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
int cardWidth = (Math.min(w, h) - 10) / 4; addCards(cardWidth, cardWidth); } private void addCards(int cardWith, int cardHeight){
Card c;
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
c=new Card(getContext());
c.setNum(2);
addView(c, cardWith, cardHeight);
}
}
}
运行后的效果
出现问题,所有的2都出现在同一行中,解决办法:
在initGameView() 中添加代码,指定为四列:setColumnCount(4);
lable.setGravity(Gravity.CENTER);
接着添加相关的背景颜色以及卡片数字的背景颜色,还有卡片间距
setBackgroundColor(0xffbbada0); // 设置整体背景
lable.setBackgroundColor(0x33ffffff);
lable.setGravity(Gravity.CENTER);
lp.setMargins(10, 10, 0, 0);
运行后界面如下:
7、在2048游戏中添加随机数
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
int cardWidth = (Math.min(w, h) - 10) / 4; addCards(cardWidth, cardWidth); startGame(); } private void startGame() {
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
cardsMap[x][y].setNum(0);
}
}
addRandomNum();
addRandomNum();
} private void addRandomNum() {
emptyPoints.clear();// 清空
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
if (cardsMap[x][y].getNum() <= 0) {
emptyPoints.add(new Point(x, y));
} }
}
Point p = emptyPoints.remove((int) (Math.random() * emptyPoints.size()));
cardsMap[p.x][p.y].setNum(Math.random() > 0.1 ? 2 : 4); }
8、实现2048游戏逻辑
private void swipeLeft() { // 往左滑动手指
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) { for (int x1 = x + 1; x1 < 4; x1++) {
if (cardsMap[x1][y].getNum() > 0) { if (cardsMap[x][y].getNum() <= 0) {
cardsMap[x][y].setNum(cardsMap[x1][y].getNum());
cardsMap[x1][y].setNum(0); x--;
break;
} else if(cardsMap[x][y].equals(cardsMap[x1][y])){
cardsMap[x][y].setNum(cardsMap[x][y].getNum()*2);
cardsMap[x1][y].setNum(0);
break;
}
}
}
}
} } private void swipeRight() {
for (int y = 0; y < 4; y++) {
for (int x = 3; x >=0; x--) { for (int x1 = x - 1; x1 >=0; x1--) {
if (cardsMap[x1][y].getNum() > 0) { if (cardsMap[x][y].getNum() <= 0) {
cardsMap[x][y].setNum(cardsMap[x1][y].getNum());
cardsMap[x1][y].setNum(0); x++;
break;
} else if(cardsMap[x][y].equals(cardsMap[x1][y])){
cardsMap[x][y].setNum(cardsMap[x][y].getNum()*2);
cardsMap[x1][y].setNum(0);
break;
}
}
}
}
} } private void swipeUp() {
for (int x = 0; x < 4; x++) {
for (int y = 0; y < 4; y++) { for (int y1 = y + 1; y1 < 4; y1++) {
if (cardsMap[x][y1].getNum() > 0) { if (cardsMap[x][y].getNum() <= 0) {
cardsMap[x][y].setNum(cardsMap[x][y1].getNum());
cardsMap[x][y1].setNum(0); y--;
break;
} else if(cardsMap[x][y].equals(cardsMap[x][y1])){
cardsMap[x][y].setNum(cardsMap[x][y].getNum()*2);
cardsMap[x][y1].setNum(0);
break;
}
}
}
}
} } private void swipeDown() { for (int x = 0; x < 4; x++) {
for (int y = 3; y >=0; y--) { for (int y1 = y - 1; y1 >= 0; y1--) {
if (cardsMap[x][y1].getNum() > 0) { if (cardsMap[x][y].getNum() <= 0) {
cardsMap[x][y].setNum(cardsMap[x][y1].getNum());
cardsMap[x][y1].setNum(0); y++;
break;
} else if(cardsMap[x][y].equals(cardsMap[x][y1])){
cardsMap[x][y].setNum(cardsMap[x][y].getNum()*2);
cardsMap[x][y1].setNum(0);
break;
}
}
}
}
}
} private Card[][] cardsMap = new Card[4][4];
private List<Point> emptyPoints = new ArrayList<Point>();
9、游戏2048计分
MainActivity.java 中添加相关代码:
package com.wuyudong.game2048; import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView; public class MainActivity extends Activity { public MainActivity() {
mainActivity = this;
} @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); tvScore = (TextView) findViewById(R.id.tvScore);
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} public void clearScore() {
score = 0;
showScore();
} public void showScore() {
tvScore.setText(score + "");
} public void addScore(int s) {
score += s;
showScore();
} private int score = 0;
private TextView tvScore;
private static MainActivity mainActivity = null; public static MainActivity getMainActivity() {
return mainActivity;
} }
10、检查2048游戏结束
private void checkComplete() {
boolean complete = true;
ALL: for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
if (cardsMap[x][y].getNum() == 0
|| (x > 0 && cardsMap[x][y].equals(cardsMap[x - 1][y]))
|| (x < 3 && cardsMap[x][y].equals(cardsMap[x + 1][y]))
|| (y > 0 && cardsMap[x][y].equals(cardsMap[x][y - 1]))
|| (y < 3 && cardsMap[x][y].equals(cardsMap[x][y + 1]))) { complete = false;
break ALL;
}
}
}
if (complete) {
new AlertDialog.Builder(getContext())
.setTitle("Oh")
.setMessage("Game Over!")
.setPositiveButton("restart",
new DialogInterface.OnClickListener() { @Override
public void onClick(DialogInterface dialog,
int which) {
startGame(); }
}).show();
} }
Android项目开发实战-2048游戏的更多相关文章
- Android 项目开发实战:聚合数据短信验证码
聚合数据集成短信验证码官网: https://www.juhe.cn/docs/api/id/54 我根据文档集成了一个例子 效果: 源码下载:http://download.csdn.net/det ...
- Android项目开发第四周学习总结
Android项目开发实战第四周 在本周,我们进行了Android项目第四周的项目开发,在本周,我们对原有的项目进行改进,我们的想法是使项目在原有的基础上增加一些新的功能,使得txt阅读器可以更加先进 ...
- 开源自己的一个小android项目(美女撕衣服游戏)
这是自己的一个开源自己的一个小android项目(美女撕衣服游戏),也是前6个月开发的,有部分的资源来自网络上的,现在开源出来给大家吧,由于源码比较大,不上传了,我已经上传到源码天堂那个网站那里了,大 ...
- 《Android Studio开发实战 从零基础到App上线》资源下载和内容勘误
转载于:https://blog.csdn.net/aqi00/article/details/73065392 资源下载 下面是<Android Studio开发实战 从零基础到App上线&g ...
- 《Android NFC 开发实战详解 》简介+源码+样章+勘误ING
<Android NFC 开发实战详解>简介+源码+样章+勘误ING SkySeraph Mar. 14th 2014 Email:skyseraph00@163.com 更多精彩请直接 ...
- Swift项目开发实战-基于分层架构的多版本iPhone计算器-直播公开课
Swift项目开发实战-基于分层架构的多版本iPhone计算器-直播公开课 本课程采用Q Q群直播方式进行直播,价值99元视频课程免费直播.完整的基于Swift项目实战,手把手教你做一个Swift版i ...
- Android项目开发全程(四)-- 将网络返回的json字符串轻松转换成listview列表
前面几篇博文介绍了从项目搭建到获取网络字符串,对一个项目的前期整体工作进行了详细的介绍,本篇接着上篇介绍一下怎么样优雅将网络返回的json字符串轻松转换成listview列表. 先上图,看一下效果. ...
- Android项目开发全程(三)-- 项目的前期搭建、网络请求封装是怎样实现的
在前两篇博文中已经做了铺垫,下面咱们就可以用前面介绍过的内容开始做一个小项目了(项目中会用到Afinal框架,不会用Afinal的童鞋可以先看一下上一篇博文),正所谓麻雀虽小,五脏俱全,这在里我会尽量 ...
- Android项目开发全程(二)--Afinal用法简单介绍
本篇博文接上篇的<Android项目开发全程(一)--创建工程>,主要介绍一下在本项目中用到的一个很重要的框架-Afinal,由于本系列博文重点是项目开发全程,所以在这里就先介绍一下本项目 ...
随机推荐
- HT for Web基于HTML5的图像操作(三)
上篇采用了HTML5的Canvas的globalCompositeOperation属性达到了染色效果,其实CSS也提供了一些常规图像变化的设置参数,关于CSS的过滤器Filter设置可参考 http ...
- JS实现简易的计算器
JS可以做的事多了,那就用来实现一个计算器吧 看看手机中的计算器,分为普通计算器和科学计算器 自认脑袋不够大,就实现一个普通版本的吧(支持正负数加减乘除等基本连续的运算,未提供括号功能) 看看 ...
- chm转换为html的超简单方法
在Windows下chm转换为html的超简单方法(反编译CHM文件的方法) 通过调用Windows命令,将chm 文件转换为html 文件. 方法: 命令行(cmd),输入hh -decompile ...
- 解决 DotNetCore.1.0.1-VS2015Tools.Preview2.0.3.exe 在VS2015 Update3 安装失败的问题
今天抽空升级VS2015 Update3. 在安装DotNetCore.1.0.1-VS2015Tools.Preview2.0.3.exe 时报错了,看了错误日志 显示: 看到我标红的两个地方,那么 ...
- 【C#】递归搜索指定目录下的指定项目(文件或目录)
---------------更新:201411201121--------------- 主要更新说明:将原bool recurse参数改为int depth,这样可以指定递归深度,而不是笼统的是否 ...
- Asp.net Mvc模块化开发之“开启模块开发、调试的简单愉快之旅”
整个世界林林种种,把所有的事情都划分为对立的两个面. 每个人都渴望的财富划分为富有和贫穷,身高被划分为高和矮,身材被划分为胖和瘦,等等. 我们总是感叹,有钱人的生活我不懂;有钱人又何尝能懂我们每天起早 ...
- DokuWiki用storage的模式在sae上部署后速度太慢
利用sae做的io wrapper接口,对dokuwiki做了基于sae的分布式storage存储改造,能正常安装和运行,但速度太慢,基本没什么用. 定义一个常量: define('SAESTORE_ ...
- CXF和spring整合遇到的问题:No bean named 'cxf' is defined
今天在做ws和spring整合的时候,很不幸的遇到了这个问题,百度了好久,竟然没人遇到这个问题,后来谷歌了一下,都是遇到这个问题的了...在看到一篇文章中提到了cxf.xml,所以我果断的打开这个配置 ...
- Guava学习笔记:Guava cache
缓存,在我们日常开发中是必不可少的一种解决性能问题的方法.简单的说,cache 就是为了提升系统性能而开辟的一块内存空间. 缓存的主要作用是暂时在内存中保存业务系统的数据处理结果,并且等待下次访问使用 ...
- GJM : Taurus.MVC 2.0 开源发布:WebAPI开发教程 [转载]
Taurus.MVC 2.0 开源发布:WebAPI开发教程 转载自http://www.cnblogs.com/cyq1162/p/6069020.html 因是新手 粘贴时有一个版权问题 本文原 ...