




已阅读5页,还剩23页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
No.27第1章 游戏源码1.1 MinesweeperGamepackage com.VertexVerveInc.Games;import java.util.Random;import android.app.Activity;import android.graphics.Typeface;import android.os.Bundle;import android.os.Handler;import android.view.Gravity;import android.view.View;import android.view.View.OnClickListener;import android.view.View.OnLongClickListener;import android.widget.ImageButton;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TableRow.LayoutParams;import android.widget.TableLayout;import android.widget.TableRow;import android.widget.TextView;import android.widget.Toast;public class MinesweeperGame extends Activityprivate TextView txtMineCount;private TextView txtTimer;private ImageButton btnSmile;private TableLayout mineField; / table layout to add mines toprivate Block blocks; / blocks for mine fieldprivate int blockDimension = 24; / width of each blockprivate int blockPadding = 2; / padding between blocksprivate int numberOfRowsInMineField = 9;private int numberOfColumnsInMineField = 9;private int totalNumberOfMines = 10;/ timer to keep track of time elapsedprivate Handler timer = new Handler();private int secondsPassed = 0;private boolean isTimerStarted; / check if timer already started or notprivate boolean areMinesSet; / check if mines are planted in blocksprivate boolean isGameOver;private int minesToFind; / number of mines yet to be discoveredOverridepublic void onCreate(Bundle savedInstanceState)super.onCreate(savedInstanceState);setContentView(R.layout.main);txtMineCount = (TextView) findViewById(R.id.MineCount);txtTimer = (TextView) findViewById(R.id.Timer);/ set font style for timer and mine count to LCD styleTypeface lcdFont = Typeface.createFromAsset(getAssets(),fonts/lcd2mono.ttf);txtMineCount.setTypeface(lcdFont);txtTimer.setTypeface(lcdFont);btnSmile = (ImageButton) findViewById(R.id.Smiley);btnSmile.setOnClickListener(new OnClickListener()Overridepublic void onClick(View view)endExistingGame();startNewGame(););mineField = (TableLayout)findViewById(R.id.MineField);showDialog(Click smiley to start New Game, 2000, true, false);private void startNewGame()/ plant mines and do rest of the calculationscreateMineField();/ display all blocks in UIshowMineField();minesToFind = totalNumberOfMines;isGameOver = false;secondsPassed = 0;private void showMineField()/ remember we will not show 0th and last Row and Columns/ they are used for calculation purposes onlyfor (int row = 1; row numberOfRowsInMineField + 1; row+)TableRow tableRow = new TableRow(this); tableRow.setLayoutParams(new LayoutParams(blockDimension + 2 * blockPadding) * numberOfColumnsInMineField, blockDimension + 2 * blockPadding);for (int column = 1; column numberOfColumnsInMineField + 1; column+)blocksrowcolumn.setLayoutParams(new LayoutParams( blockDimension + 2 * blockPadding, blockDimension + 2 * blockPadding); blocksrowcolumn.setPadding(blockPadding, blockPadding, blockPadding, blockPadding);tableRow.addView(blocksrowcolumn);mineField.addView(tableRow,new TableLayout.LayoutParams( (blockDimension + 2 * blockPadding) * numberOfColumnsInMineField, blockDimension + 2 * blockPadding); private void endExistingGame()stopTimer(); / stop if timer is runningtxtTimer.setText(000); / revert all texttxtMineCount.setText(000); / revert mines countbtnSmile.setBackgroundResource(R.drawable.smile);/ remove all rows from mineField TableLayoutmineField.removeAllViews();/ set all variables to support end of gameisTimerStarted = false;areMinesSet = false;isGameOver = false;minesToFind = 0;private void createMineField()/ we take one row extra row for each side/ overall two extra rows and two extra columns/ first and last row/column are used for calculations purposes only/ x|xxxxxxxxxxxxxx|x/ -/ x| |x/ x| |x/ -/ x|xxxxxxxxxxxxxx|x/ the row and columns marked as x are just used to keep counts of near by minesblocks = new BlocknumberOfRowsInMineField + 2numberOfColumnsInMineField + 2;for (int row = 0; row numberOfRowsInMineField + 2; row+)for (int column = 0; column 0) & !isGameOver)int nearbyFlaggedBlocks = 0;for (int previousRow = -1; previousRow 2; previousRow+)for (int previousColumn = -1; previousColumn 2; previousColumn+)if (blockscurrentRow + previousRowcurrentColumn + previousColumn.isFlagged()nearbyFlaggedBlocks+;/ if flagged block count is equal to nearby mine count/ then open nearby blocksif (nearbyFlaggedBlocks = blockscurrentRowcurrentColumn.getNumberOfMinesInSorrounding()for (int previousRow = -1; previousRow 2; previousRow+)for (int previousColumn = -1; previousColumn 2; previousColumn+)/ dont open flagged blocksif (!blockscurrentRow + previousRowcurrentColumn + previousColumn.isFlagged()/ open blocks till we get numbered blockrippleUncover(currentRow + previousRow, currentColumn + previousColumn);/ did we clicked a mineif (blockscurrentRow + previousRowcurrentColumn + previousColumn.hasMine()/ oops game overfinishGame(currentRow + previousRow, currentColumn + previousColumn);/ did we win the gameif (checkGameWin()/ mark game as winwinGame();/ as we no longer want to judge this gesture so return/ not returning from here will actually trigger other action/ which can be marking as a flag or question mark or blankreturn true;/ if clicked block is enabled, clickable or flaggedif (blockscurrentRowcurrentColumn.isClickable() & (blockscurrentRowcurrentColumn.isEnabled() | blockscurrentRowcurrentColumn.isFlagged()/ for long clicks set:/ 1. empty blocks to flagged/ 2. flagged to question mark/ 3. question mark to blank/ case 1. set blank block to flaggedif (!blockscurrentRowcurrentColumn.isFlagged() & !blockscurrentRowcurrentColumn.isQuestionMarked()blockscurrentRowcurrentColumn.setBlockAsDisabled(false);blockscurrentRowcurrentColumn.setFlagIcon(true);blockscurrentRowcurrentColumn.setFlagged(true);minesToFind-; /reduce mine countupdateMineCountDisplay();/ case 2. set flagged to question markelse if (!blockscurrentRowcurrentColumn.isQuestionMarked()blockscurrentRowcurrentColumn.setBlockAsDisabled(true);blockscurrentRowcurrentColumn.setQuestionMarkIcon(true);blockscurrentRowcurrentColumn.setFlagged(false);blockscurrentRowcurrentColumn.setQuestionMarked(true);minesToFind+; / increase mine countupdateMineCountDisplay();/ case 3. change to blank squareelseblockscurrentRowcurrentColumn.setBlockAsDisabled(true);blockscurrentRowcurrentColumn.clearAllIcons();blockscurrentRowcurrentColumn.setQuestionMarked(false);/ if it is flagged then increment mine countif (blockscurrentRowcurrentColumn.isFlagged()minesToFind+; / increase mine countupdateMineCountDisplay();/ remove flagged statusblockscurrentRowcurrentColumn.setFlagged(false);updateMineCountDisplay(); / update mine displayreturn true;);private boolean checkGameWin()for (int row = 1; row numberOfRowsInMineField + 1; row+)for (int column = 1; column numberOfColumnsInMineField + 1; column+)if (!blocksrowcolumn.hasMine() & blocksrowcolumn.isCovered()return false;return true;private void updateMineCountDisplay()if (minesToFind 0)txtMineCount.setText(Integer.toString(minesToFind);else if (minesToFind 10)txtMineCount.setText(00 + Integer.toString(minesToFind);else if (minesToFind 100)txtMineCount.setText(0 + Integer.toString(minesToFind);elsetxtMineCount.setText(Integer.toString(minesToFind);private void winGame()stopTimer();isTimerStarted = false;isGameOver = true;minesToFind = 0; /set mine count to 0/set icon to cool dudebtnSmile.setBackgroundResource(R.drawable.cool);updateMineCountDisplay(); / update mine count/ disable all buttons/ set flagged all un-flagged blocksfor (int row = 1; row numberOfRowsInMineField + 1; row+)for (int column = 1; column numberOfColumnsInMineField + 1; column+)blocksrowcolumn.setClickable(false);if (blocksrowcolumn.hasMine()blocksrowcolumn.setBlockAsDisabled(false);blocksrowcolumn.setFlagIcon(true);/ show messageshowDialog(You won in + Integer.toString(secondsPassed) + seconds!, 1000, false, true);private void finishGame(int currentRow, int currentColumn)isGameOver = true; / mark game as overstopTimer(); / stop timerisTimerStarted = false;btnSmile.setBackgroundResource(R.drawable.sad);/ show all mines/ disable all blocksfor (int row = 1; row numberOfRowsInMineField + 1; row+)for (int column = 1; column numberOfColumnsInMineField + 1; column+)/ disable blockblocksrowcolumn.setBlockAsDisabled(false);/ block has mine and is not flaggedif (blocksrowcolumn.hasMine() & !blocksrowcolumn.isFlagged()/ set mine iconblocksrowcolumn.setMineIcon(false);/ block is flagged and doesnt not have mineif (!blocksrowcolumn.hasMine() & blocksrowcolumn.isFlagged()/ set flag iconblocksrowcolumn.setFlagIcon(false);/ block is flaggedif (blocksrowcolumn.isFlagged()/ disable the blockblocksrowcolumn.setClickable(false);/ trigger mineblockscurrentRowcurrentColumn.triggerMine();/ show messageshowDialog(You tried for + Integer.toString(secondsPassed) + seconds!, 1000, false, false);private void setMines(int currentRow, int currentColumn)/ set mines excluding the location where user clickedRandom rand = new Random();int mineRow, mineColumn;for (int row = 0; row totalNumberOfMines; row+)mineRow = rand.nextInt(numberOfColumnsInMineField);mineColumn = rand.nextInt(numberOfRowsInMineField);if (mineRow + 1 != currentColumn) | (mineColumn + 1 != currentRow)if (blocksmineColumn + 1mineRow + 1.hasMine()row-; / mine is already there, dont repeat for same block/ plant mine at this locationblocksmineColumn + 1mineRow + 1.plantMine();/ exclude the user clicked locationelserow-;int nearByMineCount;/ count number of mines in surrounding blocks for (int row = 0; row numberOfRowsInMineField + 2; row+)for (int column = 0; column numberOfColumnsInMineField + 2; column+)/ for each block find nearby mine countnearByMineCount = 0;if (row != 0) & (row != (numberOfRowsInMineField + 1) & (column != 0) & (column != (numberOfColumnsInMineField + 1)/ check in all nearby blocksfor (int previousRow = -1; previousRow 2; previousRow+)for (int previousColumn = -1; previousColumn 2; previousColumn+)if (blocksrow + previousRowcolumn + previousColumn.hasMine()/ a mine was found so increment the counternearByMineCount+;blocksrowcolumn.setNumberOfMinesInSurrounding(nearByMineCount);/ for side rows (0th and last row/column)/ set count as 9 and mark it as openedelseblocksrowcolumn.setNumberOfMinesInSurrounding(9);blocksrowcolumn.OpenBlock();private void rippleUncover(int rowClicked, int columnClicked)/ dont open flagged or mined rowsif (blocksrowClickedcolumnClicked.hasMine() | blocksrowClickedcolumnClicked.isFlagged()return;/ open clicked blockblocksrowClickedcolumnClicked.OpenBlock();/ if clicked block have nearby mines then dont open furtherif (blocksrowClickedcolumnClicked.getNumberOfMinesInSorrounding() != 0 )return;/ open next 3 rows and 3 columns recursivelyfor (int row = 0; row 3; row+)for (int column = 0; column 0) & (columnClicked + column - 1 0)& (rowClicked + row - 1 numberOfRowsInMineField + 1) & (columnClicked + column - 1 numberOfColumnsInMineField + 1)rippleUncover(rowClicked + row - 1, columnClicked + column - 1 ); return;public void startTimer()if (secondsPassed = 0) timer.removeCallbacks(updateTimeElasped);/ tell timer to run call back after 1 secondtimer.postDelayed(updateTimeElasped, 1000);public void stopTimer()/ disable call backstimer.removeCallbacks(updateTimeElasped);/ timer call back when timer is tickedprivate Runnable updateTimeElasped = new Runnable()public void run()long currentMilliseconds = System.currentTimeMillis();+secondsPassed;if (secondsPassed 10)txtTimer.setText(00 + Integer.toString(secondsPassed);else if (secondsPassed 100)txtTimer.setText(0 + Integer.toString(secondsPassed);elsetxtTimer.setText(Integer.toString(secondsPassed);/ add notificationtimer.postAtTime(this, currentMilliseconds);/ notify to call back after 1 seconds/ basically to remain in the timer looptimer.postDelayed(updateTimeElasped, 1000);private void showDialog(String message, int milliseconds, boolean useSmileImage, boolean useCoolImage)/ show messageToast dialog = Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG);dialog.setGravity(Gravity.CENTER, 0, 0);LinearLayout dialogView = (LinearLayout) dialog.getView();ImageView coolImage = new ImageView(getApplicationContext();if (useSmileImage)coolImage.setImageResource(R.drawable.smile);else if (useCoolImage)coolImage.setImageResource(R.drawable.cool);elsecoolImage.setImageResource(R.drawable.sad);dialogView.addView(coolImage, 0);dialog.setDuration(milliseconds);dialog.show();1.2 Blockpackage com.VertexVerveInc.Games;import android.content.Context;import android.graphics.Color;import android.graphics.Typeface;import android.util.AttributeSet;import android.widget.Button;public class Block extends Buttonprivate boolean isCovered; / is block covered yetprivate boolean isMined; / does the block has a mine underneathprivate boolean isFlagged; / is block flagged as a potential mineprivate boolean isQuestionMarked; / is block question markedprivate boolean isClickable; / can block accept click eventsprivate int numberOfMinesInSurrounding; / number of mines in nearby blockspublic Block(Context context)super(context);public Block(Context context, AttributeSet attrs)super(context, attrs);public Block(Context context, AttributeSet attrs, int defStyle)super(context, attrs, defStyle);/ set default properties for the blockpublic void setDefaults()isCovered = true;isMined = false;isFlagged = false;isQuestionMarked = false;isClickable = true;numberOfMinesInSurrounding = 0;this.setBackgroundResource(R.drawable.square_blue);setBoldFont();/ mark the block as disabled/opened/ update the number of nearby minespublic void setNumberOfSurroundingMines(int number)this.setBackgroundResource(R.drawable.square_grey);updateNumber(number);/ set mine icon for block/ set block as disabled/opened if false is passedpublic void setMineIcon(boolean enabled)this.setText(M);if (!enabled)this.setBackgroundResource(R.drawable.square_grey);this.setTextColor(Color.RED);elsethis.setTextColor(Color.BLACK);/ set mine as flagged/ set block as disabled/opened if false is passedpublic void setFlagIcon(boolean enabled)this.setText(F);if (!enabled)this.setBackgroundResource(R.drawable.square_grey);this.setTextColor(Color.RED);elsethis.setTextColor(Color.BLACK);/ set mine as question mark/ set block as disable
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 兽医专业要写毕业论文吗
- 测绘系毕业论文
- 毕业论文专业一栏怎么写
- 别墅庭院地砖墙砖铺贴劳务分包合同
- 2025云南省文山州西畴县第一人民医院招聘编外人员(1人)笔试备考题库及答案解析
- 2025新疆巴音郭楞州和硕县面向社会招聘社区工作者7人笔试模拟试题及答案解析
- 2025山东潍坊天立学校教师招聘7人考试参考题库附答案解析
- 新能源专业毕业论文大专
- 英语本科毕业论文提纲
- 2025年奢华手表选购合同协议
- 小学音乐《村晚》优质课件设计
- 竞选团支书幽默大气简短六篇
- 东锅300MW锅炉说明书
- 知名投资机构和投资人联系方式汇总
- (完整word版)教育部发布《3-6岁儿童学习与发展指南》(全文)
- 混凝土监理旁站记录
- 部门会签单模板
- 宫颈环扎术护理常规
- G12《贷款质量迁徙情况表》填报说明
- 县城市管理领域集中行使行政处罚权工作衔接规范(试行)
- 结肠息肉的护理查房精编ppt
评论
0/150
提交评论