游戏2048的JAVA源代码

合集下载

2048源码

2048源码
getLayout(width, height);
createBitmapCells();
createBackgroundBitmap(width, height);
createOverlays();
}
MianGame游戏主要逻辑
package com.tpcstld.twozerogame;
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));
if (score >= highScore) {
highScore = score;
recordHighScore();
}
score = 0;
gameState = GAME_NORMAL;
addStartTiles();
public AnimationGrid aGrid;
final int numSquaresX = 4;
final int numSquaresY = 4;

java实现2048小游戏

java实现2048小游戏

java实现2048⼩游戏本⽂实例为⼤家分享了java实现2048⼩游戏的具体代码,供⼤家参考,具体内容如下⼀、实现效果⼆、实现代码Check表⽰格⼦,GameView实现游戏视图界⾯及功能,是核⼼。

Check.javaimport java.awt.Color;import java.awt.Font;// ⽅格类public class Check {public int value;Font font1 = new Font("宋体", Font.BOLD, 46);Font font2 = new Font("宋体", Font.BOLD, 40);Font font3 = new Font("宋体", Font.BOLD, 34);Font font4 = new Font("宋体", Font.BOLD, 28);Font font5 = new Font("宋体", Font.BOLD, 22);public Check() {value = 0; //value为⽅格中数字}//字体颜⾊public Color getForeground() {switch (value) {case 0:return new Color(0xcdc1b4);//0的颜⾊与背景⾊⼀致,相当于没有数字case 2:case 4:return Color.BLACK;default:return Color.WHITE;}}//字体背景颜⾊,即⽅格颜⾊public Color getBackground() {switch (value) {case 0:return new Color(0xcdc1b4);case 2:return new Color(0xeee4da);case 4:return new Color(0xede0c8);case 8:return new Color(0xf2b179);case 16:return new Color(0xf59563);case 32:return new Color(0xf67c5f);case 64:return new Color(0xf65e3b);case 128:return new Color(0xedcf72);case 256:return new Color(0xedcc61);case 512:return new Color(0xedc850);case 1024:return new Color(0xedc53f);case 2048:return new Color(0xedc22e);case 4096:return new Color(0x65da92);case 8192:return new Color(0x5abc65);case 16384:return new Color(0x248c51);default:return new Color(0x248c51);}}public Font getCheckFont() {if (value < 10) {return font1;}if (value < 100) {return font2;}if (value < 1000) {return font3;}if (value < 10000) {return font4;}return font5;}}GameView.javaimport java.awt.*;import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList;import java.util.List;import java.util.Random;import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel;public class GameView{private static final int jframeWidth = 405;//窗⼝宽⾼private static final int jframeHeight = 530;private static int score = 0;Font topicFont = new Font("微软雅⿊", Font.BOLD, 50);//主题字体Font scoreFont = new Font("微软雅⿊", Font.BOLD, 28);//得分字体Font explainFont = new Font("宋体", Font.PLAIN,20);//提⽰字体private JFrame jframeMain;private JLabel jlblTitle;private JLabel jlblScoreName;private JLabel jlblScore;private JLabel jlblTip;private GameBoard gameBoard;public GameView() {init();}public void init() {//1、创建窗⼝jframeMain = new JFrame("2048⼩游戏");jframeMain.setSize(jframeWidth, jframeHeight);jframeMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);jframeMain.setLocationRelativeTo(null);//窗⼝显⽰位置居中jframeMain.setResizable(false);jframeMain.setLayout(null);//设置绝对布局,以便后⾯可以⽤setBounds设置位置 jlblTitle = new JLabel("2048", JLabel.CENTER);jlblTitle.setFont(topicFont);jlblTitle.setForeground(Color.BLACK);jlblTitle.setBounds(50, 0, 150, 60);jframeMain.add(jlblTitle);//2、框架窗⼝搭建好,则需向⾥⾯开始添加内容//设置字体及其颜⾊、位置jlblScoreName = new JLabel("得分", JLabel.CENTER);jlblScoreName.setFont(scoreFont);jlblScoreName.setForeground(Color.WHITE);jlblScoreName.setOpaque(true);jlblScoreName.setBackground(Color.GRAY);jlblScoreName.setBounds(250, 0, 120, 30);jframeMain.add(jlblScoreName);//3、得分区(得分名+分数)jlblScore = new JLabel("0", JLabel.CENTER);jlblScore.setFont(scoreFont);jlblScore.setForeground(Color.WHITE);jlblScore.setOpaque(true);jlblScore.setBackground(Color.GRAY);jlblScore.setBounds(250, 30, 120, 30);jframeMain.add(jlblScore);//4、提⽰说明区jlblTip = new JLabel("操作: ↑↓←→, 按esc键重新开始 ",JLabel.CENTER);jlblTip.setFont(explainFont);jlblTip.setForeground(Color.DARK_GRAY);jlblTip.setBounds(0, 60, 400, 40);jframeMain.add(jlblTip);//5、主游戏⾯板区gameBoard = new GameBoard();gameBoard.setBounds(0, 100, 400, 400);gameBoard.setBackground(Color.GRAY);gameBoard.setFocusable(true);//焦点即当前正在操作的组件,也就是移动的数字 gameBoard.setLayout(new FlowLayout());jframeMain.add(gameBoard);}// 游戏⾯板class GameBoard extends JPanel implements KeyListener {private static final int CHECK_GAP = 10;//⽅格之间的间隙private static final int CHECK_SIZE = 85;//⽅格⼤⼩private static final int CHECK_ARC = 20;//⽅格弧度private Check[][] checks = new Check[4][4];private boolean isadd = true;public GameBoard() {initGame();addKeyListener(this);}private void initGame() {score = 0;for (int indexRow = 0; indexRow < 4; indexRow++) {for (int indexCol = 0; indexCol < 4; indexCol++) {checks[indexRow][indexCol] = new Check();}}// 最开始时⽣成两个数isadd = true;createCheck();isadd = true;createCheck();}@Overridepublic void keyPressed(KeyEvent e) {switch (e.getKeyCode()) {case KeyEvent.VK_ESCAPE:initGame();//重新开始游戏(初始化游戏)break;case KeyEvent.VK_LEFT:moveLeft();createCheck();//调⽤⼀次⽅法创建⼀个⽅格数字judgeGameOver();//创建后判断是否GameOver,若所有格⼦均满即跳出GameOverbreak;case KeyEvent.VK_RIGHT:moveRight();createCheck();judgeGameOver();break;case KeyEvent.VK_UP:moveUp();createCheck();judgeGameOver();break;case KeyEvent.VK_DOWN:moveDown();createCheck();judgeGameOver();break;default:break;//按其他键没有反应}repaint();//刷新,会⾃动调⽤paint()⽅法,重新绘制移动后的图}private void createCheck() {List<Check> list = getEmptyChecks();if (!list.isEmpty() && isadd) {Random random = new Random();int index = random.nextInt(list.size());Check check = list.get(index);// 2, 4出现概率3:1int randomValue = random.nextInt(4);check.value = ( randomValue % 3 == 0 || randomValue % 3 == 1) ? 2 : 4;//只有[0,4)中的2才能⽣成4 isadd = false;}}// 获取空⽩⽅格private List<Check> getEmptyChecks() {List<Check> checkList = new ArrayList<>();for (int i = 0; i < 4; i++) {for (int j = 0; j < 4; j++) {if (checks[i][j].value == 0) {checkList.add(checks[i][j]);}}}return checkList;}//是否全部格⼦占满,全部占满则GameOverprivate boolean judgeGameOver() {jlblScore.setText(score + "");if (!getEmptyChecks().isEmpty()) {return false;}for (int i = 0; i < 3; i++) {for (int j = 0; j < 3; j++) {//判断是否存在可合并的⽅格if (checks[i][j].value == checks[i][j + 1].value|| checks[i][j].value == checks[i + 1][j].value) {return false;}}}return true;}private void moveLeft() {//找到⼀个⾮空格⼦后checks[i][j].value > 0,可分为三种情况处理for (int i = 0; i < 4; i++) {for (int j = 1, index = 0; j < 4; j++) {if (checks[i][j].value > 0) {//第⼀种情况:checks[i][j](⾮第1列)与checks[i][index]的数相等,则合并乘以2,且得分增加 if (checks[i][j].value == checks[i][index].value) {score += checks[i][index].value *= 2;checks[i][j].value = 0;isadd = true;} else if (checks[i][index].value == 0) {//第⼆种:若checks[i][index]为空格⼦,checks[i][j]就直接移到最左边checks[i][index]checks[i][index].value = checks[i][j].value;checks[i][j].value = 0;isadd = true;} else if (checks[i][++index].value == 0) {//第三种:若checks[i][index]不为空格⼦,并且数字也不相等,若其旁边为空格⼦,则移到其旁边 checks[i][index].value = checks[i][j].value;checks[i][j].value = 0;isadd = true;}}}}}private void moveRight() {for (int i = 0; i < 4; i++) {for (int j = 2, index = 3; j >= 0; j--) {if (checks[i][j].value > 0) {if (checks[i][j].value == checks[i][index].value) {score += checks[i][index].value *= 2;checks[i][j].value = 0;isadd = true;} else if (checks[i][index].value == 0) {checks[i][index].value = checks[i][j].value;checks[i][j].value = 0;isadd = true;} else if (checks[i][--index].value == 0) {checks[i][index].value = checks[i][j].value;checks[i][j].value = 0;isadd = true;}}}}}private void moveUp() {for (int i = 0; i < 4; i++) {for (int j = 1, index = 0; j < 4; j++) {if (checks[j][i].value > 0) {if (checks[j][i].value == checks[index][i].value) {score += checks[index][i].value *= 2;checks[j][i].value = 0;isadd = true;} else if (checks[index][i].value == 0) {checks[index][i].value = checks[j][i].value;checks[j][i].value = 0;isadd = true;} else if (checks[++index][i].value == 0){checks[index][i].value = checks[j][i].value;checks[j][i].value = 0;isadd = true;}}}}}private void moveDown() {for (int i = 0; i < 4; i++) {for (int j = 2, index = 3; j >= 0; j--) {if (checks[j][i].value > 0) {if (checks[j][i].value == checks[index][i].value) {score += checks[index][i].value *= 2;checks[j][i].value = 0;isadd = true;} else if (checks[index][i].value == 0) {checks[index][i].value = checks[j][i].value;checks[j][i].value = 0;isadd = true;} else if (checks[--index][i].value == 0) {checks[index][i].value = checks[j][i].value;checks[j][i].value = 0;isadd = true;}}}}}@Overridepublic void paint(Graphics g) {super.paint(g);for (int i = 0; i < 4; i++) {for (int j = 0; j < 4; j++) {drawCheck(g, i, j);}}// GameOverif (judgeGameOver()) {g.setColor(new Color(64, 64, 64, 100));//RGBA最后⼀个A可以视为透明度g.fillRect(0, 0, getWidth(), getHeight());//填充矩形(游戏⾯板),将暗⿊⾊填充上去g.setColor(Color.WHITE);g.setFont(topicFont);FontMetrics fms = getFontMetrics(topicFont);//FontMetrics字体测量,该类是Paint的内部类,通过getFontMetrics()⽅法可获取字体相关属性 String value = "Game Over!";g.drawString(value, (getWidth()-fms.stringWidth(value)) / 2, getHeight() / 2);//字体居中显⽰}}// 绘制⽅格// Graphics2D 类是Graphics ⼦类,拥有强⼤的⼆维图形处理能⼒private void drawCheck(Graphics g, int i, int j) {Graphics2D gg = (Graphics2D) g;//下⾯两句是抗锯齿模式,计算和优化消除⽂字锯齿,字体更清晰顺滑gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);gg.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);//获取⽅格Check check = checks[i][j];//不同数字设置背景⾊gg.setColor(check.getBackground());// 绘制圆⾓gg.fillRoundRect(CHECK_GAP + (CHECK_GAP + CHECK_SIZE) * j, CHECK_GAP + (CHECK_GAP + CHECK_SIZE) * i,CHECK_SIZE, CHECK_SIZE, CHECK_ARC, CHECK_ARC);//绘制字体及其颜⾊gg.setColor(check.getForeground());gg.setFont(check.getCheckFont());// ⽂字测量,并对⽂字进⾏绘制FontMetrics fms = getFontMetrics(check.getCheckFont());String value = String.valueOf(check.value);//使⽤此图形上下⽂的当前颜⾊绘制由指定迭代器给定的⽂本。

