android开发-写个扫雷玩玩

相信以前都玩过扫雷吧,比较闲,自己写了个玩,性能算法什么的都没考虑。。

下载地址:http://download.csdn.net/detail/u010697537/8728967

以下就是我2个小时的成果,很简单的demo

大致思路:

1.定好10*10的方格,设定20个雷,并随机雷的位置

2.遍历所有的方格位置,计算方格上显示的数字或者雷或者0

3.点击方格,判断当前方格位置的内容,长按标记是不是雷


难点:1.计算各个方格中该显示的数字(比较懒,直接用try catch来防止2维数组下标越界)

2.点击空白(边上没有雷的方格),边上的一块区域内的方格全部显示内容

这些都在代码里面有,不多说了,直接上代码:

<pre name="code" class="java">package com.example.winmine;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;

public class MainActivity extends Activity {
	private GridView gridview;
	private List<Integer> list;
	private List<Integer> numFoundList;
	private List<Integer> mineFoundList;
	private Context context;
	private int itemWidth;
	private int sum;
	private static final int TYPE_MINE = -1;
	private static final int TYPE_NULL = 0;
	private static final int LINE = 10;
	private static final int SUM_MINE = 20;
	boolean[][] isNullArr;
//	private List<Point> nullPosList;
	/**
	 * 点击某个格子,边上一起也显示的集合
	 * */
	private Set<Integer> nullPosSet;
	private List<Integer> nullPosList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		itemWidth = getResources().getDisplayMetrics().widthPixels/10;
		gridview = (GridView) findViewById(R.id.gridview);
		context = this;
		sum = LINE*LINE;
		getList();
		gridview.setAdapter(new MyAdapter());
		gridview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if(list.get(arg2)==TYPE_MINE){
					new AlertDialog.Builder(context).setMessage("你是sb!!")
							.setPositiveButton("确定", null).show();
				}else {
					if(hasNull(arg2)){
						nullPosSet = new HashSet<Integer>();
						nullPosList = new ArrayList<Integer>();
						getNullList(arg2);
						for(int i:nullPosSet){
							((TextView)arg0.getChildAt(i)).setTextColor(getResources().getColor(android.R.color.black));
							arg0.getChildAt(i).setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));
							arg0.getChildAt(i).setOnClickListener(null);
							numFoundList.add(i);
						}
						
					}else{
						((TextView)arg1).setTextColor(getResources().getColor(android.R.color.black));
						arg1.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));
						arg1.setOnClickListener(null);
						numFoundList.add(arg2);
					}
					Log.e("@@@", "gameList.size()=="+numFoundList.size());
					if(numFoundList.size()>=(LINE*LINE-SUM_MINE)){
						new AlertDialog.Builder(context).setMessage("success!!")
						.setPositiveButton("确定", null).show();
						
					}
				}
				
			}
		});
		gridview.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				if(arg1.getTag()==null){
					arg1.setTag(list.get(arg2));
					((TextView)arg1).setText("*");
					((TextView)arg1).setTextColor(getResources().getColor(android.R.color.black));
					arg1.setBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
				}else{
					((TextView)arg1).setText(arg1.getTag().toString());
					((TextView)arg1).setTextColor(getResources().getColor(android.R.color.white));
					arg1.setBackgroundColor(getResources().getColor(android.R.color.white));
					arg1.setTag(null);
				}
				
				return true;
			}
		});
	}

	public void getList() {
		list = new ArrayList<Integer>();
		numFoundList = new ArrayList<Integer>();
		Set<Integer> sets = new HashSet<Integer>();
		Random random = new Random();
		while (sets.size() < SUM_MINE) {
			sets.add(random.nextInt(sum));
		}
		for(int i=0;i<sum;i++){
			if(sets.contains(i)){
				list.add(TYPE_MINE);
			}else{
				list.add(TYPE_NULL);
			}
		}

		int[][] array = new int[LINE][LINE];
		isNullArr = new boolean[LINE][LINE];
		for(int i=0;i<LINE;i++){
			for(int j=0;j<LINE;j++){
				array[i][j] = list.get(i*LINE+j);
			}
		}
		for(int i=0;i<LINE;i++){
			for(int j=0;j<LINE;j++){
				int num = list.get(i*LINE+j);
				if(num!=TYPE_MINE){
					try{
						num+=array[i-1][j-1];
					}catch(Exception e){}
					try{
						num+=array[i-1][j];
					}catch(Exception e){}
					try{
						num+=array[i-1][j+1];
					}catch(Exception e){}
					try{
						num+=array[i][j-1];
					}catch(Exception e){}
					try{
						num+=array[i][j+1];
					}catch(Exception e){}
					try{
						num+=array[i+1][j-1];
					}catch(Exception e){}
					try{
						num+=array[i+1][j];
					}catch(Exception e){}
					try{
						num+=array[i+1][j+1];
					}catch(Exception e){}
					list.set(i*LINE+j, -num);
					if(num==TYPE_NULL){
						isNullArr[i][j]=true;

					}
				}
			}
		}
		
		
	}
	
	private boolean hasNull(int index){
		try{
			if(isNullArr[index/LINE-1][index%LINE-1])return true;
		}catch(Exception e){}
		try{
			if(isNullArr[index/LINE-1][index%LINE])return true;
		}catch(Exception e){}
		try{
			if(isNullArr[index/LINE-1][index%LINE+1])return true;
		}catch(Exception e){}
		try{
			if(isNullArr[index/LINE][index%LINE-1])return true;
		}catch(Exception e){}
		try{
			if(isNullArr[index/LINE][index%LINE])return true;
		}catch(Exception e){}
		try{
			if(isNullArr[index/LINE][index%LINE+1])return true;
		}catch(Exception e){}
		try{
			if(isNullArr[index/LINE+1][index%LINE-1])return true;
		}catch(Exception e){}
		try{
			if(isNullArr[index/LINE+1][index%LINE])return true;
		}catch(Exception e){}
		try{
			if(isNullArr[index/LINE+1][index%LINE+1])return true;
		}catch(Exception e){}
		return false;
	}
	
	private void getNullList(List<Integer> posList){
		for(int p:posList){
			getNullList(p);
		}
	}
	
	private void getNullList(int index){
		if(nullPosList.contains(index))return;
		nullPosList.add(index);
			List<Integer> nullPos = new ArrayList<Integer>();
			try{
				if(isNullArr[index/LINE-1][index%LINE-1]){
					if(!nullPosList.contains(index-LINE-1))
						nullPos.add(index-LINE-1);
				}
				if(list.get(index-LINE-1)!=TYPE_MINE)
					nullPosSet.add(index-LINE-1);
			}catch(Exception e){}
			try{
				if(isNullArr[index/LINE-1][index%LINE]){
					if(!nullPosList.contains(index-LINE))
						nullPos.add(index-LINE);
				}
				if(list.get(index-LINE)!=TYPE_MINE) 
				nullPosSet.add(index-LINE);
			}catch(Exception e){}
			try{
				if(isNullArr[index/LINE-1][index%LINE+1]){
					if(!nullPosList.contains(index-LINE+1))
						nullPos.add(index-LINE+1);
				}
				if(list.get(index-LINE+1)!=TYPE_MINE)
				nullPosSet.add(index-LINE+1);
			}catch(Exception e){}
			try{
				if(isNullArr[index/LINE][index%LINE-1]){
					if(!nullPosList.contains(index-1))
						nullPos.add(index-1);
				}
				if(list.get(index-1)!=TYPE_MINE)
				nullPosSet.add(index-1);
			}catch(Exception e){}
			try{
				if(isNullArr[index/LINE][index%LINE+1]){
					if(!nullPosList.contains(index+1))
						nullPos.add(index+1);
				}
				if(list.get(index+1)!=TYPE_MINE)
				nullPosSet.add(index+1);
			}catch(Exception e){}
			try{
				if(isNullArr[index/LINE+1][index%LINE-1]){
					if(!nullPosList.contains(index+LINE-1))
						nullPos.add(index+LINE-1);
				}
				if(list.get(index+LINE-1)!=TYPE_MINE)
				nullPosSet.add(index+LINE-1);
			}catch(Exception e){}
			try{
				if(isNullArr[index/LINE+1][index%LINE]){
					if(!nullPosList.contains(index+LINE))
						nullPos.add(index+LINE);
				}
				if(list.get(index+LINE)!=TYPE_MINE)
				nullPosSet.add(index+LINE);
			}catch(Exception e){}
			try{
				if(isNullArr[index/LINE+1][index%LINE+1]){
					if(!nullPosList.contains(index+LINE+1))
						nullPos.add(index+LINE+1);
				}
				if(list.get(index+LINE+1)!=TYPE_MINE)
				nullPosSet.add(index+LINE+1);
			}catch(Exception e){}
			getNullList(nullPos);
	}
	
	class MyAdapter extends BaseAdapter{
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
			arg1 = LayoutInflater.from(context).inflate(R.layout.item, null);
			AbsListView.LayoutParams params = new AbsListView.LayoutParams(itemWidth-1, itemWidth);
			arg1.setLayoutParams(params);
			if(list.get(arg0)==TYPE_MINE){
				((TextView)arg1).setText("*");
			}else if(list.get(arg0)==TYPE_NULL){
				((TextView)arg1).setText("");
			}else{
				((TextView)arg1).setText(""+list.get(arg0));
			}
			
			return arg1;
		}
		
	}

}





