java小游戏源代码
java小游戏源代码
Java小游戏第一个Java文件:import java.util.Scanner;public class GameA_B {public static void main(String[] args) {Scanner reader=new Scanner(System.in);int area;System.out.println("Game Start…………Please enter the area:(1-9)"+ '\n'+"1,2,3 means easy"+'\n'+"4,5,6 means middle"+'\n'+"7,8,9 means hard"+'\n'+"Please choose:");a rea=reader.nextInt();s witch((area-1)/3){c ase 0:System.out.println("You choose easy! ");break;c ase 1:System.out.println("You choose middle! ");break;c ase 2:System.out.println("You choose hard! ");break;}S ystem.out.println("Good Luck!");G ameProcess game1=new GameProcess(area);game1.process();}}第二个Java文件:import java.util.Random;import java.util.Scanner;public class GameProcess {int area,i,arrcount,right,midright,t;int base[]=new int[arrcount],userNum[]=new int[area],sysNum[]=new int[area];Random random=new Random();Scanner reader=new Scanner(System.in);GameProcess(int a){area=a;arrcount=10;midright=0;t=0;base=new int[arrcount];userNum=new int[area];sysNum=new int[area];for(int i=0;i<arrcount;i++){base[i]=i;//System.out.println(base[i]);}}void process(){r and();w hile(right!=area){s canf();c ompare();p rint();c heck();}}void rand(){f or(i=0;i<area;i++){t=random.nextInt(arrcount);//System.out.println(t);sysNum[i]=base[t];System.out.println(base[t]);delarr(t);}}void delarr(int t){f or(int j=t;j<arrcount-1;j++)base[j]=base[j+1];a rrcount--;}void scanf(){S ystem.out.println("The system number has created!"+"\n"+"Please enter "+area+" Numbers");{userNum[i]=reader.nextShort();}}void check(){if(right==area)S ystem.out.println("You win…………!");}boolean check(int i){r eturn true;}void compare(){i nt i=0,j=0;r ight=midright=0;f or(i=0;i<area;i++){for(j=0;j<area;j++){if(userNum[i]==sysNum[j]){if(i==j)right++;elsemidright++;}}}}void print(){S ystem.out.println(" A "+right+" B "+midright); }}import java.awt.*;import java.awt.event.*;import javax.swing.*;class TestGame {public static void main(String[] args) {App ap = new App(); //调用App()开始运行程序ap.show();}}class App extends JFrame {MainPanel mp;public App() {mp = new MainPanel();this.getContentPane().add(mp);this.setSize(400, 450);this.setTitle("小游戏");}}/*** 主面板* 显示格子* @author Administrator**/class MainPanel extends JPanel {ButtonPanel bp = new ButtonPanel();CtrlPanel rp = new CtrlPanel();public MainPanel() {this.setLayout(new BorderLayout());rp.btnstart.addActionListener(new StartListener()); this.add(bp, "Center");this.add(rp, "South");class StartListener implements ActionListener {/*** 重新开始按钮的事件* 调用按钮面板里面的颜色初始化方法*/public void actionPerformed(ActionEvent e) {if (e.getActionCommand() == "重新开始") {bp.ColorInit();}}}}class ButtonPanel extends JPanel {JButton[][] b = new JButton[5][5];/*** 按钮界面的构造器* 设置布局方式为Grid布局,并生成5*5的格子,* 在每个格子生成一个按钮,* 为每个按钮添加一个监听事件*/public ButtonPanel() {this.setLayout(new GridLayout(5, 5));for (int i = 0; i < 5; i++) {for (int j = 0; j < 5; j++) {b[i][j] = new JButton();b[i][j].setActionCommand("" + (i + 1) + (j + 1));b[i][j].addActionListener(new MyButtonListener());this.add(b[i][j]);}}this.ColorInit();}* 面板初始化时候给所有的格子都绘上深灰色* i.j分别是行和列*/public void ColorInit() {for (int i = 0; i < 5; i++) {for (int j = 0; j < 5; j++) {b[i][j].setBackground(Color.DARK_GRAY);}}}/*** 按钮上监听的时事件,监听点击* @author Administrator**/class MyButtonListener implements ActionListener { int r, c;/*** 需要改变颜色的行和列* r row* c colunm* 调用change()来改变颜色*/public void actionPerformed(ActionEvent e) {int i = Integer.parseInt(e.getActionCommand()); r = i / 10 - 1;c = i % 10 - 1;this.changer();}/*** 传一个按钮控件进去* 判断颜色,如果是深灰则变为粉红* 否则义相反* @param b*/if (b.getBackground() == Color.DARK_GRAY) {b.setBackground(Color.pink);} else {b.setBackground(Color.DARK_GRAY);}}/*** 这个方法是根据点击的按钮判断周围需要* 不能超越数组的下标*/public void changer() {this.btnChange(b[r][c]);if (r > 0) //行号大于0this.btnChange(b[r - 1][c]);if (r < 4)this.btnChange(b[r + 1][c]);if (c > 0)//列号大于0this.btnChange(b[r][c - 1]);if (c < 4)//列好小余0this.btnChange(b[r][c + 1]);}}}/*** 控制面板* @author Administrator*下面的开始按钮*/class CtrlPanel extends JPanel {JButton btnstart;public CtrlPanel() {btnstart = new JButton("重新开始");this.add(btnstart);}}import java.util.*;public class Cai {enum Res{SHITOU, JIANZI, BU};Res res;public static void main(String[] args) throws Exception { // TODO Auto-generated method stubCai cai = new Cai();System.out.println("请输入你的选择:");System.out.println("0表示石头,1表示剪子,2表示布"); char yourResultOfChar =(char) System.in.read();int yourResultOfInt = yourResultOfChar - '0';int computerResult = pb();cai.getYourResult(yourResultOfInt);switch (computerResult){case 0:System.out.println("电脑选择石头");break;case 1:System.out.println("电脑选择剪子");break;case 2:System.out.println("电脑选择布");break;}cai.pa(computerResult);}public void getYourResult(int count){res = result[count];}void pa(int computer){Res[] result = Res.values();if(this.res == Res.SHITOU){System.out.println("我选择石头"); switch(result[computer]){case SHITOU:System.out.println("平局,再来!");break;case JIANZI:System.out.println("我赢了!");break;case BU:System.out.println("我输了!");break;}} else if(this.res == Res.JIANZI) {System.out.println("我选择剪子"); switch(result[computer]){case JIANZI:System.out.println("平局,再来!");break;case BU:System.out.println("我赢了!");break;case SHITOU:System.out.println("我输了!");break;}} else if(this.res == Res.BU){System.out.println("我选择布");switch(result[computer]){case BU:System.out.println("平局,再来!");break;case SHITOU:System.out.println("我赢了!");break;case JIANZI:System.out.println("我输了!");break;}}}static int pb(){Random ran = new Random();int res = ran.nextInt(3);return res;//输出0-2的整数,0表示石头,1表示剪子,2表示布,和enum Res中的顺序相对应}}import java.util.*; //导入实用包util下所有的类import javax.swing.*;import java.awt.*;import java.awt.event.*;public class CaiShu {public static void main(String[] args) {Win f = new Win();f.setVisible(true);}}class Win extends JFrame implements ActionListener {JLabel labe;JButton butt;JButton button;Random a = new Random();private int i = 0;private int num;JTextField text1, text2;JPanel p;public Win() {super("猜数游戏");labe = new JLabel("我心里有个数,它是1---100之间的,你能猜出来吗?"); butt = new JButton("确认");button = new JButton("重开");text1 = new JTextField(5);text2 = new JTextField(20);p = new JPanel();Container con = getContentPane();// 调用JFrame的getContentPane得到容器text2.setEditable(false);// 使输出结果文本域不可编辑butt.addActionListener(this);// 执行结果动作con.setLayout(new GridLayout(4, 1));// 设置整个界面的长宽比p.add(text1);// 添加输入数字文本域p.add(butt);p.add(button);button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { text1.setText("");text2.setText("");i=0;}});con.add(labe);// 添加游戏标签con.add(p);con.add(text2);// 添加输出结果信息文本域setSize(300, 300);// 设置窗口尺寸setVisible(true);// 设置窗口可视pack();addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { setVisible(false);System.exit(0);}});}public void actionPerformed(ActionEvent e) {int shu;while (true) {shu = Integer.parseInt(text1.getText());if (i == 0) {num = a.nextInt(100);}i++;if (i == 10) {text2.setText("结束吧,你没有希望了!!");i = 0;break;}if (e.getSource() == butt) {if (shu > num) {text2.setText("输入的数大了,输小点的!");} else if (shu < num) {text2.setText("输入的数小了,输大点的!");} else if (shu == num) {text2.setText("恭喜你,猜对了!");if (i <= 2)text2.setText("你真是个天才!");else if (i <= 6)text2.setText("还将就,你过关了!");else if (i <= 8)text2.setText("但是你还……真笨!");elsetext2.setText("你实在是太笨了!");}break;}}}}。
java斗地主游戏项目源码
java⽃地主游戏项⽬源码部分代码如下Main.javapackage com;import java.awt.Color;import java.awt.Container;import java.awt.Point;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.ArrayList;import java.util.List;import java.util.Random;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.JTextField;import javax.swing.SwingUtilities;public class Main extends JFrame implements ActionListener {public Container container = null;// 定义容器JMenuItem start, exit, about;// 定义菜单按钮JButton landlord[]=new JButton[2];//抢地主按钮JButton publishCard[]=new JButton[2];//出牌按钮int dizhuFlag;//地主标志int turn;JLabel dizhu; //地主图标List<Card> currentList[] =new ArrayList[3]; // 当前的出牌List<Card> playerList[] = new ArrayList[3]; // 定义3个玩家表List<Card> lordList;//地主牌Card card[] = new Card[56]; // 定义54张牌JTextField time[]=new JTextField[3]; //计时器Time t; //定时器(线程)boolean nextPlayer=false; //转换⾓⾊public Main(){Init();// 初始化SetMenu();// 创建菜单按钮(抢地主,发牌,计时器)this.setVisible(true);CardInit();//发牌getLord(); //发完牌开始抢地主time[1].setVisible(true);//线程安全性,把⾮主线程的UI控制放到⾥⾯SwingUtilities.invokeLater(new NewTimer(this,10));}// 抢地主public void getLord(){//System.out.println(CardType.c0.toString());for(int i=0;i<2;i++)landlord[i].setVisible(true);}//初始化牌// 发牌洗牌public void CardInit() {int count = 1;//初始化牌for (int i = 1; i <= 5; i++) {for (int j = 1; j <= 13; j++) {if ((i == 5) && (j > 2))break;else {card[count] = new Card(this, i + "-" + j, false);card[count].setLocation(350, 50);container.add(card[count]);count++;}}}//打乱顺序for(int i=0;i<100;i++){Random random=new Random();int a=random.nextInt(54)+1;int b=random.nextInt(54)+1;Card k=card[a];card[a]=card[b];card[b]=k;}//开始发牌for(int i=0;i<3;i++)playerList[i]=new ArrayList<Card>(); //玩家牌lordList=new ArrayList<Card>();//地主牌三张int t=0;for(int i=1;i<=54;i++){if(i>=52)//地主牌{Common.move(card[i], card[i].getLocation(),new Point(300+(i-52)*80,10)); lordList.add(card[i]);continue;}switch ((t++)%3) {case0://左边玩家Common.move(card[i], card[i].getLocation(),new Point(50,60+i*5));playerList[0].add(card[i]);break;case1://我Common.move(card[i], card[i].getLocation(),new Point(180+i*7,450));playerList[1].add(card[i]);card[i].turnFront(); //显⽰正⾯break;case2://右边玩家Common.move(card[i], card[i].getLocation(),new Point(700,60+i*5));playerList[2].add(card[i]);break;}//card[i].turnFront(); //显⽰正⾯container.setComponentZOrder(card[i], 0);}//发完牌排序,从⼤到⼩for(int i=0;i<3;i++){Common.order(playerList[i]);Common.rePosition(this,playerList[i],i);//重新定位}dizhu=new JLabel(new ImageIcon("images/dizhu.gif"));dizhu.setVisible(false);dizhu.setSize(40, 40);container.add(dizhu);}// 初始化窗体public void Init() {this.setTitle("java单机⽃地主");this.setSize(830, 620);setResizable(false);setLocationRelativeTo(getOwner()); // 屏幕居中container = this.getContentPane();container.setLayout(null);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);container.setBackground(new Color(0, 112, 26)); // 背景为绿⾊}// 创建菜单功能按钮public void SetMenu() {JMenuBar jMenuBar = new JMenuBar();JMenu game = new JMenu("游戏");JMenu help = new JMenu("帮助");start = new JMenuItem("新游戏");exit = new JMenuItem("退出");about = new JMenuItem("关于");start.addActionListener(this);exit.addActionListener(this);about.addActionListener(this);game.add(start);game.add(exit);help.add(about);jMenuBar.add(game);jMenuBar.add(help);this.setJMenuBar(jMenuBar);landlord[0]=new JButton("抢地主");landlord[1]=new JButton("不抢");publishCard[0]= new JButton("出牌");publishCard[1]= new JButton("不要");for(int i=0;i<2;i++){publishCard[i].setBounds(320+i*100, 400, 60, 20);landlord[i].setBounds(320+i*100, 400,75,20);container.add(landlord[i]);landlord[i].addActionListener(this);landlord[i].setVisible(false);container.add(publishCard[i]);publishCard[i].setVisible(false);publishCard[i].addActionListener(this);}for(int i=0;i<3;i++){time[i]=new JTextField("倒计时:");time[i].setVisible(false);container.add(time[i]);}time[0].setBounds(140, 230, 60, 20);time[1].setBounds(374, 360, 60, 20);time[2].setBounds(620, 230, 60, 20);for(int i=0;i<3;i++){currentList[i]=new ArrayList<Card>();}}@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubif (e.getSource() == exit) {this.dispose();}if (e.getSource() == about) {JOptionPane.showMessageDialog(this, "哈哈");}if (e.getSource() == start) {// this.restart();}if(e.getSource()==landlord[0]){time[1].setText("抢地主");t.isRun=false; //时钟终结}if(e.getSource()==landlord[1]){time[1].setText("不抢");t.isRun=false; //时钟终结}//如果是不要if(e.getSource()==publishCard[1]){this.nextPlayer=true;currentList[1].clear();time[1].setText("不要");}//如果是出牌按钮if(e.getSource()==publishCard[0]){List<Card> c=new ArrayList<Card>();//点选出牌for(int i=0;i<playerList[1].size();i++){Card card=playerList[1].get(i);if(card.clicked){c.add(card);}}int flag=0;//如果我主动出牌if(time[0].getText().equals("不要")&&time[2].getText().equals("不要")) {if(Common.jugdeType(c)!=CardType.c0)flag=1;//表⽰可以出牌}//如果我跟牌else{flag=Common.checkCards(c,currentList);}//判断是否符合出牌if(flag==1){currentList[1]=c;playerList[1].removeAll(currentList[1]);//移除⾛的牌 //定位出牌Point point=new Point();point.x=(770/2)-(currentList[1].size()+1)*15/2;;point.y=300;for(int i=0,len=currentList[1].size();i<len;i++){Card card=currentList[1].get(i);Common.move(card, card.getLocation(), point); point.x+=15;}//抽完牌后重新整理牌Common.rePosition(this, playerList[1], 1);time[1].setVisible(false);this.nextPlayer=true;}}}public static void main(String args[]) {new Main();}}class NewTimer implements Runnable{Main main;int i;public NewTimer(Main m,int i){this.main=m;this.i=i;}@Overridepublic void run() {// TODO Auto-generated method stubmain.t=new Time(main,10);//从10开始倒计时main.t.start();}}效果图<ignore_js_op><ignore_js_op><ignore_js_op><ignore_js_op>详细说明:。
Java猜拳小游戏源代码
第一个文件:public class Computer {String name;int score;public int showfist(){int quan;quan=(int)(Math.random()*10);if(quan<=2){quan=1;}else if(quan<=5){quan=2;}else{quan=3;}switch(quan){case 1:System.out.println(name+"出拳:剪刀");break;case 2:System.out.println(name+"出拳:石头");break;case 3:System.out.println(name+"出拳:布");break;}return quan;}}第二个文件:import java.util.Scanner;public class Game {int count=0;int countP=0;Person person=new Person();Computer computer=new Computer();Scanner input=new Scanner(System.in);public void initial(){System.out.print("请选择你的角色(1.刘备 2.孙权 3.曹操):");int juese=input.nextInt();switch(juese){case 1:="刘备";break;case 2:="孙权";break;case 3:="曹操";break;}System.out.print("请选择对手角色(1.关羽 2.张飞 3.赵云):");int JueSe=input.nextInt();switch(JueSe){case 1:="关羽";break;case 2:="张飞";break;case 3:="赵云";break;}}public void begin(){System.out.print("\n要开始吗? (y/n)");String ans=input.next();if(ans.equals("y")){String answ;do{int a=person.showFist();int b=computer.showfist();if(a==1&&b==3||a==2&&b==1||a==3&&b==2){System.out.println("结果:你赢了!");person.score++;}else if(a==1&&b==1||a==2&&b==2||a==3&&b==3){System.out.println("结果:平局,真衰!嘿嘿,等着瞧吧!");countP++;}else{System.out.println("结果:你输了!");computer.score++;}count++;System.out.print("\n是否开始下一轮? (y/n)");answ=input.next();}while(answ.equals("y"));}}public String calcResult(){String a;if(person.score>computer.score){a="最终结果:恭喜恭喜!你赢了!";}else if(person.score==computer.score){a="最终结果:打成平手,下次再和你一决高下!";}else{a="最终结果:呵呵,你输了!笨笨,下次加油啊!";}return a;}public void showResult(){System.out.println("---------------------------------------------------");System.out.println("\t\t"++" VS"++"\n");System.out.println("对战次数:"+count+"次");System.out.println("平局:"+countP+"次");System.out.println(+"得:"+person.score+"分");System.out.println(+"得:"+computer.score+"分\n");System.out.println(calcResult());System.out.println("---------------------------------------------------");}}第三个文件:import java.util.Scanner;public class Person {String name;int score;Scanner input=new Scanner(System.in);public int showFist(){System.out.print("\n请出拳:1.剪刀2.石头3.布");int quan=input.nextInt();switch(quan){case 1:System.out.println("你出拳:剪刀");break;case 2:System.out.println("你出拳:石头");break;case 3:System.out.println("你出拳:布");break;}return quan;}}第四个文件:public class Test {public static void main(String[]args){Game g=new Game();System.out.println("-----------------欢迎进入游戏世界--------------------\n\n");System.out.println("\t\t******************");System.out.println("\t\t** 猜拳开始 **");System.out.println("\t\t******************\n\n");System.out.println("出拳规则:1.剪刀2.石头3.布");g.initial();g.begin();g.showResult();}}。
JAVA小游戏代码(剪刀石头布)
JAVA⼩游戏代码(剪⼑⽯头布) /** 创建⼀个类Game,⽯头,剪⼑,布的游戏。
*/public class Game {/*** @param args*/String[] s ={"⽯头","剪⼑","布"};//获取电脑出拳String getComputer(int i){String computerGuess = s[i];return computerGuess;}//判断⼈出拳是否为⽯头,剪⼑,布boolean isOrder(String guess){boolean b = false;for(int x = 0;x < s.length; x++){if(guess.equals(s[x])){b = true;break;}}return b;}//⽐较void winOrLose(String guess1,String guess2){if(guess1.equals(guess2)){System.out.println("你出:" + guess1 + ",电脑出:" + guess2 + "。
平了");}else if(guess1.equals("⽯头")){if(guess2.equals("剪⼑"))System.out.println("你出:" + guess1 + ",电脑出:" + guess2 + "。
You Win!");}else{System.out.println("你出:" + guess1 + ",电脑出:" + guess2 + "。
You Lose!");}}else if(guess1.equals("剪⼑")){if(guess2.equals("布")){System.out.println("你出:" + guess1 + ",电脑出:" + guess2 + "。
小游戏系统代码
小游戏系统
V1.0
} } public static void main(String[] args) { ZhuCe zhuce = new ZhuCe(); } } 三、 package game; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class DengLu extends JFrame implements ActionListener { JPanel row = new JPanel(); JLabel nameLabel = new JLabel("姓名:",JLabel.RIGHT); JTextField name = new JTextField(30); JLabel passwordLabel = new JLabel("密码:",JLabel.RIGHT); JPasswordField password = new JPasswordField(30); JButton OK = new JButton("确定"); JButton forget = new JButton("忘记密码"); Boolean i = true; public DengLu() { super("登录"); setBounds(450,250,300,120); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(i); setResizable(false); //不许用户改变窗口大小 GridLayout layout = new GridLayout(3,2,50,10); row.setLayout(layout); row.add(nameLabel); row.add(name); row.add(passwordLabel); row.add(password); row.add(OK);
java小游戏源代码
j a v a小游戏源代码 Document number:NOCG-YUNOO-BUYTT-UU986-1986UTJava小游戏第一个Java文件:import class GameA_B {public static void main(String[] args) {Scanner reader=new Scanner;int area;"Game Start…………Please enter the area:(1-9)" +'\n'+"1,2,3 means easy"+'\n'+"4,5,6 means middle"+'\n'+"7,8,9 means hard"+'\n'+"Please choose:");area=();switch((area-1)/3){case 0:"You choose easy! ");break;case 1:"You choose middle! ");break;case 2:"You choose hard! ");break;}"Good Luck!");GameProcess game1=new GameProcess(area);();}}第二个Java文件:import class GameProcess {int area,i,arrcount,right,midright,t;int base[]=new int[arrcount],userNum[]=newint[area],sysNum[]=new int[area];Random random=new Random();Scanner reader=new Scanner;GameProcess(int a){area=a;arrcount=10;right=0;midright=0;t=0;base=new int[arrcount];userNum=new int[area];sysNum=new int[area];for(int i=0;i<arrcount;i++){base[i]=i;// }}void process(){rand();while(right!=area){scanf();compare();print();check();}}void rand(){for(i=0;i<area;i++){t=(arrcount);//sysNum[i]=base[t];delarr(t);}}void delarr(int t){for(int j=t;j<arrcount-1;j++)base[j]=base[j+1];arrcount--;}void scanf(){"The system number has created!"+"\n"+"Please enter "+area+" Numbers");for(int i=0;i<area;i++){userNum[i]=();}}void check(){if(right==area)"You win…………!");}boolean check(int i){return true;}void compare(){int i=0,j=0;right=midright=0;for(i=0;i<area;i++){for(j=0;j<area;j++){if(userNum[i]==sysNum[j]){if(i==j)right++;elsemidright++;}}}}void print(){" A "+right+" B "+midright);}}。
JAVA小程序—贪吃蛇源代码
JAVA贪吃蛇源代码SnakeGame。
javapackage SnakeGame;import javax.swing。
*;public class SnakeGame{public static void main( String[]args ){JDialog。
setDefaultLookAndFeelDecorated( true ); GameFrame temp = new GameFrame();}}Snake.javapackage SnakeGame;import java。
awt.*;import java。
util。
*;class Snake extends LinkedList{public int snakeDirection = 2;public int snakeReDirection = 4;public Snake(){this。
add( new Point( 3, 3 ));this。
add(new Point(4, 3 ));this.add( new Point(5,3 ) );this。
add( new Point(6,3 ) );this。
add(new Point(7,3 ));this。
add( new Point( 8,3 ) );this。
add( new Point( 9, 3 ));this。
add( new Point( 10,3 ));}public void changeDirection( Point temp, int direction ) {this。
snakeDirection = direction;switch(direction ){case 1://upthis.snakeReDirection = 3;this。
add( new Point(temp.x,temp.y - 1 ));break;case 2://rightthis。
一个简单又有趣的JAVA小游戏代码
一个简单又有趣的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<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("但是你还……真笨!"); elseSystem.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); }}}}。
JAVA抓螃蟹小游戏源代码
鼠标点击事件:package muitl;import java.applet.Applet;import java.awt.Cursor;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.io.File;import .MalformedURLException;import javax.swing.JLabel;public class Catcher extends MouseAdapter{public void mousePressed(MouseEvent e){if (e.getButton() != MouseEvent.BUTTON1)return;Object source = e.getSource();//获取事件源if (source instanceof JLabel) { // 如果事件源是标签组件JLabel carb = (JLabel) source; // 强制转换为JLabel标签if (carb.getIcon() != null) {carb.setIcon(Image.crab2); // 为该标签添加螃蟹图片}}//螃蟹叫声try{CommUtil.audioClip = Applet.newAudioClip(new File(Class.class.getResource("/com/insigma/music/cap.au").getPath()).toURI().toURL());} catch (MalformedURLException e1){// TODO Auto-generated catch blocke1.printStackTrace();}CommUtil.audioClip.play();// 播放try{Thread.sleep(1000);} catch (InterruptedException e2){// TODO Auto-generated catch blocke2.printStackTrace();} // 使线程休眠1秒}public void mouseReleased(MouseEvent e) {if (e.getButton() != MouseEvent.BUTTON1)return;Object source = e.getSource(); // 获取事件源,即螃蟹标签if (source instanceof JLabel) { // 如果事件源是标签组件JLabel carb = (JLabel) source; // 强制转换为JLabel标签carb.setIcon(null);// 清除标签中的螃蟹图片}}}图片类:package muitl;import javax.swing.ImageIcon;public class Image{/*** 背景图片*/public static final ImageIcon background = new ImageIcon(Class.class.getResource("/com/insigma/images/background.jpg").getPath());/*** 螃蟹图片*/public static final ImageIcon crab1 = new ImageIcon(Class.class.getResource("/com/insigma/images/crab.png").getPath());public static final ImageIcon crab2 = new ImageIcon(Class.class.getResource("/com/insigma/images/crab2.png").getPath());/*** 鼠标图片*/public static final ImageIcon hand1 = new ImageIcon(Class.class.getResource("/com/insigma/images/hand.jpg").getPath());public static final ImageIcon hand2 = new ImageIcon(Class.class.getResource("/com/insigma/images/hand2.jpg").getPath());}背景音乐:package muitl;import java.applet.Applet;import java.applet.AudioClip;import java.io.File;import .MalformedURLException;public class PlayMusic extends Thread{public void run(){// 以下是编写背景音乐类,并加入到main方法中启动while (true){if (CommUtil.audioClip == null){try{try{CommUtil.audioClip = Applet.newAudioClip(new File(Class.class.getResource("/com/insigma/music/backgroup.au").getPath()).toURI().toURL());} catch (MalformedURLException e1){e1.printStackTrace();}CommUtil.audioClip.play();// 播放CommUtil.audioClip.loop(); // 循环播放} catch (Exception e){e.printStackTrace();}}}}}工具类:package muitl;import java.applet.AudioClip;public class CommUtil{public static AudioClip audioClip = null; }。
用Java编程语言编写石头剪刀布游戏示例
用Java编程语言编写石头剪刀布游戏示例文章标题:用Java编程语言编写石头剪刀布游戏示例介绍内容:石头剪刀布游戏是一种简单而受欢迎的游戏,编程语言可以帮助我们实现一个可以和计算机进行对战的石头剪刀布游戏程序。
本文将介绍如何使用Java编程语言编写一个简单而有趣的石头剪刀布游戏示例。
首先,我们需要创建一个Java类,作为我们的游戏程序的主类。
接下来,我们可以使用Java的输入输出和随机数生成的类来实现游戏的逻辑。
下面是一个示例代码,用于实现一个石头剪刀布游戏:```javaimport java.util.Scanner;import java.util.Random;public class RockPaperScissorsGame {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);Random random = new Random();String[] gestures = {"石头", "剪刀", "布"};System.out.println("欢迎来到石头剪刀布游戏!");while (true) {System.out.print("请输入你的选择(石头、剪刀、布):");String playerGesture = scanner.nextLine();if (!isValidGesture(playerGesture)) {System.out.println("无效的手势,请重新输入。
");continue;}int computerChoice = random.nextInt(3);String computerGesture = gestures[computerChoice];System.out.println("你的选择:" + playerGesture);System.out.println("电脑的选择:" + computerGesture);String result = calculateResult(playerGesture, computerGesture);System.out.println(result);System.out.print("是否要继续游戏?(是/否):");String continueChoice = scanner.nextLine();if (continueChoice.equalsIgnoreCase("否")) {break;}}System.out.println("谢谢你玩石头剪刀布游戏!");}private static boolean isValidGesture(String gesture) {return gesture.equals("石头") || gesture.equals("剪刀") || gesture.equals("布");}private static String calculateResult(String playerGesture, String computerGesture) {if (playerGesture.equals(computerGesture)) {return "平局!";} else if ((playerGesture.equals("石头") && computerGesture.equals("剪刀")) ||(playerGesture.equals("剪刀") && computerGesture.equals("布")) ||(playerGesture.equals("布") && computerGesture.equals("石头"))) {return "你赢了!";} else {return "你输了!";}}}```在上述Java代码中,我们首先使用Scanner类来接收玩家输入,使用Random类来生成电脑的随机选择。
初学JAVA 好玩的打架小游戏代码 -
break;}
}
}
if (enemyif == 1){
enemyhp+=enemyheal;
if(enemyhp >= 1000){enemyhp = 1000;}
int enemyheal = (int)(Math.random()*50);
int i = JOptionPane.showOptionDialog(null, "Which action you want to do next?", "Combat Control Panel",JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options1, options[0]);
import javax.swing.JOptionPane;
public class GameWithNumbers_GroupProject
{
public static void main(String[] args)
{
//Create buttons for you to choose the game.
else{
JOptionPane.showMessageDialog(null,"You have attacked your enemy critially this "
+ "turn \nYour HP: " + myhp + ", \nYour enemy's HP:" + enemyhp +
【连连看】小游戏初始源代码
mai nFrame.setBou nds(280,100,500,450);
mai nFrame.setVisible(true);
}
p ublic void ran domBuild() {
int ran doms,cols,rows;
thisCo ntai ner.add( north Pan el,"North");
cen terPa nel.setLayout (new GridLayout(6,5));
for(i nt cols = 0;cols < 6;cols++){
for(i nt rows = 0;rows < 5;rows++ ){
JButton diamo ndsButt on叩=new JButt on[ 6][5];//游戏按钮数组
JButton exitButto n,resetButt on,n ewlyButto n; //退出,重列,重新开始按钮
JLabel fractionLable=new JLabel("0"); //分数标签
while(grid[cols][rows]!=0) {
cols=(i nt)(Math.ra ndom()*6+1);
rows=(i nt)(Math.ra ndom()*5+1);
}
this.grid[cols][rows]=ra ndoms;
}
}
}
p ublic void fraction(){
centerPanel=new JPan el();
新人Eclipse编写的Java小游戏
新人Eclipse编写的Java小游戏Eclipse编写的Java小游戏初学java时编写的简单小游戏,非界面版,纯java基础组成,新人都能看得懂可以做的来,主要是其中的逻辑思想。
使用eclipse编程,直接建立一个java 复制代码进去就可以了。
希望对大家学习java编程有点帮助游戏一:随即取5个数排列,要求猜出这5个数package day;import java.util.Random;import java.util.Scanner;import java.util.regex.Matcher;import java.util.regex.Pattern;public class Game {public static void main(String[] args) {Random r = new Random();int a1 = r.nextInt(10);int a2 = r.nextInt(10);int a3 = r.nextInt(10);int a4 = r.nextInt(10);int a5 = r.nextInt(10);System.out.println("游戏规则:随即取5个数,请输入5个数,数字顺序要求一致,会告诉你答对几个,看你能在几次猜对");Scanner scan = new Scanner(System.in);for(int i=1;;i++){int c=0;System.out.println("请输入5个数:");String dir = scan.nextLine();Pattern pattern = /doc/8a7064941.html,pile("^[0-9]{5}$");Matcher matcher = pattern.matcher(dir);if(matcher.find()){int b1 = Integer.parseInt(dir.substring(0,1));int b2 = Integer.parseInt(dir.substring(1,2));int b3 = Integer.parseInt(dir.substring(2,3));int b4 = Integer.parseInt(dir.substring(3,4));int b5 = Integer.parseInt(dir.substring(4,5));if(a1==b1){c++;}if(a2==b2){c++;}if(a3==b3){c++;}if(a4==b4){c++;}if(a5==b5){c++;}if(c==5){if(i<=5){System.out.println("恭喜你猜对了,猜对次数"+i+",妖才级别");break;}else if(i<=15){System.out.println("恭喜你猜对了,猜对次数"+i+",天才级别");break;}else if(i<=25){System.out.println("恭喜你猜对了,猜对次数"+i+",聪明人级别");break;}else if(i<=40){System.out.println("恭喜你猜对了,猜对次数"+i+",常人级别");break;}else if(i<=60){System.out.println("恭喜你猜对了,猜对次数"+i+",迟钝级别");break;}else{System.out.println("恭喜你猜对了,猜对次数"+i+",傻瓜级别");break;}}else{System.out.println("猜对了"+c+"个,请继续努力");}}else{System.out.println("只能输入5位数字,请重试");}}}}游戏二:package day;import java.util.Arrays;import java.util.Random;import java.util.Scanner;import java.util.regex.Matcher;import java.util.regex.Pattern;public class Game1 {public static void main(String[] args) {String[] str = {"鼠","牛","虎","兔","龙","蛇","马","羊","猴","鸡","狗","猪"};System.out.println("玩个小游戏,现在你手上有100分,从十二生肖中选择押注,只能压一个数目不限,随机选取5次");System.out.println("中1个翻1倍,2个翻3倍,3个翻6倍,4个翻10倍,5个翻15倍(输入如:龙5)。
java小游戏源代码教学文案
j a v a小游戏源代码Java小游戏第一个Java文件:import java.util.Scanner;public class GameA_B {public static void main(String[] args) {Scanner reader=new Scanner(System.in);int area;System.out.println("Game Start…………Please enter the area:(1-9)" +'\n'+"1,2,3 means easy"+'\n'+"4,5,6 means middle"+'\n'+"7,8,9 means hard"+'\n'+"Please choose:");area=reader.nextInt();switch((area-1)/3){case 0:System.out.println("You choose easy! ");break;case 1:System.out.println("You choose middle! ");break;case 2:System.out.println("You choose hard! ");break;}System.out.println("Good Luck!");GameProcess game1=new GameProcess(area);game1.process();}}第二个Java文件:import java.util.Random;import java.util.Scanner;public class GameProcess {int area,i,arrcount,right,midright,t;int base[]=new int[arrcount],userNum[]=newint[area],sysNum[]=new int[area];Random random=new Random();Scanner reader=new Scanner(System.in);GameProcess(int a){area=a;arrcount=10;right=0;midright=0;t=0;base=new int[arrcount];userNum=new int[area];sysNum=new int[area];for(int i=0;i<arrcount;i++){base[i]=i;//System.out.println(base[i]);}}void process(){rand();while(right!=area){scanf();compare();print();check();}}void rand(){for(i=0;i<area;i++){t=random.nextInt(arrcount);//System.out.println(t);sysNum[i]=base[t];System.out.println(base[t]);delarr(t);}}void delarr(int t){for(int j=t;j<arrcount-1;j++)base[j]=base[j+1];arrcount--;}void scanf(){System.out.println("The system number has created!"+"\n"+"Please enter "+area+" Numbers");for(int i=0;i<area;i++){userNum[i]=reader.nextShort();}}void check(){if(right==area)System.out.println("You win…………!");}boolean check(int i){return true;}void compare(){int i=0,j=0;right=midright=0;for(i=0;i<area;i++){for(j=0;j<area;j++){if(userNum[i]==sysNum[j]){if(i==j)right++;elsemidright++;}}}}void print(){System.out.println(" A "+right+" B "+midright); }}。
java简易小游戏制作代码
java简易⼩游戏制作代码java简易⼩游戏制作游戏思路:设置⼈物移动,游戏规则,积分系统,随机移动的怪物,游戏胜负判定,定时器。
游戏内容部分package 代码部分;import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.util.Random;public class TestGamePanel extends JPanel implements KeyListener, ActionListener {//初始化⼈物坐标int p1X;int p1Y;int p2X;int p2Y;boolean isStart = false; //游戏是否开始boolean p1isFail = false; //游戏是否失败boolean p2isFail = false;String fx1; //左:L,右:R,上:U,下:DString fx2;Timer timer = new Timer(50,this);//定时器//积分int p1score = 0;int p2score = 0;//苹果int AppleX;int AppleY;//怪物int monster1X;int monster1Y;int monster2X;int monster2Y;int monster3X;int monster3Y;int monster4X;int monster4Y;int monster5X;int monster5Y;//随机积分Random random = new Random();public TestGamePanel() {init();this.setFocusable(true);this.addKeyListener(this);timer.start();}//初始化public void init() {p1X = 25;p1Y = 150;p2X = 700;p2Y = 550;fx1 = "L";fx2 = "R";monster1X = 25*random.nextInt(28);monster1Y = 100 + 25*random.nextInt(18);monster2X = 25*random.nextInt(28);monster2Y = 100 + 25*random.nextInt(18);monster3X = 25*random.nextInt(28);monster3Y = 100 + 25*random.nextInt(18);monster4X = 25*random.nextInt(28);monster4Y = 100 + 25*random.nextInt(18);monster5X = 25*random.nextInt(28);monster5Y = 100 + 25*random.nextInt(18);AppleX = 25*random.nextInt(28);AppleY = 100 + 25*random.nextInt(18);add(kaishi);add(chongkai);guize.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {new TestGameRule();}});}//游戏功能按钮JButton kaishi = new JButton("开始");JButton chongkai = new JButton("重新开始");JButton guize = new JButton("游戏规则");//画板@Overrideprotected void paintComponent(Graphics g) {super.paintComponent(g);TestGameData.header.paintIcon(this,g,0,0);g.setColor(Color.CYAN);g.fillRect(0,100,780,520);//画⼈物TestGameData.p1player1.paintIcon(this,g,p1X,p1Y);TestGameData.p2player1.paintIcon(this,g,p2X,p2Y);//画得分g.setFont(new Font("华⽂彩云",Font.BOLD,18)); //设置字体g.setColor(Color.RED);g.drawString("玩家1:" + p1score,20,20 );g.drawString("玩家2:" + p2score,680,20);//画苹果TestGameData.apple.paintIcon(this,g,AppleX,AppleY);//画静态怪物TestGameData.monster.paintIcon(this,g,monster1X,monster1Y);TestGameData.monster.paintIcon(this,g,monster2X,monster2Y);TestGameData.monster.paintIcon(this,g,monster3X,monster3Y);TestGameData.monster.paintIcon(this,g,monster4X,monster4Y);TestGameData.monster.paintIcon(this,g,monster5X,monster5Y);//游戏提⽰,是否开始if(!isStart) {g.setColor(Color.BLACK);g.setFont(new Font("华⽂彩云",Font.BOLD,30));g.drawString("请点击开始游戏",300,300);}//游戏结束提⽰,是否重新开始if(p2isFail || p1score == 15) {g.setColor(Color.RED);g.setFont(new Font("华⽂彩云",Font.BOLD,30));g.drawString("玩家⼀获胜,请点击重新开始游戏",200,300);if(p1isFail || p2score == 15) {g.setColor(Color.RED);g.setFont(new Font("华⽂彩云",Font.BOLD,30));g.drawString("玩家⼆获胜,请点击重新开始游戏",200,300); }}//键盘监听事件@Overridepublic void keyPressed(KeyEvent e) {//控制⼈物⾛动//玩家1if(isStart == true && (p1isFail == false && p2isFail == false)) { if(e.getKeyCode() == KeyEvent.VK_D) {fx1 = "R";p1X += 25;if(p1X >= 750) {p1X = 750;}}else if(e.getKeyCode() == KeyEvent.VK_A) {fx1 = "L";p1X -= 25;if(p1X <= 0) {p1X = 0;}}else if(e.getKeyCode() == KeyEvent.VK_W) {fx1 = "U";p1Y -= 25;if(p1Y <= 100) {p1Y = 100;}}else if(e.getKeyCode() == KeyEvent.VK_S) {fx1 = "D";p1Y += 25;if(p1Y >= 600) {p1Y = 600;}}//玩家2if(e.getKeyCode() == KeyEvent.VK_RIGHT) {fx2 = "R";p2X += 25;if(p2X >= 750) {p2X = 750;}}else if(e.getKeyCode() == KeyEvent.VK_LEFT) {fx2 = "L";p2X -= 25;if(p2X <= 0) {p2X = 0;}}else if(e.getKeyCode() == KeyEvent.VK_UP) {fx2 = "U";p2Y -= 25;if(p2Y <= 100) {p2Y = 100;}}else if(e.getKeyCode() == KeyEvent.VK_DOWN) {fx2 = "D";p2Y += 25;if(p2Y >= 600) {p2Y = 600;}}}repaint();}@Overridepublic void actionPerformed(ActionEvent e) {kaishi.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {isStart = true;}});chongkai.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {if(p1isFail) { p1isFail = !p1isFail; init(); }if(p2isFail) { p2isFail = !p2isFail; init(); }}});add(kaishi);add(chongkai);add(guize);if(isStart == true && (p1isFail == false && p2isFail == false)) { //让⼈动起来if(fx1.equals("R")) {p1X += 25;if(p1X >= 750) { p1X = 750; }}if(fx1.equals("L")) {p1X -= 25;if(p1X <= 0) { p1X = 0; }}if(fx1.equals("U")) {p1Y -= 25;if(p1Y <= 100) { p1Y = 100; }}if(fx1.equals("D")) {p1Y += 25;if(p1Y >= 600) { p1Y = 600; }}if(fx2.equals("R")) {p2X += 25;if(p2X >= 750) { p2X = 750; }}if(fx2.equals("L")) {p2X -= 25;if(p2X <= 0) { p2X = 0; }}if(fx2.equals("U")) {p2Y -= 25;if(p2Y <= 100) { p2Y = 100; }}if(fx2.equals("D")) {p2Y += 25;if(p2Y >= 600) { p2Y = 600; }}//让怪物动起来//怪物1int i = random.nextInt(4) + 1;if(i == 1) {monster1X += 5;if(monster1X >= 750) {monster1X = 750;}}if(i == 2) {monster1X -= 5;if(monster1X <= 0) {monster1X = 0;}}if(i == 3) {monster1Y += 5;if(monster1Y >= 600) {monster1Y = 600;}if(i == 4) {monster1Y -= 5;if(monster1Y <= 100) {monster1Y = 100;}}//怪物2int j = random.nextInt(4) + 1;if(j == 1) {monster2X += 5;if(monster2X >= 750) {monster2X = 750;}}if(j == 2) {monster2X -= 5;if(monster2X <= 0) {monster2X = 0;}}if(j == 3) {monster2Y += 5;if(monster2Y >= 600) {monster2Y = 600;}}if(j == 4) {monster2Y -= 5;if(monster2Y <= 100) {monster2Y = 100;}}//怪物3int k = random.nextInt(4) + 1;if(k == 1) {monster3X += 5;if(monster3X >= 750) {monster3X = 750;}}if(k == 2) {monster3X -= 5;if(monster3X <= 0) {monster3X = 0;}}if(k == 3) {monster3Y += 5;if(monster3Y >= 600) {monster3Y = 600;}}if(k == 4) {monster3Y -= 5;if(monster3Y <= 100) {monster3Y = 100;}}//怪物4int n= random.nextInt(4) + 1;if(n == 1) {monster4X += 5;if(monster4X >= 750) {monster4X = 750;}}if(n == 2) {monster4X -= 5;if(monster4X <= 0) {monster4X = 0;}}if(n == 3) {monster4Y += 5;if(monster4Y >= 600) {monster4Y = 600;}}if(n == 4) {monster4Y -= 5;if(monster4Y <= 100) {monster4Y = 100;}}//怪物5int m = random.nextInt(4) + 1;if(m == 1) {monster5X += 5;if(monster5X >= 750) {monster5X = 750;}}if(m == 2) {monster5X -= 5;if(monster5X <= 0) {monster5X = 0;}}if(m == 3) {monster5Y += 5;if(monster5Y >= 600) {monster5Y = 600;}}if(m == 4) {monster5Y -= 5;if(monster5Y <= 100) {monster5Y = 100;}}//如果有玩家吃到⾷物if(p1X == AppleX && p1Y == AppleY) {p1score++;AppleX = 25*random.nextInt(28);AppleY = 100 + 25*random.nextInt(18);} else if(p2X == AppleX && p2Y == AppleY) {p2score++;AppleX = 25*random.nextInt(28);AppleY = 100 + 25*random.nextInt(18);}//如果有玩家碰到怪物,判定死亡,游戏结束后续有修改,暂⽤ //怪物1死亡if(p1X >= monster1X -25 && p1X <= monster1X +25) {if(p1Y == monster1Y) { p1isFail = !p1isFail; p1score = p2score = 0;} }if(p1Y >= monster1Y -25 && p1Y <= monster1Y +25) {if(p1X == monster1X) { p1isFail = !p1isFail; p1score = p2score = 0;} }if(p2X >= monster1X -25 && p2X <= monster1X +25) {if(p2Y == monster1Y) { p2isFail = !p2isFail; p1score = p2score = 0;} }if(p2Y >= monster1Y -25 && p2Y <= monster1Y +25) {if(p2X == monster1X) { p2isFail = !p2isFail; p1score = p2score = 0;} }//怪物2死亡if(p1X >= monster2X -25 && p1X <= monster2X +25) {if(p1Y == monster2Y) { p1isFail = !p1isFail; p1score = p2score = 0;} }if(p1Y >= monster2Y -25 && p1Y <= monster2Y +25) {if(p1X == monster2X) { p1isFail = !p1isFail; p1score = p2score = 0;} }if(p2X >= monster2X -25 && p2X <= monster2X +25) {if(p2Y == monster2Y) { p2isFail = !p2isFail; p1score = p2score = 0;} }if(p2Y >= monster2Y -25 && p2Y <= monster2Y +25) {if(p2X == monster2X) { p2isFail = !p2isFail; p1score = p2score = 0;} }//怪物3死亡if(p1X >= monster3X -25 && p1X <= monster3X +25) {if(p1Y == monster3Y) { p1isFail = !p1isFail; p1score = p2score = 0;} }if(p1Y >= monster3Y -25 && p1Y <= monster3Y +25) {if(p1X == monster3X) { p1isFail = !p1isFail; p1score = p2score = 0;} }if(p2X >= monster3X -25 && p2X <= monster3X +25) {if(p2Y == monster3Y) { p2isFail = !p2isFail; p1score = p2score = 0;}if(p2Y >= monster3Y -25 && p2Y <= monster3Y +25) {if(p2X == monster3X) { p2isFail = !p2isFail; p1score = p2score = 0;}}//怪物4死亡if(p1X >= monster4X -25 && p1X <= monster4X +25) {if(p1Y == monster4Y) { p1isFail = !p1isFail; p1score = p2score = 0;}}if(p1Y >= monster4Y -25 && p1Y <= monster4Y +25) {if(p1X == monster1X) { p1isFail = !p1isFail; p1score = p2score = 0;}}if(p2X >= monster4X -25 && p2X <= monster4X +25) {if(p2Y == monster4Y) { p2isFail = !p2isFail; p1score = p2score = 0;}}if(p2Y >= monster4Y -25 && p2Y <= monster4Y +25) {if(p2X == monster4X) { p2isFail = !p2isFail; p1score = p2score = 0;}}//怪物5死亡if(p1X >= monster5X -25 && p1X <= monster5X +25) {if(p1Y == monster5Y) { p1isFail = !p1isFail; p1score = p2score = 0;}}if(p1Y >= monster5Y -25 && p1Y <= monster5Y +25) {if(p1X == monster5X) { p1isFail = !p1isFail; p1score = p2score = 0;}}if(p2X >= monster5X -25 && p2X <= monster5X +25) {if(p2Y == monster5Y) { p2isFail = !p2isFail; p1score = p2score = 0;}}if(p2Y >= monster5Y -25 && p2Y <= monster5Y+25) {if(p2X == monster5X) { p2isFail = !p2isFail; p1score = p2score = 0;}}//如果有玩家达到指定积分,判定获胜,游戏结束if(p1score == 15) { p2isFail = !p2isFail; }if(p2score == 15) { p1isFail = !p1isFail; }repaint();}timer.start();}@Overridepublic void keyTyped(KeyEvent e) {}@Overridepublic void keyReleased(KeyEvent e) {}}游戏规则(使⽤弹窗)部分package 代码部分;import javax.swing.*;import java.awt.*;public class TestGameRule extends JDialog {private int num = 1;public TestGameRule() {TextArea textArea = new TextArea(20,10);textArea.setText("游戏中有五个怪物随机移动,碰到怪物算死亡\\\n游戏中有随机出现的苹果,碰到⼀个苹果加⼀分,\\\n先达到⼗五分或者对⼿死亡算游戏胜利!"); JScrollPane jScrollPane = new JScrollPane(textArea);this.add(jScrollPane);this.setBounds(200,200,400,400);this.setVisible(true);textArea.setEditable(false);setResizable(false);textArea.setBackground(Color.PINK);}}图⽚素材package 代码部分;import javax.swing.*;import .URL;public class TestGameData {public static URL headerurl = TestGameData.class.getResource("/图⽚素材/header.jpg");public static URL p1player1url = TestGameData.class.getResource("/图⽚素材/1.jpg");public static URL p2player2url = TestGameData.class.getResource("/图⽚素材/2.jpg");public static URL appleurl = TestGameData.class.getResource("/图⽚素材/apple.jpg");public static URL monsterurl = TestGameData.class.getResource("/图⽚素材/monster.jpg");public static ImageIcon p1player1 = new ImageIcon(p1player1url);public static ImageIcon p2player1 = new ImageIcon(p2player2url);public static ImageIcon header = new ImageIcon(headerurl);public static ImageIcon apple = new ImageIcon(appleurl);public static ImageIcon monster = new ImageIcon(monsterurl);}主函数package 代码部分;import javax.swing.*;public class TestStartGame {public static void main(String[] args) {//制作窗⼝JFrame jFrame = new JFrame("2D对战⼩游戏");jFrame.setBounds(10,10,790,660);jFrame.setResizable(false);jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//添加游戏⾯板jFrame.add(new TestGamePanel());//设置可见jFrame.setVisible(true);}}实现效果到此这篇关于java简易⼩游戏制作代码的⽂章就介绍到这了,更多相关java简易⼩游戏内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。
java推箱子游戏源代码(含推箱子的判断)
第一个Java文件:package xiaoA;import java.awt.Color;import java.awt.HeadlessException;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;public class GameFrame extends JFrame {JPanel zhuobu = new JPanel();//工人JLabel worker = null;//箱子JLabel box = null;//目的地JLabel goal = null;JLabel[] walls = null;public static final int SPEED = 12;//设置图片大小int imgSize = 48;public void setImgSize(int imgSize){this.imgSize = imgSize;}public GameFrame(String title) throws HeadlessException { super(title);//构造方法中调用本类的其它方法this.initContentPane();this.addKeyListener(new KeyListener() {//键盘按下事件public void keyPressed(KeyEvent e) {//[2.5] 使工人可以移动int xSpeed = 0, ySpeed = 0;switch (e.getKeyCode()) {case KeyEvent.VK_LEFT :xSpeed = -SPEED;worker.setIcon(new ImageIcon("image/workerUp.gif"));break;case KeyEvent.VK_RIGHT :xSpeed = SPEED;worker.setIcon(new ImageIcon("image/workerUp.gif"));break;case KeyEvent.VK_UP :ySpeed = -SPEED;worker.setIcon(new ImageIcon("image/workerUp.gif"));break;case KeyEvent.VK_DOWN :ySpeed = SPEED;worker.setIcon(new ImageIcon("image/workerUp.gif"));break;default:return;}worker.setBounds(worker.getX() + xSpeed, worker.getY() + ySpeed, worker.getWidth(), worker.getHeight());//[2.7] 判断工人是否撞到墙壁for (int i = 0; i < walls.length; i++) {if(worker.getBounds().intersects(walls[i].getBounds())) {worker.setBounds(worker.getX() - xSpeed, worker.getY() - ySpeed, worker.getWidth(), worker.getHeight());}}//[3.2] 使工人可以推动箱子if (worker.getBounds().intersects(box.getBounds())) {box.setBounds(box.getX() + xSpeed, box.getY() + ySpeed, box.getWidth(), box.getHeight());//[3.3] 判断箱子是否撞到墙壁for (int i = 0; i < walls.length; i++) {if (box.getBounds().intersects(walls[i].getBounds())) {worker.setBounds(worker.getX() - xSpeed, worker.getY() - ySpeed, worker.getWidth(), worker.getHeight());box.setBounds(box.getX() - xSpeed, box.getY() - ySpeed, box.getWidth(), box.getHeight());}}//[3.4] 判断是否胜利if (box.getX()==goal.getX() && box.getY()==goal.getY()) { JOptionPane.showMessageDialog(null, "您赢啦!");}}}public void keyReleased(KeyEvent e) {}public void keyTyped(KeyEvent e) {}});}/***设置内容面板*/public void initContentPane() {zhuobu.setBackground(Color.red);zhuobu.setLayout(null);//调用父类的属性和方法super.setContentPane(zhuobu);}/***把某个图片以组件的方式加入窗体*@param imgPath图片路径*@param x x*@param y y*@param width宽度*@param height高度*@return添加完的组件*/public void addComponent(int tag, String imgPath, int x, int y) { ImageIcon img = new ImageIcon(imgPath);//创建JLabel并把ImageIcon通过构造方法传参传入//把食物放到盘子里JLabel componet = new JLabel(img);//设置盘子在桌布上的位置和大小componet.setBounds(x, y, imgSize, imgSize);//把盘子放到桌布上zhuobu.add(componet);switch (tag) {case 1:box = componet;break;case 2:goal = componet;break;case 3:worker = componet;break;}}public void addWall(String imgPath, int[][] loactions) { ImageIcon wallImg = new ImageIcon(imgPath);walls = new JLabel[66 + loactions.length];for (int i = 0; i < walls.length; i++) {//创建没每一个围墙,他们使用的是同一个图片walls[i] = new JLabel(wallImg);}for (int i = 0; i < walls.length; i++) {//创建没每一个围墙,他们使用的是同一个图片walls[i] = new JLabel(wallImg);}int index = 0;/*分别设置各个图片位置*/for (int i = 0; i < 14; i++) {//左边墙walls[index].setBounds(0, i * imgSize, imgSize, imgSize);zhuobu.add(walls[index]);index++;//右边墙walls[index].setBounds(20 * imgSize, i * imgSize, imgSize, imgSize);zhuobu.add(walls[index]);index++;}for (int i = 0; i < 19; i++) {//上边墙walls[index].setBounds((i + 1) * imgSize, 0, imgSize, imgSize);zhuobu.add(walls[index]);index++;//下边墙walls[index].setBounds((i + 1) * imgSize, 13 * imgSize, imgSize, imgSize);zhuobu.add(walls[index]);index++;}//添加中间障碍耦合解耦for (int i = 0; i < loactions.length; i++) {walls[index].setBounds(loactions[i][0]* imgSize, loactions[i][1]* imgSize, imgSize, imgSize);zhuobu.add(walls[index]);index++;}}}第二个Java文件:public class Run {public static void main(String[] args) {GameFrame gameFrame = new GameFrame("推箱子游戏…");//设置大小gameFrame.setBounds(100, 50, 21 * 48 + 5, 14 * 48 + 25);//窗体大小不可变gameFrame.setResizable(false);gameFrame.setImgSize(48);gameFrame.addComponent(3, "workerUp.png", 400, 100);gameFrame.addComponent(1, "box.png", 160, 60);gameFrame.addComponent(2, "goal.png", 80, 520);int[][] wallLocations ={{4, 5},{5, 5},{6, 5},{7, 5},{8, 5},{9, 5},{10, 5},{6, 8},{7, 8},{8, 8},{9, 8},{10, 8},{11, 5}};gameFrame.addWall("wall.png", wallLocations);gameFrame.setVisible(true);}}。
Java实现的打地鼠小游戏完整示例【附源码下载】
Java实现的打地⿏⼩游戏完整⽰例【附源码下载】本⽂实例讲述了Java实现的打地⿏⼩游戏。
分享给⼤家供⼤家参考,具体如下:这⾥涉及到java线程和GUI的相关知识,⼀个简单的java⼩游戏打地⿏,有兴趣的朋友可以优化⼀下。
先来看看运⾏效果:具体代码:Mouse.java:import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.Toolkit;import java.awt.event.KeyEvent;import java.util.HashMap;import java.util.Map;import java.util.Random;public class Mouse {private int x, y;private int tab;private int data;Random rd = new Random();private boolean live = true;private int mouseTime = 10;private MouseClient mc;private static Toolkit tk = Toolkit.getDefaultToolkit();private static Image[] imgs = null;private static Map<Image, String> imgKV = new HashMap<Image, String>();static {imgs = new Image[] {tk.getImage(Mouse.class.getClassLoader().getResource("images/A.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/B.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/C.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/D.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/E.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/F.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/G.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/H.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/I.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/J.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/K.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/L.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/M.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/N.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/O.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/P.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/Q.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/R.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/S.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/T.png")),tk.getImage(Mouse.class.getClassLoader().getResource("images/U.png")),tk.getImage(Mouse.class.getClassLoader().getResource( "images/V.png")),tk.getImage(Mouse.class.getClassLoader().getResource( "images/W.png")),tk.getImage(Mouse.class.getClassLoader().getResource( "images/X.png")),tk.getImage(Mouse.class.getClassLoader().getResource( "images/Y.png")),tk.getImage(Mouse.class.getClassLoader().getResource( "images/Z.png")),tk.getImage(Mouse.class.getClassLoader().getResource( "images/0.png")),tk.getImage(Mouse.class.getClassLoader().getResource( "images/1.png")),tk.getImage(Mouse.class.getClassLoader().getResource( "images/2.png")),tk.getImage(Mouse.class.getClassLoader().getResource( "images/3.png")),tk.getImage(Mouse.class.getClassLoader().getResource( "images/4.png")),tk.getImage(Mouse.class.getClassLoader().getResource( "images/5.png")),tk.getImage(Mouse.class.getClassLoader().getResource( "images/6.png")),tk.getImage(Mouse.class.getClassLoader().getResource( "images/7.png")),tk.getImage(Mouse.class.getClassLoader().getResource( "images/8.png")),tk.getImage(Mouse.class.getClassLoader().getResource( "images/9.png"))};imgKV.put(imgs[0], "A");imgKV.put(imgs[1], "B");imgKV.put(imgs[2], "C");imgKV.put(imgs[3], "D");imgKV.put(imgs[4], "E");imgKV.put(imgs[5], "F");imgKV.put(imgs[6], "G");imgKV.put(imgs[7], "H");imgKV.put(imgs[8], "I");imgKV.put(imgs[9], "J");imgKV.put(imgs[10], "K");imgKV.put(imgs[11], "L");imgKV.put(imgs[12], "M");imgKV.put(imgs[13], "N");imgKV.put(imgs[14], "O");imgKV.put(imgs[15], "P");imgKV.put(imgs[16], "Q");imgKV.put(imgs[17], "R");imgKV.put(imgs[18], "S");imgKV.put(imgs[19], "T");imgKV.put(imgs[20], "U");imgKV.put(imgs[21], "V");imgKV.put(imgs[22], "W");imgKV.put(imgs[23], "X");imgKV.put(imgs[24], "Y");imgKV.put(imgs[25], "Z");imgKV.put(imgs[26], "0");imgKV.put(imgs[27], "1");imgKV.put(imgs[28], "2");imgKV.put(imgs[29], "3");imgKV.put(imgs[30], "4");imgKV.put(imgs[31], "5");imgKV.put(imgs[32], "6");imgKV.put(imgs[33], "7");imgKV.put(imgs[34], "8");imgKV.put(imgs[35], "9");}public Mouse(int x, int y, int tab, MouseClient mc) {this.x = x;this.y = y;this.tab = tab;this.mc = mc;data = rd.nextInt(36);new Thread(new MouseTime()).start();}public void draw(Graphics g) {if (!live) {mc.mouses.remove(this);mc.tab[tab] = 0;return;}g.drawImage(imgs[data], x, y, null);Color c = g.getColor();g.setColor(Color.gray);g.setFont(new Font(null, 1, 40));g.drawString("" + mouseTime, x + 50, y + 10);if (mouseTime <= 0) {this.live = false;mc.eclipseTime++;}}public boolean keyReleased(KeyEvent e) {int key = imgKV.get(imgs[data]).charAt(0);if (e.getKeyCode() == key) {System.out.println(key);mc.mouseCount++;this.live = false;return true;}return false;}private class MouseTime implements Runnable { public void run() {while (true) {mouseTime--;try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}}}MouseClient.java:import java.awt.Color;import java.awt.Frame;import java.awt.Graphics;import java.awt.Image;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.util.ArrayList;import java.util.List;import java.util.Random;public class MouseClient extends Frame {/** 整个游戏界⾯的规格*/public static final int GAME_WIDTH = 1000;public static final int GAME_HEIGHT = 700;public static int mouseCount;public static int count;public static int gameTime;public static int eclipseTime;List<Mouse> mouses = new ArrayList<Mouse>(); Random rd = new Random();public int initMouseCount = 2;// 同时显⽰的地⿏数 public int[] tab = new int[10];// 标记坑⾥是否有地⿏ Image offScreenImage = null;/** 本⽅法显⽰主窗⼝*/public void launchFrame() {this.setLocation(200, 10);this.setSize(GAME_WIDTH, GAME_HEIGHT);this.setTitle("MouseClient");this.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}});this.setVisible(true);this.setBackground(Color.GREEN);this.setResizable(false);this.addKeyListener(new KeyMonitor());new Thread(new PaintThread()).start();new Thread(new GameTime()).start();}private class GameTime implements Runnable {public void run() {while (true) {gameTime++;try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}}private class PaintThread implements Runnable {public void run() {while (true) {repaint();try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}}}}public void update(Graphics g) {if (offScreenImage == null) {offScreenImage = this.createImage(GAME_WIDTH, GAME_HEIGHT); }Graphics gOffScreen = offScreenImage.getGraphics();Color c = gOffScreen.getColor();gOffScreen.setColor(Color.GREEN);gOffScreen.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);gOffScreen.setColor(c);paint(gOffScreen);g.drawImage(offScreenImage, 0, 0, null);}public void paint(Graphics g) {Color c = g.getColor();g.setColor(Color.gray);for (int i = 1; i <= 3; i++)for (int j = 1; j <= 3; j++)g.fillOval(GAME_WIDTH / 4 * i - 60, GAME_HEIGHT / 4 * j - 25,120, 50);g.setColor(c);g.drawString("击打数:" + count, 20, 40);g.drawString("击中数:" + mouseCount, 20, 60);g.drawString("逃跑数:" + eclipseTime + "", 20, 80);g.drawString("时间:" + gameTime + "s", 20, 100);if (mouseCount >= 80)initMouseCount = 8;else if (mouseCount >= 50)initMouseCount = 6;else if (mouseCount >= 20)initMouseCount = 4;int temp;while (mouses.size() < initMouseCount) {temp = rd.nextInt(9);while (tab[temp] == 1) {temp++;if (temp == 9)temp = 0;}tab[temp] = 1;mouses.add(new Mouse(GAME_WIDTH / 4 * (temp % 3 + 1) - 70,GAME_HEIGHT / 4 * (temp / 3 + 1) - 100, temp, this));}for (int i = 0; i < mouses.size(); i++) {Mouse m = mouses.get(i);m.draw(g);}}public static void main(String[] args) {MouseClient km = new MouseClient();unchFrame();}private class KeyMonitor extends KeyAdapter {public void keyReleased(KeyEvent e) {System.out.println(e.getKeyCode());count++;for (int i = 0; i < mouses.size(); i++) {if (mouses.get(i).keyReleased(e))break;}}}}附:完整实例代码点击此处。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Java小游戏
第一个Java文件:
import java.util.Scanner;
public class GameA_B {
public static void main(String[] args) {
Scanner reader=new Scanner(System.in);
int area;
System.out.println("Game Start…………Please enter the area:(1-9)"+ '\n'+"1,2,3 means easy"+'\n'+"4,5,6 means middle"+'\n'+
"7,8,9 means hard"+'\n'+"Please choose:");
a rea=reader.nextInt();
s witch((area-1)/3)
{
c ase 0:System.out.println("You choose easy! ");break;
c ase 1:System.out.println("You choose middle! ");break;
c ase 2:System.out.println("You choose hard! ");break;
}
S ystem.out.println("Good Luck!");
G ameProcess game1=new GameProcess(area);
game1.process();
}
}
第二个Java文件:
import java.util.Random;
import java.util.Scanner;
public class GameProcess {
int area,i,arrcount,right,midright,t;
int base[]=new int[arrcount],userNum[]=new int[area],sysNum[]=new int[area];
Random random=new Random();
Scanner reader=new Scanner(System.in);
GameProcess(int a)
{
area=a;
arrcount=10;
right=0;
midright=0;
t=0;
base=new int[arrcount];
userNum=new int[area];
sysNum=new int[area];
for(int i=0;i<arrcount;i++)
{
base[i]=i;
//System.out.println(base[i]);
}
}
void process()
{
r and();
w hile(right!=area)
{
s canf();
c ompare();
p rint();
c heck();
}
}
void rand()
{
f or(i=0;i<area;i++)
{
t=random.nextInt(arrcount);
//System.out.println(t);
sysNum[i]=base[t];
System.out.println(base[t]);
delarr(t);
}
}
void delarr(int t)
{
f or(int j=t;j<arrcount-1;j++)
base[j]=base[j+1];
a rrcount--;
}
void scanf()
{
S ystem.out.println("The system number has created!"+"\n"+"Please enter "+area+" Numbers");
for(int i=0;i<area;i++)
{
userNum[i]=reader.nextShort();
}
}
void check()
{
if(right==area)
S ystem.out.println("You win…………!");
}
boolean check(int i)
{
r eturn true;
}
void compare()
{
i nt i=0,j=0;
r ight=midright=0;
f or(i=0;i<area;i++)
{
for(j=0;j<area;j++)
{
if(userNum[i]==sysNum[j])
{
if(i==j)
right++;
else
midright++;
}
}
}
}
void print()
{
S ystem.out.println(" A "+right+" B "+midright); }
}。