刚学了一点xml布局、activity的原理,突发奇想想实现一个根据出现数字点击相应数字的游戏。
经过几天的尝试,完成了如下:
最初界面:
游戏模式选择:
解锁norma模式的不通关卡4 7 后,可分别解锁exceed random模式
难度选择:
解锁下一关后相应图标出现 如左图 2 3
游戏界面(最简单的模式与难度):
high score达到20可以解锁下一关
要实现的内容:
1.activity的切换(切换了大量的activity,现在发现可以使用在一个activity上切换布局)
2.游戏的逻辑,如上图212 如何判断点击正确并让score加1
3.数据的存储,如模式 关卡 的解锁与否,各个关卡的最高分等;
4.退出时如何关闭所有的activity
分别介绍以上4点的实现:
1.activity的跳转使用intent类实现,可根据情况选择要不要finish跳转前的activity,代码如下:
Intent intent = new Intent();
intent.setClass(MainActivity.this, AboutActivity.class);
MainActivity.this.startActivity(intent);
//MainActivity.this.finish()
2.首先通过random方法随机三个数并在上面显示(同时根据不同数字设置相应颜色),将数字存入string中,玩家按下面的相应数字,将按下的数字按顺序存入一个stringbuff中,比较string与stringbuff中数字顺序即可判断是否得分,关键代码如下:
p1 = Math.abs(random.nextInt())%3+1; //随机产生1-3的数字,当然有三个
a = new StringBuffer();
class b1Liestener implements OnClickListener{
@Override
public void onClick(View v) {
a.append(Integer.toString(b1));
}
}//将点击的顺序存入stringbuff,同样也有三个
String x = Integer.toString(p1)+Integer.toString(p2)+Integer.toString(p3);
//将显示顺序存入string x中
if(start&&(a.toString().length()<3||!a.toString().substring(0,3).equals(x)))//判断x a中顺序是否相同,start代表是否开始
3.数据存储是从网上找的方法,自定义一个DatabaseHelper类(注意onCreate方法只在最开始调用一次),弄了好久终于成功建立数据库,代码如下:
package com.example.game02.db;
import com.example.game02.ActivityOne;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int VERSION = 1;
private static final String DB_NAME = "123db";
private ContentValues values;
public DatabaseHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
public DatabaseHelper(Context context, String name) {
this(context, name, VERSION);
// TODO Auto-generated constructor stub
}
public DatabaseHelper(Context context, String name,int version) {
this(context, name, null, VERSION);
// TODO Auto-generated constructor stub
}
public DatabaseHelper(Context context) {
this(context, DB_NAME);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table user(id int, score varchar(20))");
db.execSQL("insert into user(id,score) values(1,'0')");
db.execSQL("insert into user(id,score) values(2,'0')");
db.execSQL("insert into user(id,score) values(3,'0')");
db.execSQL("insert into user(id,score) values(4,'0')");
db.execSQL("insert into user(id,score) values(5,'0')");
db.execSQL("insert into user(id,score) values(6,'0')");
db.execSQL("insert into user(id,score) values(7,'0')");
db.execSQL("insert into user(id,score) values(8,'0')");//exceed random 最初解锁
db.execSQL("insert into user(id,score) values(9,'0')");
db.execSQL("insert into user(id,score) values(12,'0')");//normal 解锁
db.execSQL("insert into user(id,score) values(13,'0')");//exceed 解锁
db.execSQL("insert into user(id,score) values(14,'0')");//Random 解锁
db.execSQL("insert into user(id,score) values(15,'0')");
db.execSQL("insert into user(id,score) values(16,'0')");
db.execSQL("insert into user(id,score) values(17,'0')");
db.execSQL("insert into user(id,score) values(21,'0')");//exceed 最高分
db.execSQL("insert into user(id,score) values(22,'0')");
db.execSQL("insert into user(id,score) values(23,'0')");
db.execSQL("insert into user(id,score) values(31,'0')");//random 最高分
db.execSQL("insert into user(id,score) values(32,'0')");
db.execSQL("insert into user(id,score) values(33,'0')");
db.execSQL("insert into user(id,score) values(34,'0')");
db.execSQL("insert into user(id,score) values(35,'0')");
db.execSQL("insert into user(id,score) values(36,'0')");
db.execSQL("insert into user(id,score) values(37,'0')");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
4.关闭所有activity的方法也是从网上找的,捣鼓了一下能用了,定义一个MyExit类,创建一个activity的链表,没产生一个activity,就存入其中,退出时一次调用finish方法,就能关闭该程序所有activity,代码如下:
package com.example.game02;
import android.app.Application;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
public class MyExit extends Application {
private List<Activity> activitys = null;
private static MyExit exit;
private MyExit() {
activitys = new LinkedList<Activity>();
}
public static MyExit getExit() {
if (null == exit) {
exit = new MyExit();
}
return exit;
}
public void addActivity(Activity activity) {
if (activitys != null && activitys.size() > 0) {
if(!activitys.contains(activity)){
activitys.add(activity);
}
}else{
activitys.add(activity);
}
}
public void exit() {
if (activitys != null && activitys.size() > 0) {
for (Activity activity : activitys) {
activity.finish();
}
}
System.exit(0);
}
}
下面附上最简单一关的代码(后面的也差不多):
布局:
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.game02.ActivityOne" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal" >
<TextView
android:id="@+id/score11"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#FF8C00"
android:gravity="center"
android:text="@string/score"
android:textSize="15pt" />
<TextView
android:id="@+id/score12"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#FAFAD2"
android:gravity="center"
android:text="@string/sco"
android:textSize="15pt" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal" >
<TextView
android:id="@+id/textView11"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginBottom="3dp"
android:layout_marginLeft="3dp"
android:layout_marginRight="1.5dp"
android:layout_marginTop="3dp"
android:layout_weight="1"
android:background="#FFFFFF"
android:gravity="center"
android:text="@string/pan1"
android:textSize="15pt" />
<TextView
android:id="@+id/textView12"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginBottom="3dp"
android:layout_marginLeft="1.5dp"
android:layout_marginRight="1.5dp"
android:layout_marginTop="3dp"
android:layout_weight="1"
android:background="#FFFFFF"
android:gravity="center"
android:text="@string/pan2"
android:textSize="15pt" />
<TextView
android:id="@+id/textView13"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginBottom="3dp"
android:layout_marginLeft="1.5dp"
android:layout_marginRight="3dp"
android:layout_marginTop="3dp"
android:layout_weight="1"
android:background="#FFFFFF"
android:gravity="center"
android:text="@string/pan3"
android:textSize="15pt" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="4"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#FFFF00"
android:orientation="horizontal" >
<TextView
android:id="@+id/scoreView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="3dp"
android:layout_marginLeft="3dp"
android:layout_marginRight="3dp"
android:layout_marginTop="3dp"
android:background="#FFFF00"
android:gravity="center"
android:textSize="13pt" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#FFFFFF"
android:gravity="center"
android:orientation="horizontal" >
<TextView
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:textSize="15pt"
android:gravity="center" />
<Button
android:id="@+id/check11"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_marginBottom="1.5dp"
android:layout_marginLeft="3dp"
android:layout_marginRight="3dp"
android:layout_marginTop="3dp"
android:layout_weight="2"
android:background="#FFC0CB"
android:gravity="center"
android:text="@string/on"
android:textSize="15pt" />
<TextView
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:textSize="15pt"
android:gravity="center" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:orientation="horizontal" >
<Button
android:id="@+id/check12"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="3dp"
android:layout_marginLeft="3dp"
android:layout_marginRight="1.5dp"
android:layout_marginTop="1.5dp"
android:layout_weight="2"
android:background="#7CFC00"
android:gravity="center"
android:text="@string/tw"
android:textSize="15pt" />
<Button
android:id="@+id/check13"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="3dp"
android:layout_marginLeft="1.5dp"
android:layout_marginRight="3dp"
android:layout_marginTop="1.5dp"
android:layout_weight="2"
android:background="#00FFFF"
android:gravity="center"
android:text="@string/th"
android:textSize="15pt" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
java代码:
package com.example.game02;
import java.util.Random;
import com.example.game02.db.DatabaseHelper;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ActivityOne extends Activity {
private TextView score = null;
private TextView sco = null;
private TextView pan1 = null;
private TextView pan2 = null;
private TextView pan3 = null;
private TextView hScore = null;
private Button on = null;
private Button tw = null;
private Button th = null;
int Score = 0;
int p1 = 0;
int p2 = 0;
int p3 = 0;
int b1 = 1;
int b2 = 2;
int b3 = 3;
boolean start;
boolean Run;
boolean End;
StringBuffer a = new StringBuffer();
TimeThread thread;
int end = 1;
EndThread eThread;
SQLiteDatabase db;
DatabaseHelper dbHelper;
int high;
String scoreNow=null;
Cursor cursor;
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
db.close();
cursor.close();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_one);
MyExit.getExit().addActivity(this);
score = (TextView)findViewById(R.id.score11);
sco = (TextView)findViewById(R.id.score12);
pan1 = (TextView)findViewById(R.id.textView11);
pan2 = (TextView)findViewById(R.id.textView12);
pan3 = (TextView)findViewById(R.id.textView13);
hScore = (TextView)findViewById(R.id.scoreView1);
on = (Button)findViewById(R.id.check11);
tw = (Button)findViewById(R.id.check12);
th = (Button)findViewById(R.id.check13);
on.setOnClickListener(new b1Liestener());
tw.setOnClickListener(new b2Liestener());
th.setOnClickListener(new b3Liestener());
score.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
start = false;
Run = true;
End = true;
a = new StringBuffer();
score.setOnClickListener(null);
score.setText("Score:");
thread = new TimeThread();
thread.start();
eThread = new EndThread();
eThread.start();
}
});
dbHelper = new DatabaseHelper(ActivityOne.this);
db = dbHelper.getWritableDatabase();
cursor = db.rawQuery("select score from user where id=?", new String[]{"1"});
while(cursor.moveToNext()){
scoreNow = cursor.getString(cursor.getColumnIndex("score"));
}
high = Integer.parseInt(scoreNow);
hScore.setText("High Score: "+String.valueOf(high));
}
public class TimeThread extends Thread {
@Override
public void run () {
while(Run) {
try {
{if(Score>5)
Thread.sleep(1550);
else if(Score>10)
Thread.sleep(1500);
else if(Score>20)
Thread.sleep(1450);
else if(Score>40)
Thread.sleep(1400);
else if(Score>80)
Thread.sleep(1350);
else if(Score>100)
Thread.sleep(1300);
else if(Score>110)
Thread.sleep(1250);
else if(Score>120)
Thread.sleep(1200);
else
Thread.sleep(1600);}
Message msg = new Message();
mHandler.sendMessage(msg);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class EndThread extends Thread {
@Override
public void run () {
while(End) {
try {
Thread.sleep(1000/3);
Message msg = new Message();
eHandler.sendMessage(msg);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private Handler eHandler = new Handler() {
@Override
public void handleMessage (Message msg) {
super.handleMessage(msg);
if(end==1)
{
pan1.setText("3");
pan2.setText("");
pan3.setText("");
}else if(end==2){
pan1.setText("");
pan2.setText("2");
pan3.setText("");
}else if(end==3){
pan1.setText("");
pan2.setText("");
pan3.setText("1");
}else{
pan1.setText("");
pan2.setText("GO");
pan3.setText("");
}
end++;
if(end==4)
{
End = false;
}
if(!eThread.isAlive())
{
end = 1;
}
}
};
private Handler mHandler = new Handler() {
@Override
public void handleMessage (Message msg) {
super.handleMessage(msg);
String x = Integer.toString(p1)+Integer.toString(p2)+Integer.toString(p3);
if(start&&(a.toString().length()<3||!a.toString().substring(0,3).equals(x)))
{
//thread.interrupt();
Run = false;
pan1.setText("Game");
pan2.setText("Over");
pan3.setText("!!!");
pan1.setBackgroundColor(Color.parseColor("#FFFFFF"));
pan2.setBackgroundColor(Color.parseColor("#FFFFFF"));
pan3.setBackgroundColor(Color.parseColor("#FFFFFF"));
if(!thread.isAlive())
{
score.setText(R.string.score);
score.setFocusable(true);
pan1.setText("");
pan2.setText("");
pan3.setText("");
score.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
start = false;
Run = true;
End = true;
a = new StringBuffer();
score.setOnClickListener(null);
score.setText("Score:");
thread = new TimeThread();
thread.start();
eThread = new EndThread();
eThread.start();
}
});
}
if(high<Score)
{
high = Score-1;
ContentValues values2 = new ContentValues();
values2.put("score",String.valueOf(high));
db.update("user", values2, "id=?", new String[]{"1"});
}
Score = 0;
sco.setText(Integer.toString(Score));
hScore.setText("High Score: "+String.valueOf(high));
}
else
{
if(Score==20)
{
ContentValues values3 = new ContentValues();
values3.put("score",String.valueOf(1));
db.update("user", values3, "id=?", new String[]{"12"});
}
sco.setText(Integer.toString(Score));
Score++;
Random random = new Random();
p1 = Math.abs(random.nextInt())%3+1;
p2 = Math.abs(random.nextInt())%3+1;
p3 = Math.abs(random.nextInt())%3+1;
pan1.setText(Integer.toString(p1));
switch(p1)
{
case 1:
pan1.setBackgroundColor(Color.parseColor("#FFC0CB"));
break;
case 2:
pan1.setBackgroundColor(Color.parseColor("#7CFC00"));
break;
case 3:
pan1.setBackgroundColor(Color.parseColor("#00FFFF"));
break;
}
pan2.setText(Integer.toString(p2));
switch(p2)
{
case 1:
pan2.setBackgroundColor(Color.parseColor("#FFC0CB"));
break;
case 2:
pan2.setBackgroundColor(Color.parseColor("#7CFC00"));
break;
case 3:
pan2.setBackgroundColor(Color.parseColor("#00FFFF"));
break;
}
pan3.setText(Integer.toString(p3));
switch(p3)
{
case 1:
pan3.setBackgroundColor(Color.parseColor("#FFC0CB"));
break;
case 2:
pan3.setBackgroundColor(Color.parseColor("#7CFC00"));
break;
case 3:
pan3.setBackgroundColor(Color.parseColor("#00FFFF"));
break;
}
}
a = new StringBuffer();
start = true;
//bo.setText("High Score:"+Integer.toString(heigh));
}
};
class b1Liestener implements OnClickListener{
@Override
public void onClick(View v) {
a.append(Integer.toString(b1));
}
}
class b2Liestener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//a = new StringBuffer();
//a.append(b);
a.append(Integer.toString(b2));
//b = a.toString();
//b = b.concat(Integer.toString(b2));
}
}
class b3Liestener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//a = new StringBuffer();
//a.append(b);
a.append(Integer.toString(b3));
//b = a.toString();
//b = b.concat(Integer.toString(b3));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_one, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
下载连接http://download.csdn.net/detail/u012951394/8889415
android java都初学中,想到怎么解决就怎么解决,感觉很多东西写复杂,见谅。
下一步尝试能让玩家自己选择几张图片来显示顺序点击,好像很简单,好像又很难--