javascript制作2048游戏

javascript制作2048游戏

javascript制作2048游戏这几天玩儿着2048这个游戏,突然心血来潮想练习下写程序的思路,于是乎就模仿做了一个,到目前位置还没有实现动态移动,不是很好看,不过玩儿着自己模仿的小游戏还是蛮爽的,哈哈2048.html&lt;!DOCTYPE&lt;html xmlns=““&lt;head&lt;meta http-equiv=“Content-Type”content=“text/html; charset=utf-8” /&lt;title2048&lt;/title&lt;link rel=“stylesheet” type=“text/css”href=“css/2048.css” /&lt;!-- &lt;script type=“text/javascript”src=“ --&lt;script type=“text/javascript”src=“js/2048.js”&lt;/script&lt;/head&lt;body&lt;div id=“div2048”&lt;a id=“start”tap to start :-)&lt;/a&lt;/div&lt;/body&lt;/html2048.css@charset “utf-8”;#div2048{width: 500px;height: 500px;background-color: #b8af9e; margin: 0 auto;position: relative;}#start{width: 500px;height: 500px;line-height: 500px; display: block;text-align: center;font-size: 30px; background: #f2b179;color: #FFFFFF;}#div2048 div.tile{margin: 20px 0px 0px 20px; width: 100px;height: 40px;padding: 30px 0;font-size: 40px;line-height: 40px;text-align: center;float: left;}#div2048 div.tile0{ background: #ccc0b2;}#div2048 div.tile2{color: #7c736a; background: #eee4da;}#div2048 div.tile4{color: #7c736a; background: #ece0c8; }#div2048 div.tile8 {color: #fff7eb; background: #f2b179; }#div2048 div.tile16 {color:#fff7eb; background:#f59563; }#div2048 div.tile32 {color:#fff7eb; background:#f57c5f; }#div2048 div.tile64 {color:#fff7eb;background:#f65d3b; }#div2048 div.tile128 {color:#fff7eb; background:#edce71; }#div2048 div.tile256 {color:#fff7eb; background:#edcc61; }#div2048 div.tile512 {color:#fff7eb; background:#ecc850; }#div2048 div.tile1024 {color:#fff7eb; background:#edc53f; }#div2048 div.tile2048{color:#fff7eb;background:#eec22e;}2048.jsfunction game2048(container){this.container = container;this.tiles = new Array(16);}game2048.prototype = {init: function(){for(var i = 0, len = this.tiles.length; i &lt; len; i++){var tile = this.newTile(0);tile.setAttribute(‘index’, i);this.container.appendChild(tile);this.tiles[i] = tile;}this.randomTile();this.randomTile();},newTile: function(val){var tile = document.createElement(‘div’);this.setTileVal(tile, val)return tile;},setTileVal: function(tile, val){tile.className = ‘tile tile’ + val;tile.setAttribute(‘val’, val);tile.innerHTML = val 0 ? val : ‘‘;},randomTile: function(){var zeroTiles = [];for(var i = 0, len = this.tiles.length; i &lt; len; i++){if(this.tiles[i].getAttribute(‘val’) == 0){zeroTiles.push(this.tiles[i]);}}var rTile = zeroTiles[Math.floor(Math.random() * zeroTiles.length)];this.setTileVal(rTile, Math.random() &lt; 0.8 ?2 : 4);},move:function(direction){var j;switch(direction){case ‘W’:for(var i = 4, len = this.tiles.length; i &lt; len; i++){j = i;while(j = 4){this.merge(this.tiles[j - 4], this.tiles[j]);j -= 4;}}break;case ‘S’:for(var i = 11; i = 0; i--){j = i;while(j &lt;= 11){this.merge(this.tiles[j + 4], this.tiles[j]);j += 4;}}break;case ‘A’:for(var i = 1, len = this.tiles.length; i &lt; len; i++){j = i;while(j % 4 != 0){this.merge(this.tiles[j - 1], this.tiles[j]);j -= 1;}}break;case ‘D’:for(var i = 14; i = 0; i--){j = i;while(j % 4 != 3){this.merge(this.tiles[j + 1], this.tiles[j]);j += 1;}}break;}this.randomTile();},merge: function(prevTile, currTile){var prevVal = prevTile.getAttribute(‘val’);var currVal = currTile.getAttribute(‘val’);if(currVal != 0){if(prevVal == 0){this.setTileVal(prevTile, currVal);this.setTileVal(currTile, 0);}else if(prevVal == currVal){this.setTileVal(prevTile, prevVal * 2);this.setTileVal(currTile, 0);}}},equal: function(tile1, tile2){return tile1.getAttribute(‘val’) == tile2.getAttribute(‘val’);},max: function(){for(var i = 0, len = this.tiles.length; i &lt;len; i++){if(this.tiles[i].getAttribute(‘val’) == 2048){return true;}}},over: function(){for(var i = 0, len = this.tiles.length; i &lt; len; i++){if(this.tiles[i].getAttribute(‘val’) == 0){return false;}if(i % 4 != 3){if(this.equal(this.tiles[i], this.tiles[i + 1])){return false;}}if(i &lt; 12){if(this.equal(this.tiles[i], this.tiles[i + 4])){return false;}}}return true;},clean: function(){for(var i = 0, len = this.tiles.length; i &lt; len; i++){this.container.removeChild(this.tiles[i]);}this.tiles = new Array(16);}}var game, startBtn;window.onload = function(){var container = document.getElementById(‘div2048’);startBtn = document.getElementById(‘start’);startBtn.onclick = function(){this.style.display = ‘none’;game = game || new game2048(container);game.init();}}window.onkeydown = function(e){var keynum, keychar;if(window.event){ // IEkeynum = e.keyCode;}else if(e.which){ // Netscape/Firefox/Operakeynum = e.which;}keychar = String.fromCharCode(keynum);if([‘W’, ‘S’, ‘A’, ‘D’].indexOf(keychar) -1){if(game.over()){game.clean();startBtn.style.display = ‘block’;startBtn.innerHTML = ‘game over, replay?’;return;}game.move(keychar);}}以上所诉就是本文的全部内容了,希望大家能够喜欢。

java实现2048小游戏(含注释)

java实现2048小游戏(含注释)

