如何用200行java代碼實現2048小游戲-創(chuàng)新互聯

這篇文章主要講解了如何用200行java代碼實現2048小游戲,內容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。

創(chuàng)新互聯主營羅江網站建設的網絡公司,主營網站建設方案,手機APP定制開發(fā),羅江h(huán)5微信小程序開發(fā)搭建,羅江網站營銷推廣歡迎羅江等地區(qū)企業(yè)咨詢

效果圖:

如何用200行java代碼實現2048小游戲

游戲介紹:

1.2048是一款益智類小游戲,剛開始隨機出現兩個數字,可以上下左右控制數字的移動。
2.當選擇一個方向移動后,所有數字都會沿該方向移動到表格盡頭,并且空余表格會隨機出現2或4,當碰到相同的兩個數字時,該兩個數字會合并相加成一個數字,直到大的數字變成2048游戲成功
3.否則當數字填滿表格且不能再移動時游戲失敗。

游戲代碼:

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() {
 @Override
 public void mousePressed(MouseEvent e) {
 startGame();
 repaint();
 }
 });
 addKeyListener(new KeyAdapter() {
 @Override
 public 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();
 }
 });
 }

 @Override
 public 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 &#63; 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 &#63; 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;
 } else
  break;
 }
 }
 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;
 }
}

另外有需要云服務器可以了解下創(chuàng)新互聯建站muchs.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。

文章名稱:如何用200行java代碼實現2048小游戲-創(chuàng)新互聯
轉載注明:http://muchs.cn/article38/phcpp.html

成都網站建設公司_創(chuàng)新互聯,為您提供搜索引擎優(yōu)化標簽優(yōu)化、域名注冊、Google、App開發(fā)、自適應網站

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯

網站建設網站維護公司