标签:贪吃蛇 applet
TanChiSheJframe.java
package tanchishe; import java.awt.AWTEvent; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Timer; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JLayeredPane; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.border.BevelBorder; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import util.MyAWTEventListener; public class TanChiSheJframe extends JFrame implements Serializable { /** * */ private static final long serialVersionUID = 5977722980538750979L; static JTable table; static JLayeredPane desktop = null; static TanChiSheTableModule tbModule; static int ROW_COUNT = 22; static int COL_COUNT = 22; static TanChiSheRandomIndex RANDOM_INDEX; static boolean GAME_START = false; public static List<String> displayList = new ArrayList<String>(); static Timer timer; static String randomPosition = null; public static long SCORE = 0L; public TanChiSheJframe() { super(); desktop = this.getLayeredPane(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int screenWitdth = screenSize.width; int screenHeight = screenSize.height; int width = COL_COUNT * 25; int height = ROW_COUNT * 25 + 100; setSize(width, height); setLocation((screenWitdth - width) / 2, (screenHeight - height) / 2); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { TanChiSheJframe myFrame = new TanChiSheJframe(); myFrame.setVisible(true); // myFrame.newGame(); buildFrame(); } public static void begin() { newGame(); } public static void timerStart(boolean flag) { if (flag) { if (timer != null) { timer.cancel(); } timer = new Timer(); TanChiSheTask task = new TanChiSheTask() { public void run() { if (displayList != null && !displayList.isEmpty()) { String[] position = displayList.get(0).split(":"); int x = Integer.valueOf(position[0]); int y = Integer.valueOf(position[1]); String newPosition = moveNext(x, y); checkPass(newPosition); displayList.add(0, newPosition);// 头部位置新增1 // 新的位置上有食物,那么头部加2,尾部清除 // 新的位置上没有食物,那么头部加1,尾部清除 if (compareData(newPosition, randomPosition)) { SCORE += displayList.size(); setScore(); String[] position2 = newPosition.split(":"); int x2 = Integer.valueOf(position2[0]); int y2 = Integer.valueOf(position2[1]); String newPosition2 = moveNext(x2, y2); displayList.add(0, newPosition2);// 头部位置新增2 randomPosition = random();// 新增一个食物 } displayList.remove(displayList.size() - 1);// 尾部位置清除 desktop.repaint(); } } }; timer.schedule(task, new Date(), 250); } else { if (timer != null) { timer.cancel(); timer = null; } } } public static boolean checkPass(String position) { String[] positionXY = position.split(":"); int x = Integer.valueOf(positionXY[0]); int y = Integer.valueOf(positionXY[1]); boolean flag = false; // 超出边界 if (x < 0 || x >= COL_COUNT || y < 0 || y >= ROW_COUNT) { flag = true; JOptionPane.showMessageDialog(table, "游戏结束", "GAME OVER!", JOptionPane.ERROR_MESSAGE); } // 咬到蛇身 if (displayList.contains(position)) { flag = true; JOptionPane.showMessageDialog(table, "蛇咬到了自己!", "GAME OVER!", JOptionPane.ERROR_MESSAGE); } if (flag) { desktop.repaint(); if (timer != null) { timer.cancel(); } return false; } // return; return flag; } public static boolean[][] displayFlagArr; public void move2(int index) { // 0 for (int i = 0; i < ROW_COUNT; i++) { boolean temp = false; for (int j = 0; j < COL_COUNT; j++) { int nextIndex = (j + 1) == COL_COUNT ? 0 : (j + 1); if (j == 0) { temp = displayFlagArr[i][j]; } if (j == COL_COUNT - 1) { displayFlagArr[i][j] = temp; } else { displayFlagArr[i][j] = displayFlagArr[i][nextIndex]; } } } // leftMethod(); } public static String moveNext(int row, int col) { int forwardX = 0; int forwardY = 0; switch (FORWARD) { case 0:// up forwardY = -1; break; case 1:// down forwardY = 1; break; case 2:// left forwardX = -1; break; case 3: // right 默认向右 forwardX = 1; default: break; } int rowNew = row + forwardY; int colNew = col + forwardX; return rowNew + ":" + colNew; } public static void newGame() { SCORE = 0L; displayList.clear(); GAME_START = true; String position = (ROW_COUNT / 2 - 1) + ":" + (COL_COUNT / 2 - 1);// 起始位置 displayList.add(position); randomPosition = random(); timerStart(true); desktop.repaint(); } public static void buildFrame() { desktop.setLayout(new BoxLayout(desktop, BoxLayout.Y_AXIS)); JPanel btnDesc = new JPanel(); btnDesc.add(loadDescription()); desktop.add(btnDesc, 500); desktop.add(Box.createHorizontalStrut(50)); JPanel tbPanel = new JPanel(); tbPanel.add(loadTable()); tbPanel.setBounds(0, 0, 500, 600); desktop.add(tbPanel, 100); desktop.add(Box.createHorizontalStrut(50)); /*JPanel btnPanel = new JPanel(); btnPanel.add(loadButton()); desktop.add(btnPanel, 200);*/ Toolkit.getDefaultToolkit().addAWTEventListener( new MyAWTEventListener() { public void keyPressed(KeyEvent e) { keyEvent(e); } }, AWTEvent.KEY_EVENT_MASK); table.addMouseListener(new TanChiSheMouseListener()); } public static void keyEvent(KeyEvent e) { // System.out.println(e.getKeyCode()); switch (e.getKeyCode()) { case 9:// 9 tab cheat(); break; case 112:// 112 F1 begin(); break; case 113:// 113 F2 pause(); break; case 114:// 114 F3 cheat(); break; case 115:// 115 F4 reQueue(); break; case 37:// 37 left if (FORWARD != 3 && FORWARD != 2) {// 不允许直接转身 FORWARD = 2; } break; case 38:// 38 up if (FORWARD != 0 && FORWARD != 1) {// 不允许直接转身 FORWARD = 0; } break; case 39:// 39 right if (FORWARD != 3 && FORWARD != 2) {// 不允许直接转身 FORWARD = 3; } break; case 40:// 40 down if (FORWARD != 0 && FORWARD != 1) {// 不允许直接转身 FORWARD = 1; } break; default: break; } } Color color = new Color(232, 232, 232); static TanChiSheTableCellRenderer tcr = new TanChiSheTableCellRenderer();// 设置table内容居中 static JLabel jtf = new JLabel(); public static JPanel loadTable() { JPanel fr4 = new JPanel(); fr4.setBorder(new TitledBorder("贪吃蛇")); fr4.setLayout(new BoxLayout(fr4, BoxLayout.Y_AXIS)); tbModule = new TanChiSheTableModule(ROW_COUNT, COL_COUNT); table = new JTable(tbModule); // table.setDefaultRenderer(Object.class, tcr); CellRendererAndMouseListener rendererAndListener = new CellRendererAndMouseListener(); table.addMouseMotionListener(rendererAndListener); table.setDefaultRenderer(Object.class, rendererAndListener); table.setRowSelectionAllowed(false); table.setColumnSelectionAllowed(false); table.setCellSelectionEnabled(false);// 不允许选择Cell tcr.setHorizontalAlignment(SwingConstants.CENTER); tcr.setVerticalAlignment(SwingConstants.CENTER); for (int i = 0; i < table.getColumnCount(); i++) { table.getColumnModel().getColumn(i).setPreferredWidth(22); } table.setRowHeight(22); Border bor = new BevelBorder(BevelBorder.LOWERED); table.setBorder(bor); table.setShowHorizontalLines(false); table.setShowVerticalLines(false); Dimension abc = table.getIntercellSpacing(); abc.setSize(1, 1); table.setIntercellSpacing(abc); JPanel fr5 = new JPanel(); JLabel jlb = new JLabel(); jlb.setHorizontalAlignment(SwingConstants.CENTER); jlb.setVerticalAlignment(SwingConstants.CENTER); jlb.setText("分数:"); fr5.add(jlb); jtf.setPreferredSize(new Dimension(140, 20)); setScore(); jtf.setFont(new Font("Goudy Stout", Font.BOLD, 18)); jtf.setForeground(Color.RED); jtf.setOpaque(true); jtf.setBackground(Color.BLACK); jtf.setHorizontalAlignment(SwingConstants.CENTER); fr5.add(jtf); fr4.add(fr5); fr4.add(table); return fr4; } public static void setScore() { String SCORE_S = String.valueOf(SCORE); for (int i = 8; i > String.valueOf(SCORE).length(); i--) { SCORE_S = "0" + SCORE_S; } jtf.setText(SCORE_S); } public static int FORWARD = 3;// 0 up; 1 down; 2 left; 3 right public static JPanel loadDescription() { JPanel fr = new JPanel(); JLabel j1, j2, j3, j4; fr.setSize(60, 100); j1 = new JLabel("F1 - New Game"); j1.setForeground(Color.BLUE); j1.setOpaque(true); j2 = new JLabel("F2 - Pause"); j2.setForeground(Color.BLUE); j2.setOpaque(true); j3 = new JLabel("F3 - Cheat"); j3.setForeground(Color.BLUE); j3.setOpaque(true); j4 = new JLabel("F4 - Re-Queue"); j4.setForeground(Color.BLUE); j4.setOpaque(true); fr.add(j1); fr.add(j2); fr.add(j3); fr.add(j4); fr.setCursor(new Cursor(12)); return fr; } public static JPanel loadButton() { JPanel fr2 = new JPanel(); fr2.setSize(60, 100); fr2.setLayout(new FlowLayout(FlowLayout.CENTER, 4, 3));// 设置内容面板为流式布局 fr2.setBorder(new EmptyBorder(5, 5, 5, 5));// 设置面板的边框 JButton jbtnBegin = new JButton("New Game"); jbtnBegin.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { begin(); } }); jbtnBegin.setCursor(new Cursor(12)); fr2.add(jbtnBegin); JButton jbtnPause = new JButton("Pause"); jbtnPause.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { pause(); } }); jbtnPause.setCursor(new Cursor(12)); fr2.add(jbtnPause); JButton jbtnCheat = new JButton("Cheat"); jbtnCheat.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { cheat(); } }); jbtnCheat.setCursor(new Cursor(12)); fr2.add(jbtnCheat); return fr2; } static boolean STATUS = true; public static void pause() { if (STATUS) { STATUS = false; } else { STATUS = true; } timerStart(STATUS); } public static void reQueue() { timerStart(false); GAME_START = true; List<String> displayListCopy = new ArrayList<String>(); for (int i = displayList.size() - 1; i >= 0; i--) { int row = i / COL_COUNT; int col = i % COL_COUNT; displayListCopy.add(row + ":" + col); } displayList.clear(); displayList.addAll(displayListCopy); FORWARD = 1;// down randomPosition = random(); timerStart(true); desktop.repaint(); } public static void cheat() { GAME_START = true; List<String> displayListCopy = new ArrayList<String>(); for (int i = displayList.size() - 1; i >= 0; i--) { displayListCopy.add(displayList.get(i)); } displayList.clear(); displayList.addAll(displayListCopy); switch (FORWARD) {// 0 up; 1 down; 2 left; 3 right case 0: FORWARD = 1; break; case 1: FORWARD = 0; break; case 2: FORWARD = 3; break; case 3: FORWARD = 2; break; } randomPosition = random(); timerStart(true); desktop.repaint(); } /** * @param start * when true get center position * @return */ public static String random() { if (RANDOM_INDEX == null) { RANDOM_INDEX = new TanChiSheRandomIndex(); } int index = 0; RANDOM_INDEX.clearRange();// 清空可选随机数范围 for (int row = 0; row < ROW_COUNT; row++) { for (int col = 0; col < COL_COUNT; col++) { if (!displayList.contains(row + ":" + col)) { RANDOM_INDEX.addIndexL(row * COL_COUNT + col);// 添加可用随机数 } } } index = RANDOM_INDEX.randomIndex(); int row = index / COL_COUNT; int col = index % COL_COUNT; return (row + ":" + col); } public boolean checkEmpty(Object cellV) { if (cellV == null || String.valueOf(cellV).length() == 0) { return true; } return false; } public static boolean compareData(Object val1, Object val2) { if ((val1 == null && val2 == null) || (String.valueOf(val1).equals(String.valueOf(val2)))) { return true; } return false; } public boolean compareArr(Object[][] dataArr1, Object[][] dataArr2) { for (int rowIndex = 1; rowIndex < ROW_COUNT; rowIndex++) { for (int colIndex = 0; colIndex < COL_COUNT; colIndex++) { if (!compareData(dataArr1[rowIndex][colIndex], dataArr2[rowIndex][colIndex])) { return false; } } } return true; } }
TanChiSheKeyListener.java
package tanchishe; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class TanChiSheKeyListener implements KeyListener { public void keyPressed(KeyEvent e) { // 37 left // 38 up // 39 right // 40 down } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } }
TanChiSheMouseListener.java
package tanchishe; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; public class TanChiSheMouseListener implements MouseListener,MouseMotionListener { public void mouseClicked(MouseEvent e) { // 1 left click // 2 scroll click // 3 right click //System.out.println(e.getButton()); return; } public void mouseEntered(MouseEvent e) { return; } public void mouseExited(MouseEvent e) { return; } public void mousePressed(MouseEvent e) { return; } public void mouseReleased(MouseEvent e) { return; } public void mouseDragged(MouseEvent e) { return; } public void mouseMoved(MouseEvent e) { return; } }
TanChiSheRandomIndex.java
package tanchishe; import java.util.ArrayList; import java.util.List; import java.util.Random; public class TanChiSheRandomIndex { List<Integer> indexL = null; Random random = new Random(); public void addIndexL(Integer i) { if (indexL == null) { indexL = new ArrayList<Integer>(); } indexL.add(i); } // public int getCenterNumber() { // // int number = indexL.size() / 2 - 1; // indexL.remove(number); // return number; // } public void clearRange() { if (indexL != null) { indexL.clear(); } } public int randomIndex() { if (indexL.isEmpty()) { System.out.println("No more data!"); return -1; } int index = random.nextInt(indexL.size()); int number = indexL.get(index); indexL.remove(index); return number; } }
TanChiSheTable.java
package tanchishe; import javax.swing.JTable; import javax.swing.table.TableModel; public class TanChiSheTable extends JTable { /** * serialVersionUID */ private static final long serialVersionUID = -5218217955961436299L; public TanChiSheTable() { super(); } public TanChiSheTable(TableModel tm) { super(tm); } public boolean isCellSelected(int i, int j) { return false; } }
TanChiSheTableCellRenderer.java
package tanchishe; import java.awt.Color; import java.awt.Component; import java.io.Serializable; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; public class TanChiSheTableCellRenderer extends DefaultTableCellRenderer implements Serializable { /** * serialVersionUID */ private static final long serialVersionUID = 7075922603764573186L; public TanChiSheTableCellRenderer() { setOpaque(true); } static Color color_gray = new Color(232, 232, 232); static Color color_food = new Color(112, 0, 112); public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component editor = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); editor.setBackground(color_gray); if (TanChiSheJframe.displayList.contains(row + ":" + column)) { editor.setBackground(Color.BLACK); } else if ((row + ":" + column).equals(TanChiSheJframe.randomPosition)) { editor.setBackground(color_food); } else { editor.setBackground(color_gray); } return editor; } }
TanChiSheTableModule.java
package tanchishe; import java.io.Serializable; import javax.swing.table.AbstractTableModel; public class TanChiSheTableModule extends AbstractTableModel implements Serializable { /** * */ private static final long serialVersionUID = 1978547795796513859L; private int rowCount = 1; private int columnCount = 1; private static Object[][] dataArr = null; public TanChiSheTableModule(int rowCount, int columnCount) { if (columnCount > 1) { this.columnCount = columnCount; } else { this.columnCount = 1; } if (rowCount > 1) { this.rowCount = rowCount; } else { this.rowCount = 1; } initTableDataAndHearder(); } public Class<?> getColumnClass(int columnIndex) { if (getValueAt(0, columnIndex) != null) { return getValueAt(0, columnIndex).getClass(); } else { return String.class; } } public String getColumnName(int columnIndex) { return " 第" + columnIndex + "列"; } public void setValueAt(Object aValue, int rowIndex, int columnIndex) { if (rowIndex >= rowCount) { new Exception("Row Index Outbound!").printStackTrace(); } if (columnIndex >= columnCount) { new Exception("Column Index Outbound!").printStackTrace(); } if (dataArr == null) { initTableDataAndHearder(); } dataArr[rowIndex][columnIndex] = aValue; fireTableCellUpdated(rowIndex, columnIndex); } public void initTableDataAndHearder() { dataArr = new Object[rowCount][columnCount]; } public Object getValueAt(int rowIndex, int columnIndex) { if (dataArr == null) { initTableDataAndHearder(); } Object val = dataArr[rowIndex][columnIndex]; return val; } public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } public int getRowCount() { return rowCount; } public int getColumnCount() { return columnCount; } public Object[][] getDataArr() { return dataArr; } public void setDataArr(Object[][] dataArr) { TanChiSheTableModule.dataArr = dataArr; } }
CellRendererAndMouseListener.java
package tanchishe; import java.awt.Color; import java.awt.Component; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; public class CellRendererAndMouseListener extends JLabel implements TableCellRenderer, MouseMotionListener { /** * */ private static final long serialVersionUID = 7083489923614792312L; public CellRendererAndMouseListener() { setOpaque(true); } static Color color_gray = new Color(232, 232, 232); static Color color_food = new Color(112, 0, 112); public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { this.setBackground(color_gray); if (TanChiSheJframe.displayList.contains(row + ":" + column)) { this.setBackground(Color.BLACK); } else if ((row + ":" + column).equals(TanChiSheJframe.randomPosition)) { this.setBackground(color_food); } else { this.setBackground(color_gray); } return this; } public void mouseMoved(MouseEvent e) { JTable table = (JTable) e.getSource(); table.repaint(); } public void mouseDragged(MouseEvent e) { } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }
TanChiSheTask.java
package tanchishe; import java.util.TimerTask; public class TanChiSheTask extends TimerTask { @Override public void run() { System.out.println("Timer Start!!"); } }
DataModule.java
package tanchishe; public class DataModule { int row = -1; int col = -1; public DataModule(int row, int col) { this.row = row; this.col = col; } public int getCol() { return col; } public void setCol(int col) { this.col = col; } public int getRow() { return row; } public void setRow(int row) { this.row = row; } }
标签:贪吃蛇 applet
原文地址:http://stanny.blog.51cto.com/836013/1931379