java实现2048⼩游戏(含注释)本⽂实例为⼤家分享了java实现2048⼩游戏的具体代码,供⼤家参考,具体内容如下实现⽂件APP.javaimport javax.swing.*;public class APP {public static void main(String[] args) {new MyFrame();}}类⽂件import javax.swing.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.util.Random;//定义⾃⼰的类(主类)去继承JFrame类并实现KeyListener接⼝和ActionListener接⼝public class MyFrame extends JFrame implements KeyListener, ActionListener {//⽤于存放游戏各位置上的数据int[][] data = new int[4][4];//⽤于判断是否失败int loseFlag = 1;//⽤于累计分数int score = 0;//⽤于切换主题String theme = "A";//设置三个菜单项⽬JMenuItem item1 = new JMenuItem("经典");JMenuItem item2 = new JMenuItem("霓虹");JMenuItem item3 = new JMenuItem("糖果");//核⼼⽅法public MyFrame(){//初始化窗⼝initFrame();//初始化菜单initMenu();//初始化数据initData();//绘制界⾯paintView();//为窗体提供键盘监听,该类本⾝就是实现对象this.addKeyListener(this);//设置窗体可见setVisible(true);}//窗体初始化public void initFrame(){//设置尺⼨setSize(514,538);//设置居中setLocationRelativeTo(null);//设置总在最上⾯setAlwaysOnTop(true);setLayout(null);}//初始化菜单public void initMenu() {//菜单栏⽬JMenuBar menuBar = new JMenuBar();JMenu menu1 = new JMenu("换肤");JMenu menu2 = new JMenu("关于我们");//添加上menuBarmenuBar.add(menu1);menuBar.add(menu2);//添加上menumenu1.add(item1);menu1.add(item2);menu1.add(item3);//注册监听item1.addActionListener(this);item2.addActionListener(this);item3.addActionListener(this);//添加进窗体super.setJMenuBar(menuBar);}//初始化数据,在随机位置⽣成两个2public void initData(){generatorNum();generatorNum();}//重新绘制界⾯的⽅法public void paintView(){//调⽤⽗类中的⽅法清空界⾯getContentPane().removeAll();//判断是否失败if(loseFlag==2){//绘制失败界⾯JLabel loseLable = new JLabel(new ImageIcon("D:\\Download\\BaiDu\\image\\"+theme+"-lose.png"));//设置位置和⾼宽loseLable.setBounds(90,100,334,228);//将该元素添加到窗体中getContentPane().add(loseLable);}//根据现有数据绘制界⾯for(int i=0;i<4;i++) {//根据位置循环绘制for (int j = 0; j < 4; j++) {JLabel image = new JLabel(new ImageIcon("D:\\Download\\BaiDu\\image\\"+theme+"-"+data[i][j]+".png"));//提前计算好位置image.setBounds(50 + 100 * j, 50+100*i, 100, 100);//将该元素添加进窗体getContentPane().add(image);}}//绘制背景图⽚JLabel background = new JLabel(new ImageIcon("D:\\Download\\BaiDu\\image\\"+theme+"-Background.jpg")); //设置位置和⾼宽background.setBounds(40,40,420,420);//将该元素添加进窗体getContentPane().add(background);//得分模板设置JLabel scoreLable = new JLabel("得分:"+score);//设置位置和⾼宽scoreLable.setBounds(50,20,100,20);getContentPane().repaint();}//⽤不到的但是必须重写的⽅法,⽆需关注@Overridepublic void keyTyped(KeyEvent e) {}//键盘被按下所触发的⽅法,在此⽅法中加⼊区分上下左右的按键@Overridepublic void keyPressed(KeyEvent e) {//keyCode接收按键信息int keyCode = e.getKeyCode();//左移动if(keyCode == 37){moveToLeft(1);generatorNum();}//上移动else if(keyCode==38){moveToTop(1);generatorNum();}//右移动else if(keyCode==39){moveToRight(1);generatorNum();}//下移动else if(keyCode==40){moveToBottom(1);generatorNum();}//忽视其他按键else {return;}//检查是否能够继续移动check();//重新根据数据绘制界⾯paintView();}//左移动的⽅法,通过flag判断,传⼊1是正常移动,传⼊2是测试移动 public void moveToLeft(int flag) {for(int i=0;i<data.length;i++){//定义⼀维数组接收⼀⾏的数据int[] newArr = new int[4];//定义下标⽅便操作int index=0;for(int x=0;x<data[i].length;x++){//将有数据的位置前移if(data[i][x]!=0){newArr[index]=data[i][x];index++;}}//赋值到原数组data[i]=newArr;//判断相邻数据是否相邻,相同则相加,不相同则略过for(int x=0;x<3;x++){if(data[i][x]==data[i][x+1]){data[i][x]*=2;//如果是正常移动则加分if(flag==1){score+=data[i][x];}//将合并后的数据都前移,实现数据覆盖for(int j=x+1;j<3;j++){data[i][j]=data[i][j+1];}//末尾补0data[i][3]=0;}//右移动的⽅法,通过flag判断,传⼊1是正常移动,传⼊2是测试移动 public void moveToRight(int flag) {//翻转⼆维数组reverse2Array();//对旋转后的数据左移动moveToLeft(flag);//再次翻转reverse2Array();}//上移动的⽅法,通过flag判断,传⼊1是正常移动,传⼊2是测试移动 public void moveToTop(int flag) {//逆时针旋转数据anticlockwise();//对旋转后的数据左移动moveToLeft(flag);//顺时针还原数据clockwise();}//下移动的⽅法,通过flag判断,传⼊1是正常移动,传⼊2是测试移动 public void moveToBottom(int flag) {//顺时针旋转数据clockwise();//对旋转后的数据左移动moveToLeft(flag);//逆时针旋转还原数据anticlockwise();}//检查能否左移动public boolean checkLeft(){//开辟新⼆维数组⽤于暂存数据和⽐较数据int[][] newArr = new int[4][4];//复制数组copyArr(data,newArr);//测试移动moveToLeft(2);boolean flag = false;//设置break跳出的for循环标记lo:for (int i = 0; i < data.length; i++) {for (int j = 0; j < data[i].length; j++) {//如果有数据不相同,则证明能够左移动,则返回trueif(data[i][j]!=newArr[i][j]){flag=true;break lo;}}}//将原本的数据还原copyArr(newArr,data);return flag;}//检查能否右移动,与checkLeft()⽅法原理相似public boolean checkRight(){int[][] newArr = new int[4][4];copyArr(data,newArr);moveToRight(2);boolean flag = false;lo:for (int i = 0; i < data.length; i++) {for (int j = 0; j < data[i].length; j++) {if(data[i][j]!=newArr[i][j]){flag=true;break lo;}}}copyArr(newArr,data);//检查能否上移动,与checkLeft()⽅法原理相似public boolean checkTop(){int[][] newArr = new int[4][4];copyArr(data,newArr);moveToTop(2);boolean flag = false;lo:for (int i = 0; i < data.length; i++) {for (int j = 0; j < data[i].length; j++) {if(data[i][j]!=newArr[i][j]){flag=true;break lo;}}}copyArr(newArr,data);return flag;}//检查能否下移动,与checkLeft()⽅法原理相似public boolean checkBottom(){int[][] newArr = new int[4][4];copyArr(data,newArr);moveToBottom(2);boolean flag = false;lo:for (int i = 0; i < data.length; i++) {for (int j = 0; j < data[i].length; j++) {if(data[i][j]!=newArr[i][j]){flag=true;break lo;}}}copyArr(newArr,data);return flag;}//检查是否失败public void check(){//上下左右均不能移动,则游戏失败if(checkLeft()==false&&checkRight()==false&&checkTop()==false&&checkBottom()==false){ loseFlag = 2;}}//复制⼆维数组的⽅法,传⼊原数组和新数组public void copyArr(int[][] src,int[][] dest){for (int i = 0; i < src.length; i++) {for (int j = 0; j < src[i].length; j++) {//遍历复制dest[i][j]=src[i][j];}}}//键盘被松开@Overridepublic void keyReleased(KeyEvent e) {}//翻转⼀维数组public void reverseArray(int[] arr){for(int start=0,end=arr.length-1;start<end;start++,end--){int temp = arr[start];arr[start] = arr[end];arr[end] = temp;}}//翻转⼆维数组public void reverse2Array(){for (int i = 0; i < data.length; i++) {reverseArray(data[i]);//顺时针旋转public void clockwise(){int[][] newArr = new int[4][4];for(int i=0;i<4;i++){for(int j=0;j<4;j++){//找规律啦~newArr[j][3-i] = data[i][j];}}data = newArr;}//逆时针旋转public void anticlockwise(){int[][] newArr = new int[4][4];for(int i=0;i<4;i++){for(int j=0;j<4;j++){//规律newArr[3-j][i] = data[i][j];}}data = newArr;}//空位置随机⽣成2public void generatorNum(){int[] arrarI = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; int[] arrarJ = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; int w=0;for (int i = 0; i < data.length; i++) {for (int j = 0; j < data[i].length; j++) {if(data[i][j]==0){//找到并存放空位置arrarI[w]=i;arrarJ[w]=j;w++;}}}if(w!=0){//随机数找到随机位置Random r= new Random();int index = r.nextInt(w);int x = arrarI[index];int y = arrarJ[index];//空位置随机⽣成2data[x][y]=2;}}//换肤操作@Overridepublic void actionPerformed(ActionEvent e) {//接收动作监听,if(e.getSource()==item1){theme = "A";}else if(e.getSource()==item2){theme = "B";}else if(e.getSource()==item3){theme = "C";}//换肤后重新绘制paintView();}}//测试失败效果的数据/*int[][] data = {{2,4,8,4},{16,32,64,8},{128,2,256,2},{512,8,1024,2048}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

2048源代码Flash ActionScript2.0版本,附使用方法

