用JAVA编一个小游戏或者其他程序

作者&投稿:牟庾 (若有异议请与网页底部的电邮联系)
用JAVA编写一个小游戏~

前天写的猜数字游戏,yong i控制猜测次数,有详细解析,用黑窗口可以直接运行,
我试验过了,没问题
import javax.swing.Icon;import javax.swing.JOptionPane;public class CaiShuZi4JOptionPane { /** * @param args */ public static void main(String[] args) { Icon icon = null; boolean bl = false; int put = 0; int c = (int) (((Math.random())*100)+1); //获取一个1-100的随机数 System.out.println("你获取的随机数是:"+c); //打印你的随机数字 String str1 = (String) JOptionPane.showInputDialog(null,"请输入你的猜测数字(1-100):
","猜数字游戏",JOptionPane.PLAIN_MESSAGE,icon,null,"在这输入"); //第一次输入你的猜测数字 if(str1==null){ JOptionPane.showMessageDialog(null, "你已经取消了本次游戏"); //如果你点取消那么本次游戏结束 }else{ bl = num(str1); //判断是输入的是不是数字或者是整数 if(true==bl){ //如果是数字的话进入与随机数比较的程序 System.out.println("你输入的数字是:"+str1); //打印你输入的数字 put = Integer.valueOf(str1); for(int i = 4;i > 0;i--){ //i是你可以猜测的次数 if(put==c){ JOptionPane.showMessageDialog(null, "恭喜你猜对了,正确答案是:"+c+"。"); //如果你猜对了就直接结束循环 break; }else if(put>c){ //如果输大了就让你再次从新输入 str1 = (String) JOptionPane.showInputDialog(null,"你的输入过大。你还有"+i+"次机会,请重新输入:
","猜数字游戏",JOptionPane.PLAIN_MESSAGE,icon,null,"在这输入"); if(str1==null){ JOptionPane.showMessageDialog(null, "你已经取消了本次输入"); break; }else{ bl =num(str1); if(true==bl){ put = Integer.valueOf(str1); }else{ JOptionPane.showMessageDialog(null, "你的输入不正确,请重新输入"); } } }else if(put<c){ //如果你输小了也让你从新输入 str1 = (String) JOptionPane.showInputDialog(null,"你的输入过小。你还有"+i+"次机会,请重新输入:
","猜数字游戏",JOptionPane.PLAIN_MESSAGE,icon,null,"在这输入"); if(str1==null){ JOptionPane.showMessageDialog(null, "你已经取消了本次输入"); break; }else{ bl =num(str1); if(true==bl){ put = Integer.valueOf(str1); }else{ JOptionPane.showMessageDialog(null, "你的输入不正确,请重新输入"); } } } } }else if(bl==false){ //这个 是你第一次如果填写的不是数字的话也会结束本次游戏 JOptionPane.showMessageDialog(null, "请您下次按要求填写。本次游戏结束"); } if(true==bl && c!=put){ //如果你i次都没猜对,那么就直接告诉你这个数十什么 JOptionPane.showMessageDialog(null, "很遗憾你没能猜对,这个数字是:"+c+"."); } } } public static boolean num(String value){ //一个静态方法,判断你输入的是不是数字 try { Integer.parseInt(value); return true; } catch (Exception e) { return false; } }}

import java.util.*;
import java.io.*;
public class CaiShu{
public static void main(String[] args) throws IOException{
Random a=new Random();
int num=a.nextInt(100);
System.out.println("请输入一个100以内的整数:");
for (int i=0;i<=9;i++){
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
String str=bf.readLine();
int shu=Integer.parseInt(str);
if (shu>num)
System.out.println("输入的数大了,输小点的!");
else if (shu<num)
System.out.println("输入的数小了,输大点的!");
else {
System.out.println("恭喜你,猜对了!");
if (i<=2)
System.out.println("你真是个天才!");
else if (i<=6)
System.out.println("还将就,你过关了!");
else if (i<=8)
System.out.println("但是你还……真笨!");
else
System.out.println("你和猪没有两样了!"); break;}
}
} }

贪吃蛇程序:
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


急急急,用JAVA编一个猜数字的小游戏
import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing....

跪求JAVA编写的小游戏源代码
import java.awt.*;import java.applet.*;import java.awt.event.*;import java.awt.image.*;import java.awt.geom.*;import java.util.*;class Car{ Image img;int x, y;Dimension dim;Car(Image img){ this.img=img;} Car(Image img, int x, int y){ this.img=img; this.x=x; ...

求一个JAVA“拿火柴小游戏”的程序 要求如下!!!求!!!
按照题目要求,人拿完火柴后计算机自动拿火柴,判断胜利者。鼠标点击ok或者键盘按enter键即可提交人拿的火柴个数。图形界面如下,import java.awt.*;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.sql.PreparedStatement;import java...

java 面向对象设计 运用GUI技术的开发 进行小游戏程序的开发_百度知 ...
\/* 原始图片分为16块第一块为 空白 我是这样想的:因为无法将图片分成15份而放到16块的区域中(至少是很难实现)因此将原始图片中一部分处理成白色,这样就好处理了 \/ import java.awt.Graphics;import java.awt.GridLayout;import java.awt.Image;import java.awt.MediaTracker;import java.awt....

java小游戏编好后在哪里运行
两种方法运行:1,写一个主类, public static void main(String [] args)中初始化游戏类,然后运行游戏,2,写一个public类 里面添加代码块 static{ try{初始化游戏类;...; System.exit(1)} catch(Exception ex){ System.out.println("程序因为"+ex.getMessage()+"退出。");System.exit(1...

用JAVA编一个小的贪吃蛇游戏 (要求如下) 求JAVA高手
weix=(int)(food[shu]*0.1)*60;weiy=(int)(food[shu]%10)*40;repaint(); \/\/重绘下一个食物 add(snake[shu]); \/\/增加蛇节数和位置 snake[shu].setBounds(snake[shu-1].getBounds());} thread.sleep(100); \/\/睡眠100ms } catch(Exception e){} } else if(fangxiang==1)\/\/向左...

关于Java 中,我们的作业是一个 机战的小游戏,怎么去实现一个 子弹击中...
if(B.RightX >= A.LeftX)游戏循环中不断进行这样的检测,一旦检测到碰撞成立时就认为是击中了。进一步,并不是每个图形都是规则的矩形或者圆形,这个时候,你就要为图形自己定义一个碰撞检测图形(比如一个合适大小的圆形,大小刚好可以包裹你的对象)这个形状的坐标与对象运动关联,同步改变。通过这个...

用JAVA编一个小游戏或者其他程序
要用JAVA做一个小项目,类别不限,随便什么程序都行,不用太复杂。最好有注释。谢谢。这个有点太简单了。毕竟是一个小项目啊。谁发个有图形界面的?有没有可玩性强一点的,类似贪吃蛇... 要用JAVA做一个小项目,类别不限,随便什么程序都行,不用太复杂。最好有注释。谢谢。这个有点太简单了。毕竟是一个小项目...

谁帮我做个JAVA小游戏代码
第一个类,服务器主线程类。package src;\/\/定义一个包,存放JAVA文件。import java.io.*;\/\/导入JAVA包,输入输出流包 import java.net.*;\/\/导入JAVA包,网络应用包 public class SocketServer extends Thread {\/\/服务器主线程,负责为每个发出请求连接的客户端分配一个服务线程。ServerSocket server;\/...

求大神给一份JAVA小游戏,贪吃蛇或者俄罗斯方块源代码。my eclipse能直接...
import javax.swing.*;import java.awt.*;import java.awt.event.*;class Game extends JFrame implements KeyListener,Runnable { Thread Down10 = new Thread(this);GameCanvas test = new GameCanvas();JLabel LabelTetris = new JLabel("Tetris Game");JLabel ScorePrint1 = new JLabel("...

福田区15210844035: JAVA程序设计帮我设计一个JAVA程序:(猜字游戏)编写一个小游戏,游戏规则如下:随机产生4个不同的0—9之间的整数,然后让用户依次输入4个不同... -
达奚定舒胸:[答案] 这个不就是逻辑推数字嘛 用两个累加器就OK了 第一步 用Random类生成四个不重复的随机数 存起来作为最终答案 第二步 定义两个累加器 一个用来算A的个数,一个用来算B的个数 第三步 做好前台界面等待用户输入四个数 做四个TextBox和一个按...

福田区15210844035: 求一个简单又有趣的JAVA小游戏代码 -
达奚定舒胸: 那你就自己做个猜数字好了 import java.util.*; import java.io.*; public class CaiShu{ public static void main(String[] args) throws IOException{ Random a=new Random(); int num=a.nextInt(100); System.out.println("请输入一个100以内的整数:")...

福田区15210844035: 用java编写一个程序,可以是小游戏也可以是其他的 -
达奚定舒胸: public class Test { public static void main(String[] args) { System.out.println("Hello World!"); }}

福田区15210844035: 用JAVA编写一个小程序~~不限类型~~好玩点的哈 -
达奚定舒胸: 控制台小游戏 class YZDEL {public static void main(String[] args){java.util.Random Shiji = new java.util.Random();java.util.Scanner Shuru = new java.util.Scanner(System.in);java.util.Scanner Nandu = new java.util.Scanner(System.in);int ...

福田区15210844035: Java程序写一个小游戏 -
达奚定舒胸: 前天写的猜数字游戏,yong i控制猜测次数,有详细解析,用黑窗口可以直接运行,我试验过了,没问题 import javax.swing.Icon;import javax.swing.JOptionPane;public class CaiShuZi4JOptionPane { /** * @param args */ public static void main(...

福田区15210844035: JAVA小游戏程序代码 -
达奚定舒胸: 这个是比较有名的那个烟花,不知道你有没有用: 建个工程,以Fireworks为类即可 import java.awt.*; import java.applet.*; import java.awt.event.*; import javax.swing.*;public class Fireworks extends Applet implements MouseListener,Runnable ...

福田区15210844035: 用JAVA语言编写一个“猜数字游戏”的程序 -
达奚定舒胸: package test;import java.util.Scanner;public class Test param args */ public static void main(String[] args) { int b = (int) (Math.random()*10...

福田区15210844035: 有谁能提供一些小游戏的程序???java或java script...
达奚定舒胸: /* * @author qingsongwang * * * 猜数字 */ package 大溶合; import java.io.*; import java.io.BufferedWriter; public class GuessNumber { public void show() { DataInputStream stdin = new DataInputStream(System.in); BufferedInputStream buffin = ...

福田区15210844035: java编程一个程序 -
达奚定舒胸: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Random; public class GuessNumber { public static void main(String[] args) { // 新建一个随机数产生器,然后生成一个0到99之间的整数 ...

福田区15210844035: java编程:编写一个玩猜数的游戏. -
达奚定舒胸: 源代码 看看 给你个思路 import javax.swing.joptionpane;public class t {public static void main(string[] args) {system.out.print("给你一个1~100之间的整数,你猜:");int daan = (int) (math.random() * 100) + 1;int shuru = 0; string xianshi =...

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 星空见康网