贪吃蛇程序:
GreedSnake.java (也是程序入口):
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Iterator;
import java.util.LinkedList;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GreedSnake implements KeyListener {
JFrame mainFrame;
Canvas paintCanvas;
JLabel labelScore;// 计分牌
SnakeModel snakeModel = null;// 蛇
public static final int canvasWidth = 200;
public static final int canvasHeight = 300;
public static final int nodeWidth = 10;
public static final int nodeHeight = 10;
// ----------------------------------------------------------------------
// GreedSnake():初始化游戏界面
// ----------------------------------------------------------------------
public GreedSnake() {
// 设置界面元素
mainFrame = new JFrame("GreedSnake");
Container cp = mainFrame.getContentPane();
labelScore = new JLabel("Score:");
cp.add(labelScore, BorderLayout.NORTH);
paintCanvas = new Canvas();
paintCanvas.setSize(canvasWidth + 1, canvasHeight + 1);
paintCanvas.addKeyListener(this);
cp.add(paintCanvas, BorderLayout.CENTER);
JPanel panelButtom = new JPanel();
panelButtom.setLayout(new BorderLayout());
JLabel labelHelp;// 帮助信息
labelHelp = new JLabel("PageUp, PageDown for speed;", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.NORTH);
labelHelp = new JLabel("ENTER or R or S for start;", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.CENTER);
labelHelp = new JLabel("SPACE or P for pause", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.SOUTH);
cp.add(panelButtom, BorderLayout.SOUTH);
mainFrame.addKeyListener(this);
mainFrame.pack();
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
begin();
}
// ----------------------------------------------------------------------
// keyPressed():按键检测
// ----------------------------------------------------------------------
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (snakeModel.running)
switch (keyCode) {
case KeyEvent.VK_UP:
snakeModel.changeDirection(SnakeModel.UP);
break;
case KeyEvent.VK_DOWN:
snakeModel.changeDirection(SnakeModel.DOWN);
break;
case KeyEvent.VK_LEFT:
snakeModel.changeDirection(SnakeModel.LEFT);
break;
case KeyEvent.VK_RIGHT:
snakeModel.changeDirection(SnakeModel.RIGHT);
break;
case KeyEvent.VK_ADD:
case KeyEvent.VK_PAGE_UP:
snakeModel.speedUp();// 加速
break;
case KeyEvent.VK_SUBTRACT:
case KeyEvent.VK_PAGE_DOWN:
snakeModel.speedDown();// 减速
break;
case KeyEvent.VK_SPACE:
case KeyEvent.VK_P:
snakeModel.changePauseState();// 暂停或继续
break;
default:
}
// 重新开始
if (keyCode == KeyEvent.VK_R || keyCode == KeyEvent.VK_S
|| keyCode == KeyEvent.VK_ENTER) {
snakeModel.running = false;
begin();
}
}
// ----------------------------------------------------------------------
// keyReleased():空函数
// ----------------------------------------------------------------------
public void keyReleased(KeyEvent e) {
}
// ----------------------------------------------------------------------
// keyTyped():空函数
// ----------------------------------------------------------------------
public void keyTyped(KeyEvent e) {
}
// ----------------------------------------------------------------------
// repaint():绘制游戏界面(包括蛇和食物)
// ----------------------------------------------------------------------
void repaint() {
Graphics g = paintCanvas.getGraphics();
// draw background
g.setColor(Color.WHITE);
g.fillRect(0, 0, canvasWidth, canvasHeight);
// draw the snake
g.setColor(Color.BLACK);
LinkedList na = snakeModel.nodeArray;
Iterator it = na.iterator();
while (it.hasNext()) {
Node n = (Node) it.next();
drawNode(g, n);
}
// draw the food
g.setColor(Color.RED);
Node n = snakeModel.food;
drawNode(g, n);
updateScore();
}
// ----------------------------------------------------------------------
// drawNode():绘画某一结点(蛇身或食物)
// ----------------------------------------------------------------------
private void drawNode(Graphics g, Node n) {
g.fillRect(n.x * nodeWidth, n.y * nodeHeight, nodeWidth - 1,
nodeHeight - 1);
}
// ----------------------------------------------------------------------
// updateScore():改变计分牌
// ----------------------------------------------------------------------
public void updateScore() {
String s = "Score: " + snakeModel.score;
labelScore.setText(s);
}
// ----------------------------------------------------------------------
// begin():游戏开始,放置贪吃蛇
// ----------------------------------------------------------------------
void begin() {
if (snakeModel == null || !snakeModel.running) {
snakeModel = new SnakeModel(this, canvasWidth / nodeWidth,
this.canvasHeight / nodeHeight);
(new Thread(snakeModel)).start();
}
}
// ----------------------------------------------------------------------
// main():主函数
// ----------------------------------------------------------------------
public static void main(String[] args) {
GreedSnake gs = new GreedSnake();
}
}
Node.java:
public class Node {
int x;
int y;
Node(int x, int y) {
this.x = x;
this.y = y;
}
}
SnakeModel.java:
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Random;
import javax.swing.JOptionPane;
public class SnakeModel implements Runnable {
GreedSnake gs;
boolean[][] matrix;// 界面数据保存在数组里
LinkedList nodeArray = new LinkedList();
Node food;
int maxX;// 最大宽度
int maxY;// 最大长度
int direction = 2;// 方向
boolean running = false;
int timeInterval = 200;// 间隔时间(速度)
double speedChangeRate = 0.75;// 速度改变程度
boolean paused = false;// 游戏状态
int score = 0;
int countMove = 0;
// UP和DOWN是偶数,RIGHT和LEFT是奇数
public static final int UP = 2;
public static final int DOWN = 4;
public static final int LEFT = 1;
public static final int RIGHT = 3;
// ----------------------------------------------------------------------
// GreedModel():初始化界面
// ----------------------------------------------------------------------
public SnakeModel(GreedSnake gs, int maxX, int maxY) {
this.gs = gs;
this.maxX = maxX;
this.maxY = maxY;
matrix = new boolean[maxX][];
for (int i = 0; i < maxX; ++i) {
matrix[i] = new boolean[maxY];
Arrays.fill(matrix[i], false);// 没有蛇和食物的地区置false
}
// 初始化贪吃蛇
int initArrayLength = maxX > 20 ? 10 : maxX / 2;
for (int i = 0; i < initArrayLength; ++i) {
int x = maxX / 2 + i;
int y = maxY / 2;
nodeArray.addLast(new Node(x, y));
matrix[x][y] = true;// 蛇身处置true
}
food = createFood();
matrix[food.x][food.y] = true;// 食物处置true
}
// ----------------------------------------------------------------------
// changeDirection():改变运动方向
// ----------------------------------------------------------------------
public void changeDirection(int newDirection) {
if (direction % 2 != newDirection % 2)// 避免冲突
{
direction = newDirection;
}
}
// ----------------------------------------------------------------------
// moveOn():贪吃蛇运动函数
// ----------------------------------------------------------------------
public boolean moveOn() {
Node n = (Node) nodeArray.getFirst();
int x = n.x;
int y = n.y;
switch (direction) {
case UP:
y--;
break;
case DOWN:
y++;
break;
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
}
if ((0 <= x && x < maxX) && (0 <= y && y < maxY)) {
if (matrix[x][y])// 吃到食物或者撞到身体
{
if (x == food.x && y == food.y)// 吃到食物
{
nodeArray.addFirst(food);// 在头部加上一结点
// 计分规则与移动长度和速度有关
int scoreGet = (10000 - 200 * countMove) / timeInterval;
score += scoreGet > 0 ? scoreGet : 10;
countMove = 0;
food = createFood();
matrix[food.x][food.y] = true;
return true;
} else
return false;// 撞到身体
} else// 什么都没有碰到
{
nodeArray.addFirst(new Node(x, y));// 加上头部
matrix[x][y] = true;
n = (Node) nodeArray.removeLast();// 去掉尾部
matrix[n.x][n.y] = false;
countMove++;
return true;
}
}
return false;// 越界(撞到墙壁)
}
// ----------------------------------------------------------------------
// run():贪吃蛇运动线程
// ----------------------------------------------------------------------
public void run() {
running = true;
while (running) {
try {
Thread.sleep(timeInterval);
} catch (Exception e) {
break;
}
if (!paused) {
if (moveOn())// 未结束
{
gs.repaint();
} else// 游戏结束
{
JOptionPane.showMessageDialog(null, "GAME OVER",
"Game Over", JOptionPane.INFORMATION_MESSAGE);
break;
}
}
}
running = false;
}
// ----------------------------------------------------------------------
// createFood():生成食物及放置地点
// ----------------------------------------------------------------------
private Node createFood() {
int x = 0;
int y = 0;
do {
Random r = new Random();
x = r.nextInt(maxX);
y = r.nextInt(maxY);
} while (matrix[x][y]);
return new Node(x, y);
}
// ----------------------------------------------------------------------
// speedUp():加快蛇运动速度
// ----------------------------------------------------------------------
public void speedUp() {
timeInterval *= speedChangeRate;
}
// ----------------------------------------------------------------------
// speedDown():放慢蛇运动速度
// ----------------------------------------------------------------------
public void speedDown() {
timeInterval /= speedChangeRate;
}
// ----------------------------------------------------------------------
// changePauseState(): 改变游戏状态(暂停或继续)
// ----------------------------------------------------------------------
public void changePauseState() {
paused = !paused;
}
}
下面是我大学时写的扫雷,希望对你有帮助:
/*
This class defines a class that contains some useful
attributions and some methods to set or get these attributions
*/
import javax.swing.JButton;
public class ExButton extends JButton
{
//if the button is a mine,the isMine will be true
private boolean isMine;
//to check if a button has been visited is useful
//when using the recursion in the Game class
private boolean isVisited;
//the row number of the button
int btnRowNumber;
//the column number of the button
int btnColumnNumber;
//the mines around a button
int minesAround=0;
public void setIndex(int btnRowNumber,int btnColumnNumber)
{
this.btnRowNumber=btnRowNumber;
this.btnColumnNumber=btnColumnNumber;
}
public int getRowNumber()
{
return this.btnRowNumber;
}
public int getColumnNumber()
{
return this.btnColumnNumber;
}
public void setVisited(boolean isVisited)
{
this.isVisited=isVisited;
}
public boolean getVisited()
{
return this.isVisited;
}
public void setMine(boolean isMine)
{
this.isMine=isMine;
}
public boolean getMine()
{
return this.isMine;
}
//the attribute of minesAround add one each
//time a mine is put down around the button
public void addMinesAround()
{
this.minesAround++;
}
public int getMinesAround()
{
return this.minesAround;
}
}
-------------------------------------------------
/*
File Name: Game.java
Author: Tian Wei Student Number: Email: xiangchensuiyue@163.com
Assignment number: #4
Description: In this program ,a frame will be created which contains
ten "mines".When you click a button ,it will present the
number of mines around or a message of losing the game
(if the button is a mine).You can make a right click to
sign a dengerous button as well.When all the mines have
been signed ,a message box of winning the game will jump
to the screen.And the the message of the time you used in
the game.More over,you can click the button on the bottom
to restart the game.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.Random;
import java.util.Timer;
public class Game extends JFrame{
//define some menber variables
private long minute=0,second=0;//take down time used int the game
private ExButton[][] btn;//two-dimension array present the buttons
private JLabel label;
private JButton restart;//restart button
private int minesRemained;//remained mines that you have not signed
private boolean thisTry=true;
private JLabel timeUsed=new JLabel ();
private Random rand=new Random();
private final int ROWS,COLUMNS;
private final int MINES;
// the constuctor
public Game(int rows,int columns,int mines)
{
super("Find mines");
this.ROWS=rows;
this.COLUMNS=columns;
this.MINES=mines;
minesRemained=MINES;
Timer timer=new Timer();//Timer's object to timer the game
timer.schedule(new MyTimer(), 0, 1000);//do the function every second
Container container=getContentPane();
container.setLayout(new BorderLayout());
//Jpanel in the Container
JPanel jpanel=new JPanel();
jpanel.setLayout(new GridLayout(ROWS,COLUMNS));
restart=new JButton("click me to restart the game");
JPanel jpanel2=new JPanel();
//Another JPanel in the Container
jpanel2.setLayout(new FlowLayout());
jpanel2.add(timeUsed);
jpanel2.add(restart);
ButtonListener restartHandler=new ButtonListener();
restart.addActionListener(restartHandler);
container.add(jpanel2,BorderLayout.SOUTH);
btn=new ExButton[ROWS+2][COLUMNS+2];
//initialize the buttons
for(int i=0;i<=ROWS+1;i++)
{
for(int j=0;j<=COLUMNS+1;j++)
{
btn[i][j]=new ExButton();
btn[i][j].addMouseListener(new MouseClickHandler());
btn[i][j].setIndex(i,j);
btn[i][j].setVisited(false);
}
}
for(int i=1;i<=ROWS;i++)
for(int j=1;j<=COLUMNS;j++)
jpanel.add(btn[i][j]);
container.add(jpanel,BorderLayout.CENTER);
JPanel jpanel3=new JPanel ();
label=new JLabel();
label.setText("Mines remaining "+MINES);
jpanel3.add(label);
container.add(jpanel3,BorderLayout.NORTH );
this.addMines();
this.addMinesAround();
}
//randomly put ten mines
private void addMines()
{
for(int i=1;i<=MINES;i++)
{
int raInt1=rand.nextInt(ROWS);
int raInt2=rand.nextInt(COLUMNS);
if((raInt1==0)||(raInt2==0)||btn[raInt1][raInt2].getMine())
i--;
else
btn[raInt1][raInt2].setMine(true);
}
}
//take down the mines around a button
private void addMinesAround()
{
for(int i=1;i<=ROWS;i++)
{
for(int j=1;j<=COLUMNS;j++)
{
if(btn[i][j].getMine())
{
btn[i][j-1].addMinesAround();
btn[i][j+1].addMinesAround();
btn[i-1][j-1].addMinesAround();
btn[i-1][j].addMinesAround();
btn[i-1][j+1].addMinesAround();
btn[i+1][j-1].addMinesAround();
btn[i+1][j].addMinesAround();
btn[i+1][j+1].addMinesAround();
}
}
}
}
//if a button clicked is a empty one,then use a recursion
//to find all the empty buttons around
private void checkEmpty(ExButton button)
{
button.setVisited(true);
int x=button.getRowNumber();
int y=button.getColumnNumber();
button.setBackground(Color.white);
if((button.getMinesAround()==0)&&(x>=1)&&(x<=ROWS)
&&(y>=1)&&(y<=COLUMNS))
{
if(!btn[x][y-1].getVisited())
checkEmpty(btn[x][y-1]);
if(!btn[x][y+1].getVisited())
checkEmpty(btn[x][y+1]);
if(!btn[x-1][y].getVisited())
checkEmpty(btn[x-1][y]);
if(!btn[x+1][y].getVisited())
checkEmpty(btn[x+1][y]);
if(!btn[x-1][y-1].getVisited())
checkEmpty(btn[x-1][y-1]);
if(!btn[x-1][y+1].getVisited())
checkEmpty(btn[x-1][y+1]);
if(!btn[x+1][y-1].getVisited())
checkEmpty(btn[x+1][y-1]);
if(!btn[x+1][y+1].getVisited())
checkEmpty(btn[x+1][y+1]);
}
else if(button.getMinesAround()>0)
button.setText(""+button.getMinesAround());
}
//the main function
public static void main(String args[])
{
String rows,columns,mines;
int rowNumber,columnNumber,mineNumber;
rows=JOptionPane.showInputDialog("Enter the rows of the game");
columns=JOptionPane.showInputDialog("Enter the columns of the game");
mines=JOptionPane.showInputDialog("Enter the mines of the game");
rowNumber=Integer.parseInt(rows);
columnNumber=Integer.parseInt(columns);
mineNumber=Integer.parseInt(mines);
Game frame=new Game(rowNumber,columnNumber,mineNumber);
frame.setTitle("Find Mines");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(220, 80);
frame.setSize(600, 600 );
frame.setVisible(true);
}
//there are three inner class below
//The first inner class is used to do the mouse listener's
//function.When you click a button ,it will present the
//number of mines around or a message of losing the game
//(if the button is a mine).You can make a right click to
//sign a dengerous button as well.When ten mines have been
//signed,it will check whether all the signed ones are mines
private class MouseClickHandler extends MouseAdapter
{
public void mouseClicked(MouseEvent event)
{
//get the button that been clicked
ExButton eventButton=new ExButton();
eventButton=(ExButton)event.getSource();
eventButton.setVisited(true);
//when it is a right click
if(event.isMetaDown())
{
if(eventButton.getText()=="#")
{
minesRemained++;
eventButton.setText("");
}
else
{
if((eventButton.getBackground()==Color.white)||
(eventButton.getText()!=""))
{
//do nothing
}
else
{
minesRemained--;
eventButton.setText("#");
}
}
label.setText("Mines remaining "+minesRemained);
//check if all the signed buttons are mines
if(minesRemained==0)
{
for(int i=1;i<=ROWS;i++)
for(int j=1;j<=COLUMNS;j++)
{
if(btn[i][j].getMine()&&btn[i][j].getText()!="#")
thisTry=false;
if(!btn[i][j].getMine()&&btn[i][j].getText()=="#")
thisTry=false;
}
if(thisTry)
{
//win the game
JOptionPane.showMessageDialog(null, "You succeed" +
" in this experience!");
JOptionPane.showMessageDialog(null, "Time used:"+
timeUsed.getText());
}
else//you have wrongly signed one or more mines
JOptionPane.showMessageDialog(null, "You have wrongly " +
"signed one or more mines,please check it and go on!");
}
}
else if(event.isAltDown())
{
//do nothing
}
else
{//normally click(left click)
if(eventButton.getText()=="#")
{
//do nothing
}
else if(eventButton.getMine())
{
//lose the game
JOptionPane.showMessageDialog(null, "What a pity!" +
"You failed!" );
//show all the mines to the loser
for(int i=1;i<=ROWS;i++)
for(int j=1;j<=COLUMNS;j++)
{
if(btn[i][j].getMine())
btn[i][j].setBackground(Color.BLACK);
}
JOptionPane.showMessageDialog(null, "Time used: 0"+
minute+":"+second);
}
else
{
if(eventButton.getMinesAround()==0)
{
//call the function to find all the empty buttons around
checkEmpty(eventButton);
}
else
eventButton.setText(""+eventButton.getMinesAround());
}
}
}
}
//The second class is to listen to the button which used to
//restart the game.In this class,it will dispose the old frame
//and create a new one(Of course,the mines's position have
//been changed).
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
//what to dispose is the object of Game class
Game.this.dispose();
//the same code as in the main function
Game frame=new Game(ROWS,COLUMNS,MINES);
frame.setTitle("Find Mines");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600 );
//make sure the frame is at the center of the screen
frame.setLocation(220, 80);
frame.setVisible(true);
}
}
//The last class is the class that will be used in the
//Timer's object timer.It should inherit the class TimerTask
//It is the task that the Timer will do every second
private class MyTimer extends TimerTask
{
public void run()
{
second+=1;
minute+=second/60;
second=second%60;
//change the text of the time used in the game
timeUsed.setText("Time used 0"+minute+":"+second);
}
}
}//end of the class Game
import java.util.Random;
import java.util.Scanner;
public class Game {
private static int win=0;
private static int fail=0;
private static int pi=0;
private static void check(int cpu,int pe){
int t=0;
if(pe-cpu==2) t= -1;
else if(pe-cpu==-2) t= 1;
else t=pe-cpu;
if(t>0) {System.out.println("你赢了!");win++;}
else if(t==0) {System.out.println("咱们平了!");pi++;}
else {System.out.println("你输了!");fail++;}
}
public static void main(String[] args) {
String input="";
String cpuStr="";
Random rand=new Random();
int cpu=0;
int pe=0;
while(true){
System.out.println("*************************小游戏一个 输e/E可以退出*****************");
System.out.println("请选择你要出什么?F--剪刀(forfex),S--石头(stone),C--布(cloth)");
Scanner scan=new Scanner(System.in);
input=scan.nextLine();
cpu=rand.nextInt(3);
if(cpu==0)cpuStr="剪刀";
else if(cpu==1)cpuStr="石头";
else cpuStr="布";
if(input.equals("F")||input.equals("f")){
pe=0;
System.out.println("你出的是,剪刀");
System.out.println("我出"+cpuStr);
check(cpu,pe);
}else if(input.equals("S")||input.equals("s")){
pe=1;
System.out.println("你出的是,石头");
System.out.println("我出"+cpuStr);
check(cpu,pe);
}else if(input.equals("C")||input.equals("c")){
pe=2;
System.out.println("你出的是,布");
System.out.println("我出"+cpuStr);
check(cpu,pe);
}else if(input.equals("E")||input.equals("e")){
System.out.println("结束游戏。。");
System.out.println("结果统计:");
System.out.println("胜:"+win+"局");
System.out.println("负:"+fail+"局");
System.out.println("平:"+pi+"局");
System.exit(0);
}
}
}
}
以上回答参考:
http://zhidao.baidu.com/question/39899654.html