2048源代码Flash ActionScript2.0版本,附使用方法
}
var generateNumber=generateNumberArray[Math.floor(generateNumberArray.length*Math.random())];
for(var i=0;i<=matrix.length-1;i++){
if(matrix[i]==0){
for(var Βιβλιοθήκη =0;j<=order-1;j++){
matrix[i*order+j]=heapedRow[j];
}
}
if(!compare(copied)){
generateRandomTile();
}
}
public function moveToRight(){
type为可选参数,取值范围为1-15之间的正整数,决定2048棋子的基数,默认为1。
index++;
}
}
return reheaped;
}
private function copy():Array{
var copyArr=[];
for(var i=0;i<=matrix.length-1;i++){
copyArr[i]=matrix[i];
score=0;
generateRandomTile();
generateRandomTile();
}
public function generateRandomTile(){
var countZero=0;
for(var i=0;i<=matrix.length-1;i++){

2048小游戏源码及详细解说

2048小游戏源码及详细解说

《2048》是一款比较流行的数字游戏,最早于2014年3月20日发行。

原版2048首先在GitHub上发布,原作者是Gabriele Cirulli,后被移植到各个平台。

这款游戏是基于《1024》和《小3传奇》的玩法开发而成的新型数字游戏。

游戏源地址:gabrielecirulli.github.io/2048/1修改activity_main.xml文件<LinearLayout xmlns:android="schemas.android./apk/res/android"xmlns:tools="schemas.android./tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="string/hello_world"/></LinearLayout>22048继续修改activity_main.xml文件<LinearLayout xmlns:android="schemas.android./apk/res/android"xmlns:tools="schemas.android./tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity"><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="string/score"/><TextViewandroid:id="+id/tvScore"android:layout_width="wrap_content"android:layout_height="wrap_content"/> </LinearLayout><GridLayoutandroid:id="+id/gameView"android:layout_width="fill_parent"android:layout_height="0dp"android:layout_weight="1"></GridLayout></LinearLayout>32048新建类GameView,继承自GridLayoutpackage .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="schemas.android./apk/res/android"xmlns:tools="schemas.android./tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity"><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="string/score"/><TextViewandroid:id="+id/tvScore"android:layout_width="wrap_content"android:layout_height="wrap_content"/></LinearLayout><!-- 把类GameView绑定到一起 --><.wuyudong.game2048.GameViewandroid:id="+id/gameView"android:layout_width="fill_parent"android:layout_height="0dp"android:layout_weight="1"></.wuyudong.game2048.GameView></LinearLayout>42048添加触控交互相关代码private void initGameView() {setOnTouchListener(new OnTouchListener() {//记录起始位置和偏移坐标private float startX, startY, offsetX, offsetY;Overridepublic 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;}});}52048编写卡片类Card.javapackage .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;}62048先添加相关代码看看效果Overrideprotected 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); }82048private 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;} elseif(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;} elseif(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;} elseif(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;} elseif(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>(); 92048MainActivity.java 中添加相关代码:package .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;}Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);tvScore = (TextView) findViewById(Score);}Overridepublic 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;}}102048private 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() {Overridepublic void onClick(DialogInterface dialog,int which) {startGame();}}).show();}}。

2048源代码

2048源代码

2048源代码Block.java 文件package pkg2048;import javax.swing.*;import java.awt.*;@SuppressWarnings("serial")public class Block extends JLabel { private int value;public Block() {value = 0;setFont(new Font("font", Font.PLAIN, 40)); setBackground(Color.gray);}public int getValue() {return value;}public void setValue(int value) {this.value = value;String text = String.valueOf(value);if (value != 0)setText(text);elsesetText("");setColor();}public void setColor() {if (this.value == 0)setBackground(Color.gray);else if (this.value == 2)setBackground(new Color(238, 228, 218)); else if (this.value == 4) setBackground(new Color(238, 224, 198)); else if (this.value == 8) setBackground(new Color(243, 177, 116)); else if (this.value == 16) setBackground(new Color(243, 177, 116)); else if (this.value == 32) setBackground(new Color(248, 149, 90)); else if (this.value == 64) setBackground(new Color(249, 94, 50)); else if (this.value == 128) setBackground(new Color(239, 207, 108)); else if (this.value == 256) setBackground(new Color(239, 207, 99)); else if (this.value == 512) setBackground(new Color(239, 203, 82)); else if (this.value == 1024) setBackground(new Color(239, 199, 57)); else if (this.value == 2048) setBackground(new Color(239, 195, 41)); else if (this.value == 4096) setBackground(new Color(255, 60, 57)); }}My2048 文件package pkg2048;import java.awt.*;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.*;@SuppressWarnings("serial")public class My2048 extends JFrame implements KeyListener {Block[] block = new Block[25];JPanel panel;boolean numFlag;int moveFlag;public My2048() {numFlag = true;moveFlag = 0;setTitle("2048");setSize(600, 600);//设置界面大小setLocation(300, 100);//设置界面在屏幕中的位置setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置一个默认的关闭操作panel = (JPanel) getContentPane();panel.setLayout(new GridLayout(5, 5, 5, 5));// 创建具有指定行数和列数的网格布局addBlock();for (int i = 0; i < 2; i++) {appearBlock();}this.addKeyListener(this);//键盘监听this.setVisible(true);}public void addBlock() {for (int i = 0; i < 25; i++) {block[i] = new Block();block[i].setHorizontalAlignment(JLabel.CENTER);//设置文本的水平对齐方式block[i].setOpaque(true);//设置控件不透明panel.add(block[i]);}}public void appearBlock() {//随机出现块while (numFlag) {int index = (int) (Math.random() * 25);if (block[index].getValue() == 0) {block[index].setValue(2);break;}}}public void judgeAppear() {int sum = 0;for (int i = 0; i < 25; i++) {if (block[i].getValue() != 0) {sum++;}}if (sum == 25) {numFlag = false;}}public void upBlock() {//点击键盘up键调用的方法for (int j = 0; j < 5; j++) {int temp[] = new int[5];int number = 0;for (int i = j; i <=j + 20; i = i + 5) { if (block[i].getValue() != 0) {temp[number] = block[i].getValue(); number = number + 1;}}/* if(number!=0){for (int i = 0; i < number; i++) { System.out.print(temp[i]);}}else{System.out.print("kong");}System.out.print("\n");*/for (int i = 0; i < number-1;) {if (temp[i] == temp[i + 1]) {temp[i] = temp[i] + temp[i + 1]; temp[i + 1] = 0;i = i + 2;} else {i = i + 1;}}int k = 0;for (int h = 0; h < 4; h++) {if (temp[h] != 0) {temp[k] = temp[h];if (h != k) {temp[h] = 0;}k = k + 1;}}for (int i = j,h=0; i <=j + 20; i = i + 5,h=h+1) { block[i].setValue(temp[h]);}}}public void downBlock() {//点击键盘down键调用的方法for (int j = 20; j <25; j++) {int temp[] = new int[5];int number = 0;for (int i = j; i >=j - 20; i = i - 5) {if (block[i].getValue() != 0) {temp[number] = block[i].getV alue();number = number + 1;}}/* if(number!=0){for (int i = 0; i < number; i++) {System.out.print(temp[i]);}}else{System.out.print("kong");}System.out.print("\n");*/for (int i = 0; i < number-1;) {if (temp[i] == temp[i + 1]) {temp[i] = temp[i] + temp[i + 1];temp[i + 1] = 0;i = i + 2;} else {i = i + 1;}}int k = 0;for (int h = 0; h < 4; h++) {if (temp[h] != 0) {temp[k] = temp[h];if (h != k) {temp[h] = 0;}}}for (int i = j,h=0; i >=j - 20; i = i - 5,h=h+1) {block[i].setValue(temp[h]);}}}public void rightBlock() {//点击键盘right键调用的方法for (int j = 4; j <25; j=j+5) {int temp[] = new int[5];int number = 0;for (int i = j; i >=j - 4; i--) {if (block[i].getValue() != 0) {temp[number] = block[i].getV alue(); number = number + 1;}}/* if(number!=0){for (int i = 0; i < number; i++) { System.out.print(temp[i]);}}else{System.out.print("kong");}System.out.print("\n");*/for (int i = 0; i < number-1;) {if (temp[i] == temp[i + 1]) {temp[i] = temp[i] + temp[i + 1]; temp[i + 1] = 0;i = i + 2;} else {i = i + 1;}}int k = 0;for (int h = 0; h < 4; h++) {if (temp[h] != 0) {temp[k] = temp[h];temp[h] = 0;}k = k + 1;}}for (int i = j,h=0; i >=j-4; i--,h=h+1) {block[i].setValue(temp[h]);}}}public void leftBlock() {//点击键盘left键调用的方法for (int j = 0; j <=20; j=j+5) {int temp[] = new int[5];int number = 0;for (int i = j; i <=j + 4; i++) {if (block[i].getValue() != 0) {temp[number] = block[i].getV alue();number = number + 1;}}/*if(number!=0){for (int i = 0; i < number; i++) {System.out.print(temp[i]);}}else{System.out.print("kong");}System.out.print("\n");System.out.println(number);*/for (int i = 0; i < number-1;) {if (temp[i] == temp[i + 1]) {temp[i] = temp[i] + temp[i + 1];temp[i + 1] = 0;i = i + 2;} else {i = i + 1;}}int k = 0;for (int h = 0; h < 4; h++) {if (temp[h] != 0) {temp[k] = temp[h];if (h != k) {temp[h] = 0;}k = k + 1;}}for (int i = j,h=0; i <=j+4; i++,h=h+1) { block[i].setValue(temp[h]);}}}@Overridepublic void keyPressed(KeyEvent e) { switch (e.getKeyCode()) {case KeyEvent.VK_UP://判断按下的点击否是UP键upBlock();judgeAppear();appearBlock();over();break;case KeyEvent.VK_DOWN://判断按下的点击否是down键downBlock();judgeAppear();appearBlock();over();break;case KeyEvent.VK_LEFT://判断按下的点击否是left键leftBlock();judgeAppear();appearBlock();over();break;case KeyEvent.VK_RIGHT://判断按下的点击否是right键rightBlock();judgeAppear();appearBlock();over();break;}}public void over() {//判断游戏结束if (!numFlag ) {block[5].setText("G");block[6].setText("A");block[7].setText("M");block[8].setText("E");block[11].setText("O");block[12].setText("V");block[13].setText("E");block[14].setText("R");block[11].addMouseListener(new MouseAdapter() { @Overridepublic void mousePressed(MouseEvent e) {reStart();}});}}public void win() {//判断游戏胜利block[0].setText("Y");block[1].setText("O");block[2].setText("U");block[13].setText("W");block[14].setText("I");block[15].setText("N");block[15].addMouseListener(new MouseAdapter() { @Overridepublic void mousePressed(MouseEvent e) {reStart();}});}public void reStart() {numFlag = true;moveFlag = 0;for (int i = 0; i < 16; i++) {block[i].setValue(0);}for (int i = 0; i < 2; i++) {appearBlock();}}@Overridepublic void keyTyped(KeyEvent e) {//发生击键时被触发}@Overridepublic void keyReleased(KeyEvent e) {//按键释放时被触发} public static void main(String args[]) {JFrame.setDefaultLookAndFeelDecorated(true);new My2048();}}。

2048游戏开发源代码

2048游戏开发源代码

可行性分析报告1 引言1.1编写目的:在编写本软件之前,我们查阅了很多资料,并经过细致的讨论和分析,之后由软件项目小组提出了这份可行性分析报告。

这份报告对基于飞凌6410开发板的2048游戏开发进行了全面细致的分析,并且为下一步的需求分析提供了一个可行性前提,是整个项目可以顺利有序的进行,还可以为后期的验收工作提供一个参考的标准。

以及避免在以后的开发中出现巨大的损失。

1.2 项目背景:开发软件名称:基于飞凌6410开发板的2048游戏开发。

项目任务提出者:嵌入式课程第25小组项目开发者:嵌入式课程第25小组用户:适用于所有人员本项目采用客户机/服务器原理,客户端的程序是建立在Windows NT 系统上以Eclipse为开发软件的应用程序,服务器端自行编写操作系统的工作站,是采用SQL为开发软件的数据库服务程序。

具有很好的可移植性,可在应用范围较广的WINDOWS系列操作系统上使用。

1.3 参考资料:《Qt Creator快速入门》,霍亚飞等,北京航天航空大学出版社。

《鸟哥的linux私房菜》,鸟哥著,人民邮电出版社。

2.可行性研究的前提2.1要求主要功能:界面展示、键盘控制、游戏实现、得分积累;性能要求:用户游戏时的信息必须及时的反映在arm的显示平台上。

用户的数据必须无差错的存储在系统内。

对服务器上的数据必须进行及时正确的刷新。

输入要求:用键盘的A S D W 来控制游戏时的左下右上键输出要求:简捷,快速,实时,美观,大方。

安全与保密要求:服务器的管理员享有对该系统用户信息数据库的管理与修改。

用户只享有对自己对应的部分修改。

完成期限:预计半个月2.2目标:基本实现在开发板上的2048游戏,主要是要攻克界面显示这个难题。

后期可以在此基础上自行进行改动。

2.3条件,假定和限制经费来源:自费。

硬件条件:自己用Qt Creator编写的显示界面,开发板上安装了linux 系统,PC 机上用装了linux的虚拟机进行开发。

基于java的2048小游戏的设计文档

基于java的2048小游戏的设计文档

目录一、实现方案 (2)二、具体代码及程序框图分析 (3)三、参考资料 (13)一、实现方案本游戏采用Java语言编写,使用Eclipse编译器,jdk1.7.0_51编译环境。

游戏的UI主要运用Java图形界面编程(AWT),实现窗口化可视化的界面。

游戏的后台通过监听键盘方向键来移动数字方块,运用随机数的思想随机产生一个2或4的随机数,显示在随机方块中,运用二维数组存储、遍历查找等思想,在每次移动前循环查找二维数组相邻的移动方向的行或列可以合并与否,如果没有可以合并的数字方块同时又没有空余的空间产生新的数字则游戏宣告结束,同时,当检测到合并的结果中出现2048,也宣告游戏结束。

游戏设计了非常简单的交互逻辑,流程如下:为了增加游戏的用户体验,后期加入了操作音效(音效文件提取自百度移动应用商店——2048),在移动和合并方块时播放不同声音。

二、具体代码及程序框图分析整个游戏有三个类,分别为游戏的主类Game.class、事件处理类MyListener.class、声音处理类PlaySound.class,下面对Game.class和MyListener.class进行说明。

Game.class的简单程序框图如下:游戏的主类Game.class是窗体程序JFrame的扩展类,主要负责界面的搭建,完成界面绘图的工作。

该类作为主类,主方法public static void main(String[] args)中先新建一个该类的对象,接着调用用与创建界面控件的方法IntUI(),代码如下:public static void main(String[] args) {Game UI = new Game();UI.IntUI();}IntUI()方法用于JFrame控件及界面框架的搭建,代码解析如下:首先创建一个窗体,标题为“2048小游戏”,把坐标固定在屏幕的x=450,y=100的位置,把窗体大小设置为宽400像素高500像素,然后把JPlane的布局管理器设置为空,具体代码如下:this.setTitle("2048小游戏");this.setLocation(450,100);this.setSize(400, 500);this.setLayout(null);接下来分别是【新游戏】、【帮助】、和【退一步】的按钮,以【新游戏】按钮为例,创建一个新游戏的图片按钮,图片相对路径为res/start.png,为了达到更美观的显示效果,把聚焦,边线等特征设置为false,把相对窗体的坐标设置为(5, 10),大小设置为宽120像素高30像素,具体代码如下:ImageIcon imgicon = new ImageIcon("res/start.png");JButton bt = new JButton(imgicon);bt.setFocusable(false);bt.setBorderPainted(false);bt.setFocusPainted(false);bt.setContentAreaFilled(false);bt.setBounds(-15, 10, 120, 30);this.add(bt);而分数显示控件与按钮控件类似,不再赘述。

Java 2048小游戏

Java 2048小游戏

import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel;//导包过程,没啥说的public class UI extends JFrame { public static void main(String[] args) { UI ui=new UI(); ui.InUI();}// 创建数组,存储数据private int[][] numbers=new int[4][4]; // 创建界面public void InUI() { this.setTitle("2048");this.setLocation(200, 200); this.setSize(270, 340); this.setLayout(null);// 添加按钮JButton jb=new JButton(); jb.setText("开始游戏"); jb.setFocusable(false);jb.setBounds(10, 10, 100, 30); jb.setForeground(new Color(3, 82, 212)); jb.setFont(new Font("宋体", Font.BOLD, 15)); this.add(jb);JLabel jl=new JLabel("score:"); jl.setBounds(160, 10, 100, 30);//空布局的大小位置设置要用setB ounds………………………………jl.setForeground(new Color(3, 82, 212)); this.add(jl);this.setDefaultCloseOperation(3);this.setResizable(false);//界面大小动一个试试this.setVisible(true);// 创建事件处理类NewListener nl=new NewListener(this, numbers, jl);jb.addActionListener(nl);// 动作监听器this.addKeyListener(nl);// 键盘监听器}/** 重写窗体的方法*/public void paint(Graphics g) { super.paint(g);g.setColor(new Color(255, 170, 37));g.fillRoundRect(10, 80, 250, 250, 15, 15);// 绘制大矩形框g.setColor(new Color(234, 223, 223)); for (int i=0;i <4;i++) { for (int j=0;j <4;j++) { g.fillRoundRect(20 + i * 60, 90 + j * 60, 50, 50, 15, 15);}}// 绘制小矩形框// 调整数字的位置,注意横纵坐标~~~~~~是反的哦!!!bug之一!!!for (int i=0;i <4;i++) { for (int j=0;j <4;j++) { if (numbers[i][j] != 0) {if (numbers[i][j] == 2 || numbers[i][j] == 4|| numbers[i][j] == { g.setColor(Color.red);g.fillRoundRect(20 + j * 60, 90 + i * 60, 50, 50, 15,15);g.setColor(Color.black);g.setFont(new Font("宋体", Font.BOLD, 30));g.drawString(numbers[i][j] + "", 20 + j * 60 + 17,90 + i * 60 + 33); }else if (numbers[i][j] == 16 || numbers[i][j] == 32|| numbers[i][j] == 64) { g.setColor(Color.CYAN);g.fillRoundRect(20 + j * 60, 90 + i * 60, 50, 50, 15,15);g.setColor(Color.BLUE);g.setFont(new Font("宋体", Font.BOLD, 30));g.drawString(numbers[i][j] + "", 20 + j * 60 + 8,90 + i * 60 + 33); }else if (numbers[i][j] == 128 || numbers[i][j] == 256|| numbers[i][j] == 512) {g.setColor(Color.white);g.fillRoundRect(20 + j * 60, 90 + i * 60, 50, 50, 15,15);g.setColor(Color.red);g.setFont(new Font("宋体", Font.BOLD, 20));g.drawString(numbers[i][j] + "", 20 + j * 60 + 10,90 + i * 60 + 33); }else if (numbers[i][j] == 1024 || numbers[i][j] == 2048|| numbers[i][j] == 4096) { g.setColor(Color.blue);g.fillRoundRect(20 + j * 60, 90 + i * 60, 50, 50, 15,15);g.setColor(Color.green);g.setFont(new Font("宋体", Font.BOLD, 20));g.drawString(numbers[i][j] + "", 20 + j * 60 + 5,90 + i * 60 + 33); }}}}}}//实现了数字在矩形框上显示的位置(居中),设置了数字所对应的框的颜色接下来就是各方向算法的分析咯~ import java.applet.Applet; import java.applet.AudioClip; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.Random; import javax.swing.JLabel;import javax.swing.JOptionPane;//又是导包public class NewListener extends KeyAdapter implements ActionListener { private UI ui;// 界面类的对象private int[][] numbers;// 存数数据的数组private Random rand=new Random(); private JLabel jl; private int score=0; AudioClip audio; AudioClip audio1; public NewListener(UI ui, int[][] numbers, JLabel jl) { this.ui=ui;this.numbers=numbers;this.jl=jl;audio=Applet.newAudioClip(getClass().getResource("click_01.wav"));audio1=Applet.newAudioClip(getClass().getResource("T-Ara - Number 9.wav"));//2048也是有声音滴~~~~~~这个地方不用new 而是Applet}@Overridepublic void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub for (int i=0;i <4;i++) { for (int j=0;j <4;j++) { numbers[i][j]=0;}}score=0;// 初始化,保证每次按开始后都能重新计分audio1.loop();//有背景音乐的2048,你玩过么。

2048游戏源代码

2048游戏源代码

#include <iostream>#include <iomanip>#include <cstdlib>#include <ctime>#include <string>#include <memory>// 2的概率大于4#define random_2_4 (rand()%5==4 ? 4:2)#define random_x(x) (rand()%x)using namespace std;// 矩阵大小const int MAX = 4;const int MAXMAX = MAX*MAX;// 初始数据个数const int INIT_SIZE = 2;// 数据矩阵int _matrix[MAX][MAX];// 合并临时数组int current[MAX];// 数据计数int _count;// 按键操作 => 不使用char...防止不必要的失败... => ch[0]即可... string ch;// 得分...int score;// 打印数组void print();// 操作说明void help();// 初始操作void init();// 随机位置 => 随机数据2/4bool random_data_one();// 上左下右bool b_up();bool b_left();bool b_down();bool b_right();void _up();void _left();void _down();void _right();int main(){init();print();while (b_up() || b_left() || b_down() || b_right()){help();switch (ch[0]){case 'w':_up();break;case 'a':_left();break;case 's':_down();break;case 'd':_right();break;default:cout <<"无效输入..."<< endl << endl; break;}print();}cout << " Game Over !! " << endl;cout << "最终得分Socre => " << score << endl;system("pause");system("pause");system("pause");return 0;}void print(){int j;cout << "-------------------------------------" << endl; cout << "得分Socre => " << score << endl;cout << "-------------------------------------" << endl;for (int i = 0; i < MAX; i++){for ( j = 0; j < MAX; j++){if (_matrix[i][j])cout << setw(5) << _matrix[i][j] << " |";elsecout << setw(7) << " |";}cout << endl;}cout << "-------------------------------------" << endl << endl;; }void help(){cout << "wasd => 上左下右" << endl;cout << "请输入: ";cin >> ch;}void init(){_count = 0;score = 0;srand((int)time(0));for (int i = 0; i < INIT_SIZE; i++)random_data_one();}bool random_data_one(){if (_count == MAXMAX)return false;int left = MAXMAX - _count;int tmp = random_x(left);int num = random_2_4;int k = 0;for (int i = 0; i < MAX; i++){for (int j = 0; j < MAX; j++){if (_matrix[i][j] == 0){if (k++ == tmp){_matrix[i][j] = num;break;}}}}++_count;return true;}bool b_up(){int j;for (int k = 0; k < MAX; k++){// 特殊情况...这一列有空元素...bool flag = false;for (int i = 0; i < MAX - 1; i++){if (_matrix[i][k] == 0)flag = true;else{int j = i + 1;while (j < MAX){if (_matrix[j][k]){if (_matrix[i][k] == _matrix[j][k]) return true;elsebreak;}else{++j;}}}}if (flag){// 空元素上方有元素则为True...// 使用左右夹击法...int i = 0, j = MAX - 1;while (i < MAX){if (_matrix[i][k])++i;elsebreak;}while (j >= 0){if (_matrix[j][k] == 0)--j;elsebreak;}if (i < j)return true;}}return false;}bool b_left(){for (int k = 0; k < MAX; k++){// 特殊情况...这一行有空元素...bool flag = false;for (int i = 0; i < MAX - 1; i++){if (_matrix[k][i] == 0)flag = true;else{int j = i + 1;while (j < MAX){if (_matrix[k][j]){if (_matrix[k][i] == _matrix[k][j]) return true;elsebreak;}else{++j;}}}}if (flag){// 空元素右边有元素则为True...// 使用左右夹击法...int i = 0, j = MAX - 1;// i 是空元素位置,j是非空元素位置 while (i < MAX){if (_matrix[k][i])++i;elsebreak;}while (j >= 0){if (_matrix[k][j] == 0)--j;elsebreak;}if (i < j)return true;}}return false;}bool b_down(){for (int k = 0; k < MAX; k++){// 特殊情况...这一列有空元素...bool flag = false;for (int i = MAX - 1; i > 0; i--){if (_matrix[i][k] == 0)flag = true;else{int j = i - 1;while (j >= 0){if (_matrix[j][k]){if (_matrix[i][k] == _matrix[j][k])return true;elsebreak;}else{--j;}}}}if (flag){// 空元素上方有元素则为True... => 下边第一个空元素在上边第一个非空元素下边即可...// 使用左右夹击法...int i = 0, j = MAX - 1;// i 是非空位置,j是空元素位置while (i < MAX){if (_matrix[i][k] == 0)++i;elsebreak;}while (j >= 0){if (_matrix[j][k])--j;elsebreak;}if (i < j)return true;}}return false;}bool b_right(){for (int k = 0; k < MAX; k++){// 特殊情况...这一行这一行有空元素...bool flag = false;for (int i = MAX - 1; i > 0; i--){if (_matrix[k][i] == 0)flag = true;else{int j = i - 1;while (j >= 0){if (_matrix[k][j]){if (_matrix[k][i] == _matrix[k][j])return true;elsebreak;}else{--j;}}}}if (flag){// 空元素左边有元素则为True... => 右边第一个空元素在左边第一个非空元素右边即可...// 使用左右夹击法...int i = 0, j = MAX - 1;// i 是非空位置,j是空元素位置while (i < MAX){if (_matrix[k][i] == 0)++i;elsebreak;}while (j >= 0){if (_matrix[k][j])--j;elsebreak;}if (i < j)return true;}}return false;}void _up(){cout << "按下了上键" << endl << endl;if (b_up()){cout << "可以向上合并" << endl;for (int i = 0; i < MAX; i++){memset(current, 0, sizeof(int)*MAX); int ii = 0;for (int j = 0; j < MAX; j++){if (_matrix[j][i])current[ii++] = _matrix[j][i]; }for (int k = 0; k < ii - 1; k++){if (current[k] == current[k + 1]) {current[k] *= 2;score += current[k];current[k + 1] = 0;++k;--_count;}}ii = 0;for ( j = 0; j < MAX; j++){if (current[j])_matrix[ii++][i] = current[j]; }for (; ii < MAX; ii++)_matrix[ii][i] = 0;}random_data_one();}else{cout << "向上无效" << endl << endl; }}void _left(){cout << "按下了左键" << endl << endl;if (b_left()){cout << "可以向左合并" << endl << endl;for (int i = 0; i < MAX; i++){memset(current, 0, sizeof(int)*MAX);int ii = 0;for (int j = 0; j < MAX; j++){if (_matrix[i][j])current[ii++] = _matrix[i][j];}for (int k = 0; k < ii - 1; k++){if (current[k] == current[k + 1]){current[k] *= 2;score += current[k];current[k + 1] = 0;++k;--_count;}}ii = 0;for ( j = 0; j < MAX; j++){if (current[j])_matrix[i][ii++] = current[j];}for (; ii < MAX; ii++)_matrix[i][ii] = 0;}random_data_one();}else{cout << "向左无效" << endl << endl; }}void _down(){cout << "按下了下键" << endl << endl;if (b_down()){cout << "可以向下合并" << endl;for (int i = 0; i < MAX; i++){memset(current, 0, sizeof(int)*MAX);int ii = 0;for (int j = MAX - 1; j >= 0; j--){if (_matrix[j][i])current[ii++] = _matrix[j][i];}for (int k = 0; k < ii - 1; k++){if (current[k] == current[k + 1]){current[k] *= 2;score += current[k];current[k + 1] = 0;++k;--_count;}}ii = MAX - 1;for ( j = 0; j < MAX; j++){if (current[j])_matrix[ii--][i] = current[j];}for (; ii >= 0; ii--)_matrix[ii][i] = 0;}random_data_one();}else{cout << "向下无效" << endl << endl; }}void _right(){cout << "按下了右键" << endl << endl;if (b_right()){cout << "可以向右合并" << endl;for (int i = 0; i < MAX; i++){memset(current, 0, sizeof(int)*MAX);int ii = 0;for (int j = MAX - 1; j >= 0; j--){if (_matrix[i][j])current[ii++] = _matrix[i][j];}for (int k = 0; k < ii - 1; k++){if (current[k] == current[k + 1]){current[k] *= 2;score += current[k];current[k + 1] = 0;++k;--_count;}}ii = MAX - 1;for ( j = 0; j < MAX; j++){if (current[j])_matrix[i][ii--] = current[j];}for (; ii >= 0; ii--)_matrix[i][ii] = 0;}random_data_one();}else{cout << "向右无效" << endl << endl;}}//</memory></string></ctime></cstdlib></iomanip></iostream>。

桌面版2048游戏的代码,实现了绝大部分功能

桌面版2048游戏的代码,实现了绝大部分功能

//如果所有空格全满,且不能再合并了,则说明这一局游戏结束 public void isGameOver() { if(d_model.isPanelFull() && !(d_model.isCombinable())) { JOptionPane.showMessageDialog(this, "您的最终得分为: "+Model.score+" 分。"); //按回车键清除向量中所有对象 } } public void DrawBlock(int x, int y, int num, Graphics g) { switch (num) { case 2: g.setColor(Color.green); break; case 4: g.setColor(Color.red); break; case 8: g.setColor(Color.gray); break; case 16: g.setColor(Color.blue); break; case 32: g.setColor(Color.yellow); break; case 64: g.setColor(Color.orange); break; case 128: g.setColor(Color.white); break; case 256: g.setColor(Color.cyan); break; case 512: g.setColor(Color.MAGENTA); break; case 1024: g.setColor(Color.PINK); break; case 2048: g.setColor(Color.DARK_GRAY); break; case 4096: g.setColor(Color.black); Page 3

java课程设计2048

java课程设计2048

Java语言程序设计课程设计题目 2048游戏的设计与实现学院数信学院专业计算机科学与技术班级计科121 学号 5131学生姓名郑帅兵指导教师赵利平编写日期 2014-7-8目录1.需求分析错误!未定义书签。

2.系统运行环境错误!未定义书签。

3.功能需求描述错误!未定义书签。

4.总体设计错误!未定义书签。

5.程序模块设计错误!未定义书签。

6.总结错误!未定义书签。

一、需求分析《2048》是比较流行的一款数字游戏。

原版2048首先在github上发布,原作者是Gabriele Cirulli。

它是基于《1024》和《小3传奇》的玩法开发而成的新型数字游戏[1] 。

随后2048便出现各种版本,走各大平台。

由Ketchapp公司移植到IOS的版本最为火热,现在约有1000万下载,其名字跟原版一模一样。

衍生版中最出名的是《2048六边形》版本,先后在全球81个国家中的board game中排进了前200。

安卓版非常火爆的有《挑战2048》,其版以后还加入了双人对战。

其次比较特别的有2048中国朝代版。

更有 2048自定义版,可以自己定义文字和图片。

《2048》是IOS中流行的一款。

本课程设计通过设计与开发JVM平台上的2048游戏,进一步掌握所学Java课程的知识,体验Java的跨平台性,同时将Java设计方面的知识拓展应用二、系统运行环境1、硬件环境:2、软件环境:操作系统:WindowsXP/Windows7软件:集成开发环境Eclipse三、功能需求描述1、图形用户界面:2048的最大特点就是玩家对图形界面里的数字进行操作,也就是是玩家与游戏的互动2、当前分数SCORE与最高分数的显示:在我们设计的2048游戏中当前分数取了页面内所有数字相加的值为分数,对玩家玩游戏的进展有直接性、客观性的展现;同时,最高分数取了以往玩家退出游戏时所保存分数的最高分3、数字颜色:游戏中数字的颜色以2为首项的等比数列变化,即2、4、8、16、32、64、128、256、512、1024、2048.......对应的数字卡片变色4、游戏的退出:游戏退出时,我们采用弹出对话框的确认玩家是否真的要退出游戏,当然这样做更符合游戏人性化设计的观念。

2048游戏源码

2048游戏源码
2048游戏源码分享修改
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="apple-mobile-web-app-capable" content="yes">
_gaq.push(['_trackEvent', 'durex2048', '攻略', '游戏开始']);
//});
</script>
</head>
<body>
<div class="container">
<div class="heading">
<h1 class="title">I love you!</h1>
</div>
<script>
var my_list = {2:'2',4:'4',8:'8',16:'16',32:'32',64:'64',128:'128',256:'256',512:'512',1024:'1024',2048:'2048',4096:'4096',8192:'8192',16384:murl+'16384.jpg',32768:'32768',65536:'65536',131072:'131072',262144:'262144',524288:'524288',1048576:'1048576',2097152:'2097152',4194304:'4194304',8388608:'8388608',16777216:'16777216',33554432:'33554432',67108864:'67108864',134217728:'134217728',268435456:'268435456',536870912:'536870912',1073741824:'1073741824',2147483648:'2147483648'}

游戏2048的JAVA源代码

游戏2048的JAVA源代码
private Random rand = new Random();
private Tile[][] tiles;
private int side = 4;
private State gamestate = State.start;
private boolean checkingAvailableMoves;
moveLeft();
break;
case KeyEvent.VK_RIGHT:
moveRight();
break;
}
repaint();
}
});
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
gamestate = State.over;
}
} else if (highest == target)
gamestate = State.won;
}
return moved;
}
boolean moveUp() {
return move(0, -1, 0);
}
boolean moveDown() {
String s = String.valueOf(value);
g.setColor(value < 128 ? colorTable[0] : colorTable[1]);
FontMetrics fm = g.getFontMetrics();
int asc = fm.getAscent();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

Java课程设计——2048小游戏(红红火火恍恍惚惚还很困)

Java课程设计——2048小游戏(红红火火恍恍惚惚还很困)

Java课程设计——2048⼩游戏(红红⽕⽕恍恍惚惚还很困)1.团队成员介绍及任务分配何汐(组长)深受NetBeans折磨发誓再也不⽤了背景⾳乐线程开局模式界⾯美化设计GUI(主菜单及游戏页⾯)李永会(组员)在⽂件流⾥⾯险些淹死登录&&注册排⾏榜GUI(登录及排⾏榜)汪⾬(组员)哪⾥需要哪⾥搬读取进度后退⼀步排⾏榜数据处理2.项⽬git地址3.git提交记录3.项⽬功能架构图与主要功能流程图项⽬功能架构主要功能流程图4.项⽬UML图5.项⽬运⾏截图注册⽤户登录失败继续游戏新游戏返回主菜单关闭游戏帮助&&排⾏榜6.项⽬关键代码1.登录界⾯设计建⽴⼀个板块jp插⼊背景图JPanel构建背景图需要重构new JPanel分别将⽤户名和输⼊框、密码和输⼊框、按钮存为⼀个⾯板利⽤GridLayout对于上述三个⾯板进⾏布局其他窗⼝的界⾯设计均采⽤NetBeans⾃动⽣成public void window() {JLabel label1 = new JLabel("L O G I N");label1.setFont(new Font("Snap ITC", 0, 47));label1.setBounds(200, 10, 100, 10);label1.setForeground(Color.darkGray);JPanel jp1 = new JPanel();ImageIcon bg = new ImageIcon("/image/444.png") ;bg.setImage(bg.getImage().getScaledInstance(900, 600, Image.SCALE_DEFAULT)); JPanel jp = new JPanel(){@Overrideprotected void paintComponent(Graphics g) {ImageIcon icon = new ImageIcon("images/444.png");Image img = icon.getImage();g.drawImage(img, 0, 0, 400, 350, icon.getImageObserver());}};jp.setBorder(new EmptyBorder(10, 10, 10,10));jp.setBackground(null);jp.setOpaque(false);ImageIcon im=new ImageIcon();JLabel jl1 = new JLabel("账号");jl1.setFont(new Font("微软雅⿊", 0, 14));jl1.setOpaque(false);jl1.setIcon(bg);jtfNumber = new JTextField(15);jp1.add(jl1);jp1.add(jtfNumber);jp1.setOpaque(false);JPanel jp2 = new JPanel();JLabel jl2 = new JLabel("密码");jl2.setFont(new Font("微软雅⿊", 0, 14));jpf = new JPasswordField(15);jp2.add(jl2);jp2.add(jpf);jl2.setOpaque(false);jp2.setOpaque(false);JPanel jp3 = new JPanel();JLabel jl3 = new JLabel("姓名");jl3.setFont(new Font("微软雅⿊", 0, 14));jtfName = new JTextField(15);jp3.add(jl3);jp3.add(jtfName);jl3.setOpaque(false);jp3.setOpaque(false);JPanel jps = new JPanel();jps.setBackground(null);jps.setOpaque(false);Dimension preferredSize = new Dimension(80,40);jbLogin = new JButton("注册");jbLogin.setFont(new Font("微软雅⿊", 0, 14));jbLogin.setPreferredSize(preferredSize);jbLogin.addActionListener(this);//给按钮添加响应jbRegister = new JButton("登录");jbLogin.setFont(new Font("微软雅⿊", 0, 14));jbRegister.setPreferredSize(preferredSize);jbRegister.addActionListener(this);//给按钮添加响应jps.add(jbLogin);jps.add(jbRegister);jp.setBackground(null);jl1.setBackground(null);JPanel jpc = new JPanel(new GridLayout(4, 1));// 4⾏1列布局jpc.setBackground(null);jpc.setOpaque(false);jpc.add(jp1);jpc.add(jp2);jpc.add(jp3);jpc.add(jps);jp.add(label1);jp.add(jpc);add(jp);setTitle("登录窗⼝");//窗⼝标题setSize(400, 350);// 窗⼝⼤⼩setLocationRelativeTo(null);// 窗⼝居中}2.排⾏榜创建Player类,定义name、number、mark三个属性,⽤户游戏得分的⽂件存取格式也是这三个属性,⼀⾏⼀⾏地读取装有⽤户游戏得分的⽂件,⽤split()⽅法将读取出来的⼀⾏数据分装成数组,将这个数组赋值给Player类型的数组,调⽤Arrays.sort()⽅法将数组按升序排序,⽤这个排好序的数组去创建排⾏榜的界⾯,排⾏榜⾄多显⽰前五名public Player[] readChart(int k) throws IOException {final String PATH = "ABC.txt";//指定⽂件的路径File file = new File(PATH);int lines = 0;try {FileInputStream fos = new FileInputStream(file);InputStreamReader osw = new InputStreamReader(fos);BufferedReader bw = new BufferedReader(osw);// 使⽤缓冲区数据流封装输⼊流LineNumberReader lineNumberReader = new LineNumberReader(bw);//获取⽂件⾏数,即玩家⼈数lineNumberReader.skip(Integer.MAX_VALUE);lines = lineNumberReader.getLineNumber() + 1;//从0开始计数,所以这⾥算⾏数的时候需要+1}catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}int i = 0;Player factor[] = new Player[lines];//创建玩家类try {if (!file.exists()) {//判断⽂件是否存在,不存在就创建⼀个⽂件file.createNewFile();}FileReader fr = new FileReader(file); // 创建⽂件输⼊流(读取)BufferedReader br = new BufferedReader(fr); // 使⽤缓冲区数据流封装输⼊流String str = "";while ((str = br.readLine()) != null) {try {String[] data = str.split(" ");int a = Integer.parseInt(data[2]);factor[i]=new Player(data[0],data[1],a);//传⼊name、number、marki++;}catch (ArrayIndexOutOfBoundsException e){System.out.println("数组下标越界");}}Arrays.sort(factor);//根据分数从⾼到低排序}catch(NullPointerException e) {e.printStackTrace();}catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}if(k==0)windoow(factor);return factor;}7.代码静态扫描修改后8.尚待改进或者新的想法尚待改进Beans的默认代码只⽀持JLabel和JButton设置背景图⽚,定制相关的代码之后,还是不能对于⾯板甚⾄整个窗体设置背景图⽚,NetBeans设计页⾯和eclipse⾃⼰写页⾯差别也蛮⼤的,所以最后只是设置了背景颜⾊;2.时间紧任务重,只是构造了游戏的背景⾳乐,没有来的及设计游戏移动⾳效;3.团队协作上,任务分配上有冲突有重复,效率不⾼;4.代码规范上,采⽤插件之后发现有很多以前不会注意到的⼩细节,例如注释的格式是/**注释*/,有些地⽅需要标明@author;5.在GUI设计上,由于对⼀些复杂组件不是特别了解,只是采⽤JPanel⼀些⼩组件,还有很多更简单⽅便的组件没有去设计;新的想法1.将2048⼩游戏转变成安卓⼿机⼩游戏,这个开始有设想过,但是后⾯百度查资料的时候发现真的还挺难的,这个还是得慢慢来;2.加⼊⽅块移动的⾳效;3.在经典玩法之外设计出速度模式;4.增加签到功能获取钻⽯,以钻⽯获取后退⼀步或者开启特殊关卡的机会;5.增设双⼈对战模式;6.将数字⽅块转换成abcd字母或者其他具有递进性的元素;![]。

200 行代码实现简易版 2048 游戏

200 行代码实现简易版 2048 游戏

200 行代码实现简易版2048 游戏创建游戏文件2048.py首先导入需要的包:import cursesfrom random import randrange, choicefrom collections import defaultdict主逻辑用户行为所有的有效输入都可以转换为”上,下,左,右,游戏重置,退出”这六种行为,用actions 表示actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit']有效输入键是最常见的W(上),A(左),S(下),D(右),R(重置),Q(退出),这里要考虑到大写键开启的情况,获得有效键值列表:letter_codes = [ord(ch) for ch in 'WASDRQwasdrq']将输入与行为进行关联:actions_dict = dict(zip(letter_codes, actions * 2))状态机处理游戏主逻辑的时候我们会用到一种十分常用的技术:状态机,或者更准确的说是有限状态机(FSM)你会发现2048 游戏很容易就能分解成几种状态的转换。

state 存储当前状态,state_actions 这个词典变量作为状态转换的规则,它的key 是状态,value 是返回下一个状态的函数:Init: init()GameGame: game() Game WinGameOver ExitWin: lambda:not_game(‘Win’)InitExitGameover: lambda: not_game(‘Gameover’)InitExitExit: 退出循环状态机会不断循环,直到达到Exit 终结状态结束程序。

下面是经过提取的主逻辑的代码,会在后面进行补全:def main(stdscr): def init(): #重置游戏棋盘return 'Game' def not_game(state): #画出GameOver 或者Win 的界面#读取用户输入得到action,判断是重启游戏还是结束游戏responses = defaultdict(lambda: state) #默认是当前状态,没有行为就会一直在当前界面循环responses['Restart'], responses['Exit'] = 'Init', 'Exit' #对应不同的行为转换到不同的状态return responses[action] def game(): #画出当前棋盘状态#读取用户输入得到actionif action == 'Restart': return 'Init' if action == 'Exit': return 'Exit' #if 成功移动了一步: if 游戏胜利了:return 'Win' if 游戏失败了:return 'Gameover' return 'Game'state_actions = { 'Init': init, 'Win': lambda: not_game('Win'), 'Gameover': lambda: not_game('Gameover'), 'Game':game } state = 'Init' #状态机开始循环while state != 'Exit': state = state_actions[state]()用户输入处理阻塞+循环,直到获得用户有效输入才返回对应行为:def get_user_action(keyboard): char = 'N' whilechar not in actions_dict: char = keyboard.getch() return actions_dict[char]矩阵转置与矩阵逆转加入这两个操作可以大大节省我们的代码量,减少重复劳动,看到后面就知道了。

Java实现2048游戏之详细教程

Java实现2048游戏之详细教程

Java实现2048游戏之详细教程⼀、整体项⽬结构使⽤Maven来管理项⽬结构⼆、基本功能实现(⼀)创建游戏窗⼝(静态)package com.baidu.czy;import java.applet.Applet;import java.applet.AudioClip;import java.awt.*;import java.awt.event.ActionEvent;import java.io.File;import .URI;import .URL;import javax.swing.*;//本类继承⾃JFrame,创建游戏窗⼝,只需要new本类对象public class GameStart extends JFrame {File f;URI uri;URL url;private ActionEvent e;// 添加背景⾳乐public GameStart() {try {f = new File("E:\\JavaProject\\HandleGame2048(2)\\src\\main\\resources\\res\\bg1.wav");uri = f.toURI();url = uri.toURL(); //解析地址AudioClip aau;aau = Applet.newAudioClip(url);aau.loop(); //循环播放} catch (Exception e) {e.printStackTrace();}}private static final long serialVersionUID = 1L;//⽤于存放数据的⼆维数组,构成4*4⽹格的游戏界⾯数值,数组中的值就是其对应位置⽅格的值,0代表⽆值private int Numbers[][] = new int[4][4];public void init() {this.setTitle("2048游戏");this.setLocation(450, 100);this.setSize(800, 600);//⾃定义,不使⽤⾯板布局格式this.setLayout(null);//添加标签JLabel jLabel = new JLabel("欢迎来到2048游戏!");jLabel.setFont(new Font("华⽂⾏楷", Font.CENTER_BASELINE, 40));jLabel.setForeground(new Color(0X0000FF));jLabel.setBounds(20, 500, 400, 50);this.add(jLabel);//添加图⽚1( Public ImageIcon(String filename)//参数可以是绝对路径也可以是相对路径)JLabel jLabel1 = new JLabel(new ImageIcon("E:\\JavaProject\\HandleGame2048(2)\\src\\main\\resources\\res\\c.png"));jLabel1.setBounds(400, 5, 400, 600);this.add(jLabel1);//添加图⽚2JLabel jLabel13 = new JLabel(new ImageIcon("E:\\JavaProject\\HandleGame2048(2)\\src\\main\\resources\\res\\d.png"));jLabel13.setBounds(1, 80, 400, 600);this.add(jLabel13);// 开始游戏按钮ImageIcon imgicon = new ImageIcon("E:\\JavaProject\\HandleGame2048(2)\\src\\main\\resources\\res\\start.png");JButton start = new JButton(imgicon);start.setFocusable(false);//设置此按钮不可获取焦点start.setBorderPainted(false);//设置此按钮没有边框start.setFocusPainted(false);//设置不绘制边框,设置 paintFocus属性,对于要绘制的焦点状态,该属性必须为 true。

Java学习—123.2048小游戏

Java学习—123.2048小游戏

Java学习—123.2048小游戏好久又没出现了,还好后台也没几条信息,我也不至于很愧疚,只是人气不太旺盛,好尴尬最近稍微有点忙,也是自己放松了一下,哈哈......抱歉一下,之前给我信息的各位亲,由于时间有点久,我就不一一回复了......前段时间写的关于连数据库的,但时间稍微有点久远了,我有点忘记当时的想法了,所以,这做事情啊,一定要一鼓作气,像我这样的,不用等到三,就已经是再而竭了,不过等我后面做系统的话,会再详细写数据库方面的内容。

最近可能会写几个小游戏,因为突然发现对游戏还挺感兴趣的。

今天要来写一个小游戏:2048数字游戏。

1、2048数字小游戏介绍2048数字游戏是20岁的Gabriele Cirulli开发的一款数字游戏。

这款游戏的玩法很简单,每次可以选择上下左右滑动,每滑动一次,所有的数字方块都会往滑动的方向靠拢,系统也会在空白的地方随机出现一个数字方块,数字的方块在靠拢、相撞时会相加。

不断的叠加最终拼凑出2048这个数字就算成功。

我在做的时候可能跟原作者的这个游戏规则稍微有点改变,大家看下面这个视频就知道是怎么玩了。

2、游戏玩法本游戏我已写好,由于篇幅太长,所以会截成几篇来写,最终的运行结果如下视频演示。

(注:实际游戏也实现了可以通过按键盘来玩,但录视频的时候不知道怎么回事,录不进去,所以只录了用鼠标点击的玩法。

)3、游戏代码本游戏我写了三个类。

这里帖的是第一个。

主方法放在类main中:public class main {public static void main(String[] args){ game_2048 gp = new game_2048(); new Thread(gp,"线程").start();gp.setVisible(true);}}具体的游戏代码详见后面几篇。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

游戏2048的JAVA源代码1.文档说明a) 本代码主要功能为实现2048游戏,GUI界面做到尽量简洁和原游戏相仿。

目前版本不包含计分,计时功能。

b) 本代码受计算机系大神指点,经许可后发布如下,向Java_online网致敬c) 运行时请把.java文件放入Game_one文件夹中方可运行(没有的自己在workplace src中创建)或者直接删去第一个package Game_one;代码即可。

