本文目录一览:
- 1、求一个简单RPG游戏的代码,JAva编写的
- 2、求一个简单又有趣的JAVA小游戏代码
- 3、怎么用JAVA来写一个小游戏程序
- 4、用java编写一个猜拳游戏
- 5、用JAVA做一个剪刀,石头,布的人机猜拳游戏。
- 6、跪求JAVA编写的小游戏源代码
- 7、用JAVA编一个小游戏或者其他程序
- 8、用JAVA编写一个小程序,不限类型好玩点的。
- 9、求一个java小游戏 不要很难的 用MyEclipse
求一个简单RPG游戏的代码,JAva编写的
package com.lxi;import java.io.BufferedReader;import java.io.InputStreamReader;public class Rpg { @SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { System.out.println("在这里输入两个人物进行PK,以英文逗号分隔: [BM,DH,MK]"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Class
package com.lxi;import java.util.Random;class BM extends Person { public BM() { val = 650; coldTime = 1.5; fight = 40; chanceHit = 3; chanceDefense = 3; waitTime = 0; } int count = 0; //防御技能发动的次数 int temp = 40; //攻击力,值同fight boolean hitFlag = false; boolean defenseFlag = false; Random rand = new Random(); public void hit(Person p) { if (rand.nextInt(10) < chanceHit) { fight = fight * 2; //发动双倍攻击 hitFlag = true; } int hurt = p.defense(this); p.val = p.val - hurt; fight = temp; //还原为单倍攻击 if (p.val <= 0) { System.out.println(this.getClass().getSimpleName() + "胜出!"); System.exit(0); } System.out.println(this.getClass().getSimpleName() + "攻击" + p.getClass().getSimpleName() + "," + this.getClass().getSimpleName() + (this.hitFlag ? "发动攻击技能 " : "未发动攻击技能 ") + p.getClass().getSimpleName() + (this.defenseFlag ? "发动防御技能 " : "未发动防御技能 ") + this.getClass().getSimpleName() + ":" + this.val + "," + p.getClass().getSimpleName() + ":" + p.val); hitFlag = false; defenseFlag = false; } public int defense(Person p) { if (rand.nextInt(10) < chanceDefense) { if (count != 0) { p.val = p.val - p.fight; count++; defenseFlag = true; if (p.val <= 0) { System.out.println(this.getClass().getSimpleName() + "胜出!"); System.exit(0); } } } return p.fight; }} class MK extends Person { public MK() { val = 700; coldTime = 2.5; fight = 50; chanceDefense = 6; chanceHit = 3; waitTime = 0; } boolean hitFlag = false; boolean defenseFlag = false; Random rand = new Random(); public void hit(Person p) { if (rand.nextInt(10) < chanceHit) { p.waitTime = 3; //使对方晕眩3s hitFlag = true; } int hurt = p.defense(this); p.val = p.val - hurt; if (p.val <= 0) { System.out.println(this.getClass().getSimpleName() + "胜出!"); System.exit(0); } System.out.println(this.getClass().getSimpleName() + "攻击" + p.getClass().getSimpleName() + "," + this.getClass().getSimpleName() + (this.hitFlag ? "发动攻击技能 " : "未发动攻击技能 ") + p.getClass().getSimpleName() + (this.defenseFlag ? "发动防御技能 " : "未发动防御技能 ") + this.getClass().getSimpleName() + ":" + this.val + "," + p.getClass().getSimpleName() + ":" + p.val); hitFlag = false; defenseFlag = false; } public int defense(Person p) { if (rand.nextInt(10) < chanceDefense) { defenseFlag = true; return p.fight / 2; //防御技能发动,伤害减半 } return p.fight; }}
package com.lxi; import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.Random; //三个人物的基类abstract class Person { int val; //生命值 double coldTime; //冷却时间 int waitTime; //晕眩时间 int fight; //攻击力 int chanceHit; //发起主动技能的概率 int chanceDefense; //发起防御技能的概率 abstract void hit(Person p); //攻击技能 abstract int defense(Person p); //防御技能,返回被伤害点数} class DH extends Person { public DH() { val = 600; coldTime = 1.0; fight = 30; chanceHit = 3; //表示30%的概率 chanceDefense = 3; waitTime = 0; } Random rand = new Random(); boolean hitFlag = false; //主动技能发动的标识 boolean defenseFlag = false; //防御技能发动的标识 public void hit(Person p) { if (rand.nextInt(10) < chanceHit) { //发动主动技能 int hurt = p.defense(this); p.val = p.val - hurt; if (p.val <= 0) { System.out.println(this.getClass().getSimpleName() + "胜出!"); System.exit(0); } val = val + hurt; if (val > 600) val = 600; hitFlag = true; //标记主动技能已经发动 } else { //进行普通攻击 int hurt = p.defense(this); p.val = p.val - hurt; if (p.val <= 0) { System.out.println(this.getClass().getSimpleName() + "胜出!"); System.exit(0); } } System.out.println(this.getClass().getSimpleName() + "攻击" + p.getClass().getSimpleName() + "," + this.getClass().getSimpleName() + (this.hitFlag ? "发动攻击技能 " : "未发动攻击技能 ") + p.getClass().getSimpleName() + (this.defenseFlag ? "发动防御技能 " : "未发动防御技能 ") + this.getClass().getSimpleName() + ":" + this.val + "," + p.getClass().getSimpleName() + ":" + p.val); hitFlag = false; // defenseFlag = false; //重置标记,下次重用 } public int defense(Person p) { if (rand.nextInt(10) < chanceDefense) { defenseFlag = true; //标记防御技能已经发动 return 0; } else { return p.fight; } }}
求一个简单又有趣的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以内的整数:");
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
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;}
}
}
}
import java.util.Scanner;
import java.util.Random;
public class Fangfa{
static int sum,sum1=0;
public static void main(String [] args){
int a=1,b=1,c=1;
int k=0,m=1;
int money =5000;
int zhu =0;
boolean flag = true;
Random rand = new Random();
Scanner input = new Scanner(System.in);
while(m==1){
while(flag){
System.out.println("掷色子开始!");
System.out.println("请下注 注:下注金额只能是50的倍数且不能超过1000");
zhu=input.nextInt();
if(zhu%50==0&&zhu<=1000&&zhu<=money){
System.out.println("下注成功");
System.out.println("买大请输入数字1,买小输入数字2");
k=input.nextInt();
a= rand.nextInt(6)+1;
b= rand.nextInt(6)+1;
c= rand.nextInt(6)+1;
sum=a+b+c;
if(k==1){
if(sum>9){
money+=zhu;
System.out.println("恭喜您猜对了,骰子点数为"+sum+"结果是大"+"余额为"+money);
}else{
money-=zhu;
System.out.println("很遗憾,骰子点数为"+sum+"结果是小"+"余额为"+money);
}
}
if(k==2){
if(sum<=9){
money+=zhu;
System.out.println("恭喜您猜对了,骰子点数为"+sum+"结果是小"+"余额为"+money);
}else{
money-=zhu;
System.out.println("很遗憾,骰子点数为"+sum+"结果是大"+"余额为"+money);
}
}
flag= false;
System.out.println("继续请按1,退出请按任意键");
m=input.nextInt();
if(m==1){
flag=true;
System.out.println("您选择的是继续");
}else{
flag=false;
System.out.println("欢迎您下次再来玩");
}
}else{
System.out.println("下注失败"+"余额为"+money);
}
}
}
}
}
连连看的小源码
package Lianliankan;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class lianliankan implements ActionListener
{
JFrame mainFrame; //主面板
Container thisContainer;
JPanel centerPanel,southPanel,northPanel; //子面板
JButton diamondsButton[][] = new JButton[6][5];//游戏按钮数组
JButton exitButton,resetButton,newlyButton; //退出,重列,重新开始按钮
JLabel fractionLable=new JLabel("0"); //分数标签
JButton firstButton,secondButton; //分别记录两次被选中的按钮
int grid[][] = new int[8][7];//储存游戏按钮位置
static boolean pressInformation=false; //判断是否有按钮被选中
int x0=0,y0=0,x=0,y=0,fristMsg=0,secondMsg=0,validateLV; //游戏按钮的位置坐标
int i,j,k,n;//消除方法控制
public void init(){
mainFrame=new JFrame("JKJ连连看");
thisContainer = mainFrame.getContentPane();
thisContainer.setLayout(new BorderLayout());
centerPanel=new JPanel();
southPanel=new JPanel();
northPanel=new JPanel();
thisContainer.add(centerPanel,"Center");
thisContainer.add(southPanel,"South");
thisContainer.add(northPanel,"North");
centerPanel.setLayout(new GridLayout(6,5));
for(int cols = 0;cols < 6;cols++){
for(int rows = 0;rows < 5;rows++ ){
diamondsButton[cols][rows]=new JButton(String.valueOf(grid[cols+1][rows+1]));
diamondsButton[cols][rows].addActionListener(this);
centerPanel.add(diamondsButton[cols][rows]);
}
}
exitButton=new JButton("退出");
exitButton.addActionListener(this);
resetButton=new JButton("重列");
resetButton.addActionListener(this);
newlyButton=new JButton("再来一局");
newlyButton.addActionListener(this);
southPanel.add(exitButton);
southPanel.add(resetButton);
southPanel.add(newlyButton);
fractionLable.setText(String.valueOf(Integer.parseInt(fractionLable.getText())));
northPanel.add(fractionLable);
mainFrame.setBounds(280,100,500,450);
mainFrame.setVisible(true);
}
public void randomBuild() {
int randoms,cols,rows;
for(int twins=1;twins<=15;twins++) {
randoms=(int)(Math.random()*25+1);
for(int alike=1;alike<=2;alike++) {
cols=(int)(Math.random()*6+1);
rows=(int)(Math.random()*5+1);
while(grid[cols][rows]!=0) {
cols=(int)(Math.random()*6+1);
rows=(int)(Math.random()*5+1);
}
this.grid[cols][rows]=randoms;
}
}
}
public void fraction(){
fractionLable.setText(String.valueOf(Integer.parseInt(fractionLable.getText())+100));
}
public void reload() {
int save[] = new int[30];
int n=0,cols,rows;
int grid[][]= new int[8][7];
for(int i=0;i<=6;i++) {
for(int j=0;j<=5;j++) {
if(this.grid[i][j]!=0) {
save[n]=this.grid[i][j];
n++;
}
}
}
n=n-1;
this.grid=grid;
while(n>=0) {
cols=(int)(Math.random()*6+1);
rows=(int)(Math.random()*5+1);
while(grid[cols][rows]!=0) {
cols=(int)(Math.random()*6+1);
rows=(int)(Math.random()*5+1);
}
this.grid[cols][rows]=save[n];
n--;
}
mainFrame.setVisible(false);
pressInformation=false; //这里一定要将按钮点击信息归为初始
init();
for(int i = 0;i < 6;i++){
for(int j = 0;j < 5;j++ ){
if(grid[i+1][j+1]==0)
diamondsButton[i][j].setVisible(false);
}
}
}
public void estimateEven(int placeX,int placeY,JButton bz) {
if(pressInformation==false) {
x=placeX;
y=placeY;
secondMsg=grid[x][y];
secondButton=bz;
pressInformation=true;
}
else {
x0=x;
y0=y;
fristMsg=secondMsg;
firstButton=secondButton;
x=placeX;
y=placeY;
secondMsg=grid[x][y];
secondButton=bz;
if(fristMsg==secondMsg && secondButton!=firstButton){
xiao();
}
}
}
public void xiao() { //相同的情况下能不能消去。仔细分析,不一条条注释
if((x0==x &&(y0==y+1||y0==y-1)) || ((x0==x+1||x0==x-1)&&(y0==y))){ //判断是否相邻
remove();
}
else{
for (j=0;j<7;j++ ) {
if (grid[x0][j]==0){ //判断第一个按钮同行哪个按钮为空
if (y>j) { //如果第二个按钮的Y坐标大于空按钮的Y坐标说明第一按钮在第二按钮左边
for (i=y-1;i>=j;i-- ){ //判断第二按钮左侧直到第一按钮中间有没有按钮
if (grid[x][i]!=0) {
k=0;
break;
}
else{ k=1; } //K=1说明通过了第一次验证
}
if (k==1) {
linePassOne();
}
}
if (y
if (grid[x][i]!=0){
k=0;
break;
}
else { k=1; }
}
if (k==1){
linePassOne();
}
}
if (y==j ) {
linePassOne();
}
}
if (k==2) {
if (x0==x) {
remove();
}
if (x0
if (grid[n][j]!=0) {
k=0;
break;
}
if(grid[n][j]==0 && n==x-1) {
remove();
}
}
}
if (x0>x) {
for (n=x0;n>=x+1 ;n-- ) {
if (grid[n][j]!=0) {
k=0;
break;
}
if(grid[n][j]==0 && n==x+1) {
remove();
}
}
}
}
}
for (i=0;i<8;i++ ) { //列
if (grid[i][y0]==0) {
if (x>i) {
for (j=x-1;j>=i ;j-- ) {
if (grid[j][y]!=0) {
k=0;
break;
}
else { k=1; }
}
if (k==1) {
rowPassOne();
}
}
if (xfor (j=x+1;j<=i;j++ ) {
if (grid[j][y]!=0) {
k=0;
break;
}
else { k=1; }
}
if (k==1) {
rowPassOne();
}
}
if (x==i) {
rowPassOne();
}
}
if (k==2){
if (y0==y) {
remove();
}
if (y0
if (grid[i][n]!=0) {
k=0;
break;
}
if(grid[i][n]==0 && n==y-1) {
remove();
}
}
}
if (y0>y) {
for (n=y0;n>=y+1 ;n--) {
if (grid[i][n]!=0) {
k=0;
break;
}
if(grid[i][n]==0 && n==y+1) {
remove();
}
}
}
}
}
}
}
public void linePassOne(){
if (y0>j){ //第一按钮同行空按钮在左边
for (i=y0-1;i>=j ;i-- ){ //判断第一按钮同左侧空按钮之间有没按钮
if (grid[x0][i]!=0) {
k=0;
break;
}
else { k=2; } //K=2说明通过了第二次验证
}
}
if (y0
if (grid[x0][i]!=0) {
k=0;
break;
}
else{ k=2; }
}
}
}
public void rowPassOne(){
if (x0>i) {
for (j=x0-1;j>=i ;j-- ) {
if (grid[j][y0]!=0) {
k=0;
break;
}
else { k=2; }
}
}
if (x0for (j=x0+1;j<=i ;j++ ) {
if (grid[j][y0]!=0) {
k=0;
break;
}
else { k=2; }
}
}
}
public void remove(){
firstButton.setVisible(false);
secondButton.setVisible(false);
fraction();
pressInformation=false;
k=0;
grid[x0][y0]=0;
grid[x][y]=0;
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==newlyButton){
int grid[][] = new int[8][7];
this.grid = grid;
randomBuild();
mainFrame.setVisible(false);
pressInformation=false;
init();
}
if(e.getSource()==exitButton)
System.exit(0);
if(e.getSource()==resetButton)
reload();
for(int cols = 0;cols < 6;cols++){
for(int rows = 0;rows < 5;rows++ ){
if(e.getSource()==diamondsButton[cols][rows])
estimateEven(cols+1,rows+1,diamondsButton[cols][rows]);
}
}
}
public static void main(String[] args) {
lianliankan llk = new lianliankan();
llk.randomBuild();
llk.init();
}
}
//old 998 lines
//new 318 lines
停留在HelloWorld的水平
这个就比较难了 你还是你弄弄数组或者list各种排序问题,比较一下效率(可以数据量大点)或者比如 输入两数字 比较大小 然后计算两数字之间的偶数和之类的吧
具体如下:
连连看的小源码
package Lianliankan;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class lianliankan implements ActionListener
{
JFrame mainFrame; //主面板
Container thisContainer;
JPanel centerPanel,southPanel,northPanel; //子面板
JButton diamondsButton[][] = new JButton[6][5];//游戏按钮数组
JButton exitButton,resetButton,newlyButton; //退出,重列,重新开始按钮
JLabel fractionLable=new JLabel("0"); //分数标签
JButton firstButton,secondButton; //
分别记录两次62616964757a686964616fe59b9ee7ad9431333335326239被选中的按钮
int grid[][] = new int[8][7];//储存游戏按钮位置
static boolean pressInformation=false; //判断是否有按钮被选中
int x0=0,y0=0,x=0,y=0,fristMsg=0,secondMsg=0,validateLV; //游戏按钮的位置坐标
int i,j,k,n;//消除方法控制
代码(code)是程序员用开发工具所支持的语言写出来的源文件,是一组由字符、符号或信号码元以离散形式表示信息的明确的规则体系。
对于字符和Unicode数据的位模式的定义,此模式代表特定字母、数字或符号(例如 0x20 代表一个空格,而 0x74 代表字符“t”)。一些数据类型每个字符使用一个字节;每个字节可以具有 256 个不同的位模式中的一个模式。
在计算机中,字符由不同的位模式(ON 或 OFF)表示。每个字节有 8 位,这 8 位可以有 256 种不同的 ON 和 OFF 组合模式。对于使用 1 个字节存储每个字符的程序,通过给每个位模式指派字符可表示最多 256 个不同的字符。2 个字节有 16 位,这 16 位可以有 65,536 种唯一的 ON 和 OFF 组合模式。使用 2 个字节表示每个字符的程序可表示最多 65,536 个字符。
单字节代码页是字符定义,这些字符映射到每个字节可能有的 256 种位模式中的每一种。代码页定义大小写字符、数字、符号以及 !、@、#、% 等特殊字符的位模式。每种欧洲语言(如德语和西班牙语)都有各自的单字节代码页。
虽然用于表示 A 到 Z 拉丁字母表字符的位模式在所有的代码页中都相同,但用于表示重音字符(如"é"和"á")的位模式在不同的代码页中却不同。如果在运行不同代码页的计算机间交换数据,必须将所有字符数据由发送计算机的代码页转换为接收计算机的代码页。如果源数据中的扩展字符在接收计算机的代码页中未定义,那么数据将丢失。
如果某个数据库为来自许多不同国家的客户端提供服务,则很难为该数据库选择这样一种代码页,使其包括所有客户端计算机所需的全部扩展字符。而且,在代码页间不停地转换需要花费大量的处理时间。
怎么用JAVA来写一个小游戏程序
JAVA来写小程序做游戏很简单的了,你也可以参照书上如果有些小案列的话,那就更容易了。
首先你应该要具备编程的基础知识水平,利用Elicpse等软件来写代码,既而来实现相应的功能,也可以用VC++等来实现图形化界面设计呢。
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
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;}
}
} }
用java编写一个猜拳游戏
我之前写了个猜拳游戏的源代码,不过没你想的这么精彩。你才给5分就给你你自己修改了,应该很简单的。要多给点分我可以帮你修改。
import java.util.Scanner;
import java.util.Random;
public class caiquan
{
final int jiandao=0;
final int shitou=1;
final int bu=2;
public static void main(String[] args)
{
String yn="y";
while (yn.equals("y"))
{
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎玩猜拳游戏。请输入0,1,2:0表示剪刀,1表示石头,2表示布");
int a = scanner.nextInt();
Random rd = new Random();
int b = rd.nextInt(3);
switch (b)
{
case 0:
{
System.out.println("系统出的是剪刀");
switch(a)
{
case 0:System.out.println("平");break;
case 1:System.out.println("赢");break;
case 2:System.out.println("输");break;
}
}
break;
case 1:
{
System.out.println("系统出的是石头");
switch(a)
{
case 0:System.out.println("输");break;
case 1:System.out.println("平");break;
case 2:System.out.println("赢");break;
}
}
break;
case 2:
{
System.out.println("系统出的是布");
switch(a)
{
case 0:System.out.println("赢");break;
case 1:System.out.println("输");break;
case 2:System.out.println("平");break;
}
}
}
Scanner ynn = new Scanner(System.in);
System.out.println("是否继续?是请输入y,否则输入n。");
yn=ynn.next();
}
}
}
import java.util.Scanner;abstract class Computer{ abstract void playGame();}public class Game extends Computer { public static void main(String[] args) { new Game().playGame(); } static Scanner sc = new Scanner(System.in); static String[] games = {"猜拳游戏"}; static String[] roles = {"刘备", "孙权", "曹操"}; static final String[] MORA = {"石头", "剪刀", "布"}; static int playCount = 0; static String currentRole = ""; @Override void playGame() { doMoragame(); } public void doMoragame(){ System.out.println("- - 欢迎进入游戏世界 - -"); System.out.println("** ******************"); System.out.println("** 猜拳,开始 **"); System.out.println("** ******************"); System.out.println("出拳规则:1.剪刀 2.石头 3.布"); String startMsg = "请选择角色:"; for (int i = 0; i < roles.length; i++) { startMsg += (i + 1) + "." + roles[i]; } System.out.println(startMsg); String input = sc.nextLine(); currentRole = roles[selectRole(input)]; System.out.println("要开始吗?(y/n"); String isStart = sc.nextLine(); if ("y".equals(isStart)) { gameStart(); } else { System.out.println("结束"); sc.close(); return; } } int selectRole(String input){ int index = 0; switch (input) { case "1": index = 0; break; case "2": index = 1; break; case "3": index = 2; break; default: break; } return index; } void gameStart(){ playCount ++; System.out.println("请出拳:1.石头 2.剪刀 3.布"); String input = sc.nextLine(); try{ int index = Integer.valueOf(input); System.out.println("你出拳:" + MORA[index - 1]); int computerIndex = (int)Math.ceil(Math.random() * 3); System.out.println("电脑出拳:" + MORA[computerIndex - 1]); System.out.println(currentRole + "VS电脑"); System.out.println("对战次数:" + playCount); if (index == computerIndex) { System.out.println("结果:和局,真衰!嘿嘿,等着瞧吧!"); } else if (computerIndex == 0 && index == 1) { System.out.println("结果:你输了"); } else if (computerIndex == 1 && index == 2) { System.out.println("结果:你输了"); } else if (computerIndex == 2 && index == 0) { System.out.println("结果:你输了"); } else { System.out.println("结果:你赢了"); } } catch (Exception e){ e.printStackTrace(); System.err.println("输入异常参数!!!"); } finally{ System.out.println("是否开始下一轮(y/n)"); String finalInput = sc.nextLine(); if ("y".equals(finalInput)) { gameStart(); } else { System.out.println("结束"); sc.close(); return; } } } }
我之前写了个猜拳游戏的源代码,不过没你想的这么精彩。你才给5分就给你你自己修改了,应该很简单的。要多给点分我可以帮你修改。
import java.util.Scanner;
import java.util.Random;
public class caiquan
{
final int jiandao=0;
final int shitou=1;
final int bu=2;
public static void main(String[] args)
{
String yn="y";
while (yn.equals("y"))
{
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎玩猜拳游戏。请输入0,1,2:0表示剪刀,1表示石头,2表示布");
int a = scanner.nextInt();
Random rd = new Random();
int b = rd.nextInt(3);
switch (b)
{
case 0:
{
System.out.println("系统出的是剪刀");
switch(a)
{
case 0:System.out.println("平");break;
case 1:System.out.println("赢");break;
case 2:System.out.println("输");break;
}
}
break;
case 1:
{
System.out.println("系统出的是石头");
switch(a)
{
case 0:System.out.println("输");break;
case 1:System.out.println("平");break;
case 2:System.out.println("赢");break;
}
}
break;
case 2:
{
System.out.println("系统出的是布");
switch(a)
{
case 0:System.out.println("赢");break;
case 1:System.out.println("输");break;
case 2:System.out.println("平");break;
}
}
}
Scanner ynn = new Scanner(System.in);
System.out.println("是否继续看是请输入y,否则输入n。");
yn=ynn.next();
}
}
}
老哥,这个程序好歹几十块钱,你就给10个金币 - -
import java.util.Scanner;public class Game { private Scanner scan = new Scanner(System.in); private String rule[] = {"","剪刀","石头","布"}; private String role[] = {"","刘备","孙权","曹操"}; private Computer computer; private User user; private int roundCount; private Game(){ roundCount = 0; } public static void main(String[] args) { Game game = new Game(); game.start(); } public void start(){ computer = new Computer(); System.out.println("- - 欢迎进入游戏世界 - -"); System.out.println("** ******************"); System.out.println("** 猜拳,开始 **"); System.out.println("** ******************"); System.out.println(); System.out.println("出拳规则:1.剪刀 2.石头 3.布"); System.out.print("请选择角色(1:刘备 2.孙权 3.曹操)"); int userRole = scan.nextInt(); if(userRole >=1 && userRole <=3){ user = new User(role[userRole]); System.out.println(); System.out.print("要开始吗?(y/n) "); String start = scan.next(); if(start.equals("y")){ round(); } else if(start.equals("n")){ } } } private void round(){ roundCount ++; System.out.println(); System.out.print("请出拳:1.剪刀 2.石头 3.布 (输入相应数字): "); int userRule = user.round(); if(userRule >= 1 && userRule <= 3){ int computerRule = computer.round(); judge(userRule,computerRule); System.out.println(); System.out.print("是否开始下一轮(y/n): "); String next = scan.next(); if(next.equals("y")){ round(); } else if(next.equals("n")){ end(); } } } private void judge(int ur,int cr){ System.out.println("你出拳:"+ rule[ur]); System.out.println("电脑出拳:"+ rule[cr]); if(ur == cr){ System.out.println("结果:和局,真衰!嘿嘿,等着瞧吧!"); } else if((ur == 1 && cr== 3)|| (ur == 2 && cr == 1)|| (ur == 3 && cr == 2)){ System.out.println("结果:你赢了!"); user.win(); } else{ System.out.println("结果:你输了!"); computer.win(); } } private void end(){ System.out.println("- -------------------------------------"); System.out.println(user.getName() + "VS" + computer.getName()); System.out.println("对战次数:" + roundCount); if(computer.getWin() == user.getWin()){ System.out.println("结果:打成平手,下次再和你一分高下!"); } else if(computer.getWin() > user.getWin()){ System.out.println("结果:你输了!电脑赢了" + computer.getWin()+"次!"); } else{ System.out.println("结果:你赢了!你赢了" + user.getWin()+"次!"); } System.out.println("- -------------------------------------"); } class Computer{ private int win; private String name; public Computer(){ win = 0; name = "匿名"; } public int round(){ return (int)(System.currentTimeMillis() % 3) + 1;//随机返回1、2、3 } public String getName(){ return name; } public void win(){ win ++; } public int getWin(){ return win; } } class User{ private int win; private String name = ""; public User(String name){ this.name = name; win = 0; } public int round(){ return scan.nextInt(); } public String getName(){ return name; } public void win(){ win ++; } public int getWin(){ return win; } }}刚刚写好的,应该满足你的题目要求。赢了和输了的提示信息题目里没有是我自己随便写的。
用JAVA做一个剪刀,石头,布的人机猜拳游戏。
同意一楼的,为什么要高很多类呢?不就是个随机取数的问题么?
把楼下的int h = (int)(Math.random()*10); 改为*3
闲着没事,改了下,类分好了,随机数产生,修改了。望lz多思考。
import java.util.Scanner;
class Person {
int n = 0;
public int input() {
System.out.println("请输入:石头,剪刀,布");
Scanner sc = new Scanner(System.in);
String s = sc.next();
if(s.equals("石头")){
n = 1;
}else if(s.equals("剪刀")){
n = 2;
}else if(s.equals("布")){
n = 3;
}else if(s.equals("exit")){
System.out.print("系统退出了");
System.exit(0);
}
return n;
}
}
class Computer {
public int random() {
int h = (int)(Math.random()*3+1);
return h;
}
}
public class Game {
public void result(int n,int m){
if(n == m){
System.out.println("平了");
}else{
if(m==1){
if(n==2){
System.out.println("你输了");
}else if(n ==3){
System.out.println("你赢了");
}
}else if(m == 2) {
if(n == 1){
System.out.println("你赢了");
}else if(n ==3){
System.out.println("你输了");
}
}else if( m ==3 ){
if(n==1){
System.out.println("你输了");
}else if(n == 2){
System.out.println("你赢了");
}
}
}
}
public static void main(String[] args) {
while(true){
Person p = new Person();
Computer c = new Computer();
Game g = new Game();
g.result(p.input(), c.random());
}
}
}
太简单~
不过用得着吗?
这么个小功能 定义3个类~
疯了~~~~~~~~~~~~
不超过30行代码能解决的事情~
呵呵 BLUCASTLE 的应该是可以的
还有,楼主,他给你的答案是你想要的,你如果想学好
那就把他的代码试着自己简化到最简单的,执行效率最高的~
我非为分而来,哈哈,为了伟大的共享世界而来!~~~~~~~~~~~~
另外,他的随机是用API实现的,你可以自己实现一个随机的方法嘛~
哈哈~~~~~~~
使用时间作为随机源~~~~~~~~~~
还有这是两个人的人机对战,如果3个人,4个人呢~~~~~
哈哈~~~~~~~~
我太疯狂了~
编写这个小游戏 我们需要几个类
1、第一个 Person 类
import java.util.Scanner;
/**
* @copyright 2018 sugarsLab.com All rights reserved.
* @author jingfei.wu
* @date 2018年11月16日
* @version 1.0
* @ClassName Person
* @description 用户类 用来计算用户输入
*/
public class Person {
public static final Person me = new Person();
private int n = 0;
/**
* @copyright 2018 sugarsLab.com All rights reserved.
* @author jingfei.wu
* @date 2018年11月16日
* @version 1.0
* @description 用户输入的 指令
* @return
*/
public int input() {
System.out.println("请输入:石头,剪刀,布\n输入:@退出 退出系统");
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
// s 里面存着 用户输入的 指令 切记这里不要使用 s.equals() 而是写 "指令".equals() 这么写 是为了避免空指针
if ("石头".equals(s)) {
n = 1;
} else if ("剪刀".equals(s)) {
n = 2;
} else if ("布".equals(s)) {
n = 3;
} else if ("@退出".equals(s)) {
System.out.print("系统退出了");
System.exit(0);
}
return n;
}
}
2、Computer 类
/**
* @copyright 2018 sugarsLab.com All rights reserved.
* @author jingfei.wu
* @date 2018年11月16日
* @version 1.0
* @ClassName Computer
* @description 游戏中电脑类 用来产生随机数
*/
public class Computer {
public static final Computer me = new Computer();
/**
* @copyright 2018 sugarsLab.com All rights reserved.
* @author jingfei.wu
* @date 2018年11月16日
* @version 1.0
* @description TODO
* @return {int} 返回值为int 类型
*/
public int random() {return (int) (Math.random() * 3 + 1);}
}
3、Game类
/**
* @author jingfei.wu
* @date 2018年11月16日
* @version 1.0
* @ClassName Game
* @description 游戏类 用来计算游戏结果
*/
public class Game {
/**
* @author jingfei.wu
* @date 2018年11月16日
* @version 1.0
* @description 返回 人机交互结果
* @param n
* {int} 用户输入 的标识 石头 为 1 剪刀 为 2 布 为 3
* @param m
* {int} 电脑产生的随机数 石头 为 1 剪刀 为 2 布 为 3
*/
public void result(int n, Integer m) {
String res = "";
if (m.intValue() == 1)
res = "石头";
else if (m.intValue() == 2)
res = "剪刀";
else
res = "布";
if (n == m) {
System.out.println("平了 computer出" + res);
} else {
if (m == 1) {
if (n == 2)
System.out.println("你输了 computer出 " + res);
else if (n == 3)
System.out.println("你赢了 computer出 " + res);
} else if (m == 2) {
if (n == 1)
System.out.println("你赢了 computer出 " + res);
else if (n == 3)
System.out.println("你输了 computer出 " + res);
} else if (m == 3) {
if (n == 1)
System.out.println("你输了 computer出 " + res);
else if (n == 2)
System.out.println("你赢了 computer出 " + res);
}
}
}
public static void main(String[] args) {
while (true) {
Game gamer = new Game();
gamer.result(Person.me.input(), Computer.me.random());
}
}
}
如下是程序运行截图
跪求JAVA编写的小游戏源代码
labelHelp = new JLabel("PageUp, PageDown for speed;", JLabel.CENTER);
360.240
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; this.y=y;
}
Car(Image img, int x, int y, Dimension dim){
this(img, x, y);
this.dim=dim;
}
void draw(Graphics g, ImageObserver observer){
g.drawImage(img, x, y, observer);
}
int getX(){ return x;}
int getY(){ return y;}
void setX(int x){this.x=x;}
void setY(int y){this.y=y;}
void setLocation(int x, int y){
this.x=x; this.y=y;
}
int getWidth(){ return img.getWidth(null);}
int getHeight(){ return img.getHeight(null);}
Rectangle2D getRectangle(){
return new Rectangle2D.Float(x, y, getWidth(), getHeight());
}
void move(int dx, int dy){
x+=dx;
y+=dy;
if(dim!=null){
if(x<0)x=0;
if(x+getWidth()>dim.getWidth())
x=(int)dim.getWidth()-getWidth();
}
}
boolean intersects(Car car){
return getRectangle().intersects(car.getRectangle());
}
boolean intersects(int x, int y){
return getRectangle().intersects(x, y, getWidth(), getHeight());
}
}
public class CarRace extends Applet implements KeyListener, Runnable{
Image buff;
Canvas screen;
Graphics2D gs, gb;
Car redCar;
Car[] enemy=new Car[20];
Button bStart;
Thread game;
boolean loop=true;
Dimension dim=new Dimension(200, 300);
int road;
Random rnd=new Random();
public void init(){
prepareResource();
setBackground(Color.blue);
initScreen();
add(screen);
bStart=new Button("霸烙 矫累");
add(bStart);
bStart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
screen.requestFocus();
if(!game.isAlive())
game.start();
}
});
}
void prepareResource(){
Image imgRed=getImage(getCodeBase(),"images/red_car.gif");
Image imgBlue=getImage(getCodeBase(),"images/blue_car.gif");
Image imgGreen=getImage(getCodeBase(),"images/green_car.gif");
MediaTracker mt=new MediaTracker(this);
try{
mt.addImage(imgRed, 0);
mt.addImage(imgBlue, 1);
mt.addImage(imgGreen, 2);
mt.waitForAll();
}catch(Exception e){}
buff=createImage((int)dim.getWidth(), (int)dim.getHeight());
gb=(Graphics2D)buff.getGraphics();
redCar=new Car(imgRed, 80,250, dim);
for(int i=0;i<10;i++){
enemy[i]=new Car(imgBlue, 0, 0);
}
for(int i=10;i
}
for(int i=0;i
}
game=new Thread(this);
}
public void stop(){
loop=false;
}
public void run(){
while(loop){
drawScreen();
try{ Thread.sleep(50);}catch(Exception e){}
}
}
void initScreen(){
screen=new Canvas(){
public void paint(Graphics g){
if(gs==null){
gs=(Graphics2D)screen.getGraphics();
}
drawScreen();
}
};
screen.setSize(dim);
screen.addKeyListener(this);
}
void setEnemy(int en){
int x, y;
next:while(true){
x=rnd.nextInt((int)dim.getWidth()-enemy[en].getWidth());
y=-rnd.nextInt(5000)-200;
for(int j=0;j
}
enemy[en].setLocation(x, y);
break;
}
}
void check(Car en){
if(redCar.intersects(en)){
if(redCar.getX()>en.getX()){
en.move(-20, 0);
redCar.move(20, 0);
}
else{
en.move(20,0);
redCar.move(-20, 0);
}
}
}
synchronized void drawScreen(){
gb.clearRect(0, 0, (int)dim.getWidth(), (int)dim.getHeight());
gb.setPaint(new Color(100, 100, 100));
gb.fillRect(0, 0, (int)dim.getWidth(), (int)dim.getHeight());
drawRoad();
for(int i=0;i
enemy[i].draw(gb, screen);
if(enemy[i].getY()>dim.getHeight())
setEnemy(i);
check(enemy[i]);
}
redCar.draw(gb, screen);
gs.drawImage(buff, 0,0, screen);
}
void drawRoad(){
road+=80;
gb.setPaint(Color.yellow);
gb.fillRect((int)dim.getWidth()/2, road,10,150);
if(road>=dim.getHeight())road=-150;
}
public void keyPressed(KeyEvent ke){
if(ke.getKeyCode()==KeyEvent.VK_LEFT){
redCar.move(-10,0);
}
else if(ke.getKeyCode()==KeyEvent.VK_RIGHT){
redCar.move(10,0);
}
}
public void keyReleased(KeyEvent ke){}
public void keyTyped(KeyEvent ke){}
}
这个是一个典型的Applet,文件名应该是CarRace.java,需要图片作为车子等等,本人也是别人给的,但是还要个.html文件来运行它,代码为:
请楼主采纳
用JAVA编一个小游戏或者其他程序
下面是我大学时写的扫雷,希望对你有帮助:
/*
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
贪吃蛇程序:
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;
}
}
用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 YingxHP = 20;
int YingxMP = 0;
int MogHP = 20;
int MogMP = 0;
int MogDo = 0;
int fangyu = 0;
System.out.println("┏━━━━╮┏━━┣┣┓ ╮ ┓ ┏━┳━┳┓ ┓━┓ ");
System.out.println("┏┣━━━┓┏━━┣┣┓ ┃ ┏ ┃ ┃┓ ┃ ╯ ");
System.out.println("┣┣━━━┫╭━━┻╯ ╮ ┃ ╰┓┃ ┃╯┏━┣━━┓");
System.out.println("┣┣━━━┫┏━━━━┓╭━━┣━┛┗━┻━┻┛ ┃┃ ");
System.out.println("┏┣━━━┓┣━━━━┫ ┃ ┃┃┗╮╮┃ ┃┣━╯");
System.out.println(" ┛ ┗╯┗━━━━╯ ┗╯ ╰╰━━┛┛┗━╯╰━┛");
System.out.println();
System.out.println(" 作者:天狐空幻");
System.out.println();
System.out.println("说明:勇者的操作方式为以下所示:");
System.out.println(" 使用攻击需消耗1MP 伤害1HP");
System.out.println(" 使用蓄力可增加1MP 伤害0HP");
System.out.println(" 使用躲闪需消耗0MP 伤害0HP 躲避攻击");
System.out.println(" 使用重击需消耗3MP 伤害2HP 防御无效");
System.out.println(" 恶龙攻击力高, 注意防御是取胜的关键");
System.out.println(" 恶龙MP达到4时可能会放出火焰无法躲避");
System.out.println(" 准备说明完毕,那么让我们来挑战恶龙吧!");
System.out.println("==================================");
//难度选择
System.out.println("请选择难度");
System.out.println("1.娱乐 2.挑战 3.噩梦");
int ND = Nandu.nextInt();
System.out.println("==================================");
while(true)
{
//HP,MP的显示
System.out.print("勇者: ");
System.out.print(" HP ");
for(int x=YingxHP;x>0;x--) System.out.print("*");
System.out.print(" "+YingxHP);
System.out.println();
System.out.print(" ");
System.out.print(" MP ");
for(int x=YingxMP;x>0;x--) System.out.print("*");
System.out.print(" "+YingxMP);
System.out.println();
System.out.print("恶龙: ");
System.out.print(" HP ");
for(int y=MogHP;y>0;y--) System.out.print("*");
System.out.print(" "+MogHP);
System.out.println();
System.out.print(" ");
System.out.print(" MP ");
for(int y=MogMP;y>0;y--) System.out.print("*");
System.out.print(" "+MogMP);
System.out.println();
System.out.println("==================================");
//胜利判定
if(YingxHP<1) {System.out.println();System.out.println("勇者HP为0! 不..不可能..我怎么会..勇者倒下了。再接再厉吧!~");System.out.println();break;}
if(MogHP<1) {System.out.println();System.out.println("恶龙HP为0! 恶龙绝望的哀鸣中倒了下去。勇者胜利了。恭喜你挑战成功!!");System.out.println();break;}
//角色输入判定
System.out.println("你要做什么:");
System.out.println("1.攻击 2.蓄力");
System.out.println("3.躲闪 4.重击");
System.out.println("____________________");
int Do = Shuru.nextInt();
//敌人输入判定
//娱乐难度
if(ND==1){
for(int i=1;i<3;i++) MogDo = Shiji.nextInt(4);}
//挑战难度
if(ND==2){
if(YingxMP==0&&MogMP==0) {MogDo = 0;}
else if(MogMP==0){for(int i=1;i<3;i++) MogDo = Shiji.nextInt(2);}
else if(YingxMP>2&&MogMP>2) MogDo = 2;
else if(MogMP<4) {for(int i=1;i<4;i++) MogDo = Shiji.nextInt(3);}
else MogDo = 3;}
//噩梦难度
if(ND==3){
if(Do==1) MogDo=1;
if(Do==2&&MogMP>0) MogDo=2;
if(Do==2&&MogMP==0) MogDo=0;
if(Do==3&&MogMP<4) MogDo=0;
if(Do==3&&MogMP>=4) MogDo=3;}//变态判定。。
//战斗分析
//防御
if(Do==3) {fangyu=1;System.out.println("你灵巧的躲避攻击!");}
if(MogDo==1) {fangyu=1;System.out.println("恶龙进行防御!");}
//角色判定
if(Do==1&&YingxMP==0) {System.out.println("MP不足!");}
if(Do==1&&YingxMP>0) {
if(fangyu==0) {MogHP=MogHP-1;YingxMP=YingxMP-1;System.out.println("你发动攻击!");}
if(fangyu==1) {YingxMP=YingxMP-1;System.out.println("你的攻击被格挡!");}}
if(Do==2) {YingxMP=YingxMP+1;System.out.println("你进行蓄力!");}
if(Do==4&&YingxMP<3) {System.out.println("MP不足!");}
if(Do==4&&YingxMP>2) {MogHP=MogHP-2;YingxMP=YingxMP-3;System.out.println("你发动重击!");}
if(Do> 4) System.out.println("你不知所措...");
//敌人判定
if(MogDo==2&&MogMP==0) {System.out.println("恶龙在发呆!");}
if(MogDo==2&&MogMP>0) {
if(fangyu==0) {YingxHP=YingxHP-2;MogMP=MogMP-1;System.out.println("恶龙发动攻击!");}
if(fangyu==1) {MogMP=MogMP-1;System.out.println("恶龙的攻击被躲开了!");}}
if(MogDo==0) {MogMP=MogMP+1;System.out.println("恶龙进行蓄力!");}
if(MogDo==3&&MogMP<4) {System.out.println("恶龙在发呆!");}
if(MogDo==3&&MogMP>3) {YingxHP=YingxHP-4;MogMP=MogMP-4;System.out.println("恶龙发动火焰吐吸!躲避不能!");}
//结束
fangyu = 0;
MogDo = 0;
System.out.println("____________________");
System.out.println();
System.out.println("=================================="); }
}
}
求一个java小游戏 不要很难的 用MyEclipse
如果你能用C做出来,相信用Java就不是什么难题了,Java是面向对象的语言,将棋子看成对象,更容易理解和操作。。。通常用MyEclipse编写,也可用Eclipse,用Java,首先你要对这门语言进行属性吧。。。
你好:我自己写了一个,还算好玩吧,
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):\n","猜数字游戏",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 = 3;i > 0;i--){ //i是你可以猜测的次数 if(put==c){ JOptionPane.showMessageDialog(null, "恭喜你猜对了,正确答案是:"+c+"。"); //如果你猜对了就直接结束循环 break; }else if(put>c){ //如果输大了就让你再次从新输入 str1 = (String) JOptionPane.showInputDialog(null,"你的输入过大。你还有"+i+"次机会,请重新输入:\n","猜数字游戏",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