<pre name="code" class="html"><TextView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:textColor="@android:color/white" android:background="@android:color/white" android:gravity="center"/>
 

temWidth);arg1.setLayoutParams(params);if(list.get(arg0)==TYPE_MINE){((TextView)arg1).setText("*");}else if(list.get(arg0)==TYPE_NULL){((TextView)arg1).setText("");}else{((TextView)arg1).setText(""+list.get(arg0));}return arg1;}}}
<RelativeLayout 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:background="@android:color/black"
    tools:context=".MainActivity" >

    <GridView
        android:id="@+id/gridview"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numColumns="10"
        android:verticalSpacing="1.0px" 
        android:horizontalSpacing="1.0px"
        />

</RelativeLayout>

 

 


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
安卓 扫雷源码 添加重新开始按钮支持 Android studio ====================================== Risky Project Location: ----------------------- The tools *should* handle project locations in any directory. However, due to bugs, placing projects in directories containing spaces in the path, or characters like ", ' and &, have had issues. We're working to eliminate these bugs, but to save yourself headaches you may want to move your project to a location where this is not a problem. D:\Program Files\android_s_workplace\terrysaolei - Ignored Files: -------------- The following files were *not* copied into the new Gradle project; you should evaluate whether these are still needed in your project and if so manually move them: * ic_launcher-web.png * proguard-project.txt Moved Files: ------------ Android Gradle projects use a different directory structure than ADT Eclipse projects. Here's how the projects were restructured: * AndroidManifest.xml => app\src\main\AndroidManifest.xml * assets\ => app\src\main\assets * res\ => app\src\main\res\ * src\ => app\src\main\java\ Next Steps: ----------- You can now build the project. The Gradle project needs network connectivity to download dependencies. Bugs: ----- If for some reason your project does not build, and you determine that it is due to a bug or limitation of the Eclipse to Gradle importer, please file a bug at http://b.android.com with category Component-Tools. (This import summary is for your information only, and can be deleted after import once you are satisfied with the results.)
好的,下面是一个简单的扫雷游戏的实现步骤: 1. 创建一个 Android 项目,在布局文件中添加一个 GridView 用于显示扫雷游戏的方格。 2. 创建一个二维数组作为扫雷游戏的地图,其中每个元素表示一个方格,用数字表示该方格的状态:-1 表示该方格为地雷,0 表示该方格为未翻开状态,1~8 表示该方格周围的地雷数量。 3. 在 Activity 中实现 GridView 的适配器,将二维数组中的状态显示在 GridView 上。 4. 给 GridView 添加点击事件,当用户点击一个方格时,根据该方格的状态进行相应的操作:如果该方格为地雷,则游戏失败;如果该方格周围没有地雷,则递归地翻开周围的方格;否则显示该方格周围的地雷数量。 5. 在点击事件中判断游戏是否结束,如果未结束则继续游戏,否则弹出游戏结束的提示框。 6. 可以添加计时器和地雷数量的显示,以增加游戏的趣味性。 以下是一个简单的实现代码供参考: MainActivity.java ```java public class MainActivity extends AppCompatActivity { private static final int ROWS = 10; // 行数 private static final int COLS = 10; // 列数 private static final int MINES = 10; // 地雷数量 private int[][] map; // 地图 private boolean[][] opened; // 是否已翻开 private boolean[][] marked; // 是否已标记为地雷 private GridView gridView; private TextView tvTime; private TextView tvMines; private CountDownTimer timer; private int time; // 游戏时间 private int minesLeft; // 剩余地雷数量 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gridView = findViewById(R.id.grid_view); tvTime = findViewById(R.id.tv_time); tvMines = findViewById(R.id.tv_mines); initMap(); initGridView(); startTimer(); } private void initMap() { map = new int[ROWS][COLS]; opened = new boolean[ROWS][COLS]; marked = new boolean[ROWS][COLS]; Random random = new Random(); int mines = 0; while (mines < MINES) { int row = random.nextInt(ROWS); int col = random.nextInt(COLS); if (map[row][col] != -1) { map[row][col] = -1; mines++; } } for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { if (map[i][j] == -1) { continue; } int count = 0; if (i > 0 && j > 0 && map[i - 1][j - 1] == -1) count++; if (i > 0 && map[i - 1][j] == -1) count++; if (i > 0 && j < COLS - 1 && map[i - 1][j + 1] == -1) count++; if (j > 0 && map[i][j - 1] == -1) count++; if (j < COLS - 1 && map[i][j + 1] == -1) count++; if (i < ROWS - 1 && j > 0 && map[i + 1][j - 1] == -1) count++; if (i < ROWS - 1 && map[i + 1][j] == -1) count++; if (i < ROWS - 1 && j < COLS - 1 && map[i + 1][j + 1] == -1) count++; map[i][j] = count; } } minesLeft = MINES; } private void initGridView() { GridViewAdapter adapter = new GridViewAdapter(this, ROWS, COLS); gridView.setAdapter(adapter); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { int row = position / COLS; int col = position % COLS; if (opened[row][col] || marked[row][col]) { return; } if (map[row][col] == -1) { gameOver(false); return; } open(row, col); checkWin(); } }); gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { int row = position / COLS; int col = position % COLS; if (!opened[row][col]) { marked[row][col] = !marked[row][col]; gridView.invalidateViews(); if (marked[row][col]) { minesLeft--; } else { minesLeft++; } tvMines.setText(getString(R.string.mines_left, minesLeft)); } return true; } }); } private void open(int row, int col) { if (opened[row][col] || marked[row][col]) { return; } opened[row][col] = true; gridView.invalidateViews(); if (map[row][col] == 0) { if (row > 0 && col > 0) open(row - 1, col - 1); if (row > 0) open(row - 1, col); if (row > 0 && col < COLS - 1) open(row - 1, col + 1); if (col > 0) open(row, col - 1); if (col < COLS - 1) open(row, col + 1); if (row < ROWS - 1 && col > 0) open(row + 1, col - 1); if (row < ROWS - 1) open(row + 1, col); if (row < ROWS - 1 && col < COLS - 1) open(row + 1, col + 1); } } private void checkWin() { boolean win = true; for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { if (!opened[i][j] && map[i][j] != -1) { win = false; break; } } } if (win) { gameOver(true); } } private void startTimer() { timer = new CountDownTimer(Long.MAX_VALUE, 1000) { @Override public void onTick(long millisUntilFinished) { time++; tvTime.setText(getString(R.string.time, time)); } @Override public void onFinish() { } }; timer.start(); } private void stopTimer() { if (timer != null) { timer.cancel(); } } private void gameOver(boolean win) { stopTimer(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(win ? R.string.win : R.string.lose); builder.setMessage(getString(R.string.time_used, time)); builder.setPositiveButton(R.string.restart, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { resetGame(); } }); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); builder.setCancelable(false); builder.show(); } private void resetGame() { initMap(); gridView.invalidateViews(); startTimer(); } private class GridViewAdapter extends BaseAdapter { private Context context; private int rows; private int cols; public GridViewAdapter(Context context, int rows, int cols) { this.context = context; this.rows = rows; this.cols = cols; } @Override public int getCount() { return rows * cols; } @Override public Object getItem(int position) { int row = position / cols; int col = position % cols; return map[row][col]; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { int row = position / cols; int col = position % cols; if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.item_grid_view, parent, false); } TextView textView = convertView.findViewById(R.id.tv); if (opened[row][col]) { if (map[row][col] == -1) { textView.setText(R.string.mine); textView.setTextColor(Color.RED); } else if (map[row][col] == 0) { textView.setText(""); } else { textView.setText(String.valueOf(map[row][col])); } textView.setBackgroundResource(R.drawable.bg_opened); } else if (marked[row][col]) { textView.setText(R.string.flag); textView.setBackgroundResource(R.drawable.bg_closed); } else { textView.setText(""); textView.setBackgroundResource(R.drawable.bg_closed); } return convertView; } } } ``` activity_main.xml ```xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <GridView android:id="@+id/grid_view" android:layout_width="match_parent" android:layout_height="match_parent" android:numColumns="10" android:horizontalSpacing="1dp" android:verticalSpacing="1dp" android:stretchMode="columnWidth" /> <LinearLayout android:id="@+id/layout_info" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_alignParentBottom="true" android:background="#BBFFFFFF"> <TextView android:id="@+id/tv_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="24sp" android:textColor="#FF0000" android:padding="8dp" android:text="00:00" /> <TextView android:id="@+id/tv_mines" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="24sp" android:textColor="#FF0000" android:padding="8dp" android:text="@string/mines_left" /> </LinearLayout> </RelativeLayout> ``` item_grid_view.xml ```xml <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:textSize="24sp" android:textColor="#000000" android:padding="8dp" /> ``` strings.xml ```xml <resources> <string name="app_name">Minesweeper</string> <string name="time">Time: %d</string> <string name="mines_left">Mines left: %d</string> <string name="win">You win!</string> <string name="lose">You lose!</string> <string name="restart">Restart</string> <string name="mine">X</string> <string name="flag">F</string> <string name="time_used">Time used: %d seconds</string> </resources> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值