2.运行截图a) 初始状态b) 进入游戏c) 游戏进行中3.JAVA代码package Game_one;import java.awt.*;import java.awt.event.*;import java.util.Random;import javax.swing.*;public class Game2048 extends JPanel {enum State {start, won, running, over}final Color[] colorTable = {new Color(0x701710), new Color(0xFFE4C3), new Color(0xfff4d3),new Color(0xffdac3), new Color(0xe7b08e), new Color(0xe7bf8e),new Color(0xffc4c3), new Color(0xE7948e), new Color(0xbe7e56),new Color(0xbe5e56), new Color(0x9c3931), new Color(0x701710)};final static int target = 2048;static int highest;static int score;private Color gridColor = new Color(0xBBADA0);private Color emptyColor = new Color(0xCDC1B4);private Color startColor = new Color(0xFFEBCD);private Random rand = new Random();private Tile[][] tiles;private int side = 4;private State gamestate = State.start;private boolean checkingAvailableMoves;public Game2048() {setPreferredSize(new Dimension(900, 700));setBackground(new Color(0xFAF8EF));setFont(new Font("SansSerif", Font.BOLD, 48));setFocusable(true);addMouseListener(new MouseAdapter() {@Overridepublic void mousePressed(MouseEvent e) {startGame();repaint();}});addKeyListener(new KeyAdapter() {@Overridepublic void keyPressed(KeyEvent e) {switch (e.getKeyCode()) {case KeyEvent.VK_UP:moveUp();break;case KeyEvent.VK_DOWN:moveDown();break;case KeyEvent.VK_LEFT:moveLeft();break;case KeyEvent.VK_RIGHT:moveRight();break;}repaint();}});}@Overridepublic void paintComponent(Graphics gg) {super.paintComponent(gg);Graphics2D g = (Graphics2D) gg;g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);drawGrid(g);}void startGame() {if (gamestate != State.running) {score = 0;highest = 0;gamestate = State.running;tiles = new Tile[side][side];addRandomTile();addRandomTile();}}void drawGrid(Graphics2D g) {g.setColor(gridColor);g.fillRoundRect(200, 100, 499, 499, 15, 15);if (gamestate == State.running) {for (int r = 0; r < side; r++) {for (int c = 0; c < side; c++) {if (tiles[r][c] == null) {g.setColor(emptyColor);g.fillRoundRect(215 + c * 121, 115 + r * 121, 106, 106, 7, 7);} else {drawTile(g, r, c);}}}} else {g.setColor(startColor);g.fillRoundRect(215, 115, 469, 469, 7, 7);g.setColor(gridColor.darker());g.setFont(new Font("SansSerif", Font.BOLD, 128));g.drawString("2048", 310, 270);g.setFont(new Font("SansSerif", Font.BOLD, 20));if (gamestate == State.won) {g.drawString("you made it!", 390, 350);} else if (gamestate == State.over)g.drawString("game over", 400, 350);g.setColor(gridColor);g.drawString("click to start a new game", 330, 470);g.drawString("(use arrow keys to move tiles)", 310, 530);}}void drawTile(Graphics2D g, int r, int c) {int value = tiles[r][c].getValue();g.setColor(colorTable[(int) (Math.log(value) / Math.log(2)) + 1]);g.fillRoundRect(215 + c * 121, 115 + r * 121, 106, 106, 7,7);String s = String.valueOf(value);g.setColor(value < 128 ? colorTable[0] : colorTable[1]);FontMetrics fm = g.getFontMetrics();int asc = fm.getAscent();int dec = fm.getDescent();int x = 215 + c * 121 + (106 - fm.stringWidth(s)) / 2;int y = 115 + r * 121 + (asc + (106 - (asc + dec)) / 2);g.drawString(s, x, y);}private void addRandomTile() {int pos = rand.nextInt(side * side);int row, col;do {pos = (pos + 1) % (side * side);row = pos / side;col = pos % side;} while (tiles[row][col] != null);int val = rand.nextInt(10) == 0 ? 4 : 2;tiles[row][col] = new Tile(val);}private boolean move(int countDownFrom, int yIncr, int xIncr) { boolean moved = false;for (int i = 0; i < side * side; i++) {int j = Math.abs(countDownFrom - i);int r = j / side;int c = j % side;if (tiles[r][c] == null)continue;int nextR = r + yIncr;int nextC = c + xIncr;while (nextR >= 0 && nextR < side && nextC >= 0 && nextC < side) {Tile next = tiles[nextR][nextC];Tile curr = tiles[r][c];if (next == null) {if (checkingAvailableMoves)return true;tiles[nextR][nextC] = curr;tiles[r][c] = null;r = nextR;c = nextC;nextR += yIncr;nextC += xIncr;moved = true;} else if (next.canMergeWith(curr)) {if (checkingAvailableMoves)return true;int value = next.mergeWith(curr);if (value > highest)highest = value;score += value;tiles[r][c] = null;moved = true;break;} elsebreak;}}if (moved) {if (highest < target) {clearMerged();addRandomTile();if (!movesAvailable()) {gamestate = State.over;}} else if (highest == target)gamestate = State.won;}return moved;}boolean moveUp() {return move(0, -1, 0);}boolean moveDown() {return move(side * side - 1, 1, 0);}boolean moveLeft() {return move(0, 0, -1);}boolean moveRight() {return move(side * side - 1, 0, 1);}void clearMerged() {for (Tile[] row : tiles)for (Tile tile : row)if (tile != null)tile.setMerged(false);}boolean movesAvailable() {checkingAvailableMoves = true;boolean hasMoves = moveUp() || moveDown() || moveLeft() || moveRight();checkingAvailableMoves = false;return hasMoves;}public static void main(String[] args) {SwingUtilities.invokeLater(() -> {JFrame f = new JFrame();f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setTitle("2048");f.setResizable(true);f.add(new Game2048(), BorderLayout.CENTER);f.pack();f.setLocationRelativeTo(null);f.setVisible(true);});}}class Tile {private boolean merged;private int value;Tile(int val) {value = val;}int getValue() {return value;}void setMerged(boolean m) {merged = m;}boolean canMergeWith(Tile other) {return !merged && other != null && !other.merged && value == other.getValue();}int mergeWith(Tile other) {if (canMergeWith(other)) {value *= 2;merged = true;return value;}return -1;}}。

相关文档
最新文档