java小游戏源码

合集下载

Java名字打架小游戏代码

Java名字打架小游戏代码

Java名字打架小游戏代码一、截图如下:1、初始界面:2、游戏中界面:3、游戏结束界面:二、程序代码如下:import java.awt.*;import java.awt.event.*;class Game extends Frame implements ActionListener{Labell1,l2,label0,label1,label2,label3,label4,label5,label6,label7;TextField text1,text2,text3,text4,text5,text6;Button button,button1,button2;Panel p1,p2,p3,p4;TextArea area;Menu menu;MenuBar menubar;MenuItem item1,item2;int HP,gongji,fangyv;int count1=0,count2=0,count3=0,count4=0;Thread thread1;Game(String s){super(s);thread1=new Thread();label0=new Label("初始血量在2000-3000之间随机产生!");l1=new Label("姓名1",Label.CENTER);l2=new Label("姓名2",Label.CENTER);label1=new Label("姓名1",Label.CENTER);label2=new Label("姓名2",Label.CENTER);label3=new Label("属性1",Label.CENTER);label4=new Label("属性2",Label.CENTER);label5=new Label("PK状态",Label.CENTER);label6=new Label("被治疗次数:"+count1+" 被攻击次数:"+count2);label7=new Label("被治疗次数:"+count3+" 被攻击次数:"+count4);p1=new Panel();p2=new Panel();p3=new Panel();p4=new Panel();area=new TextArea(10,30);text1=new TextField(5);text2=new TextField(5);text3=new TextField(34);text4=new TextField(34);text5=new TextField(27);text6=new TextField(27);button=new Button("确定");button1=new Button("重新输入");button2=new Button("退出");thread1.start();add(p1,BorderLayout.NORTH);add(p2,BorderLayout.CENTER);p1.add(label0);p2.add(label1);p2.add(text1);p2.add(button);p2.add(label2);p2.add(text2);p2.add(label3);p2.add(text3);p2.add(label4);p2.add(text4);p2.add(label5);p2.add(p3);p2.add(label6);p2.add(p4);p2.add(label7);p2.add(area);p2.add(button1);p2.add(button2);p3.add(l1);p3.add(text5);p4.add(l2);p4.add(text6);l1.setLocation(0, 0);text5.setLocation(20,0);area.setEditable(false);text3.setEditable(false);text4.setEditable(false);text5.setEditable(false);text6.setEditable(false);button.setBackground(Color.LIGHT_GRAY); button1.setBackground(Color.LIGHT_GRAY); button2.setBackground(Color.LIGHT_GRAY); label0.setBackground(Color.orange);label3.setBackground(Color.cyan);label4.setBackground(Color.cyan);label5.setBackground(Color.cyan); button.addActionListener(this);button1.addActionListener(this);button2.addActionListener(this);menu=new Menu("菜单");item1=new MenuItem("打开");item2=new MenuItem("退出");p2.setBackground(Color.pink);p1.setBackground(Color.orange); menubar=new MenuBar();menu.add(item1);menu.addSeparator();menu.add(item2);menubar.add(menu);setMenuBar(menubar);item2.addActionListener(this);area.setBackground(Color.yellow);addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});setBounds(500,100,285,590);setResizable(false);//设置窗口不可调整大小setVisible(true);validate();}public void actionPerformed(ActionEvent e){if(e.getSource()==item2 ||e.getSource()==button2)System.exit(0);else if(e.getSource()==button){String name1=text1.getText();String name2=text2.getText();NPCC npc1=new NPCC(name1);NPCC npc2=new NPCC(name2);npc1.shuxing();npc2.shuxing();l1.setText(name1);l2.setText(name2);int h1,h2;h1=npc1.HP;h2=npc2.HP;text3.setText(name1+": HP:"+npc1.HP+" 攻击:"+npc1.gongji+" 防御:"+npc1.fangyv);text4.setText(name2+": HP:"+npc2.HP+" 攻击:"+npc2.gongji+" 防御:"+npc2.fangyv);int i=0;while(npc1.HP>0 && npc2.HP>0){if (i%2==0){String s1=npc1.damage(npc2.gongji);if(npc1.HPP!=0){count1++;}else{count2++;}label6.setText("被治疗次数:"+count1+" 被攻击次数:"+count2);String s=s1;npc1.HP=npc1.HP+npc1.HPP+npc1.fangyv-npc1.hurt;if(npc1.HP>h1){area.append(name1+s+'\n');text5.setText(name1+s);try{thread1.sleep(1000);}catch(InterruptedException ee){}npc1.HP=h1;s1="血量已达最大值!!";}if(npc1.HP<0){npc1.HP=0;}text3.setText(name1+": HP:"+npc1.HP+" 攻击:"+npc1.gongji+" 防御:"+npc1.fangyv);text5.setText(name1+s1);area.append(name1+s1+'\n');area.append(name1+"剩余生命值:"+npc1.HP+'\n');}else{String s2=npc2.damage(npc1.gongji);if(npc2.HPP!=0){count3++;}else{count4++;}label7.setText("被治疗次数:"+count3+" 被攻击次数:"+count4);String s=s2;npc2.HP=npc2.HP+npc2.HPP+npc2.fangyv-npc2.hurt;if(npc2.HP>h2){text6.setText(name2+s);area.append(name2+s+'\n');try{thread1.sleep(1000);}catch(InterruptedException ee){}npc2.HP=h2;s2="血量已达最大值!!";}if(npc2.HP<0){npc2.HP=0;}text4.setText(name2+": HP:"+npc2.HP+" 攻击:"+npc2.gongji+" 防御:"+npc2.fangyv);text6.setText(name2+s2);area.append(name2+s2+'\n');area.append(name2+"剩余生命值:"+npc2.HP+'\n');}try{thread1.sleep(1000);}catch(InterruptedException ee){}i++;}if(npc1.HP<=0){text5.setText(name1+"挂了!!!\n");text6.setText(name1+"挂了!!!\n");area.append(name1+"挂了!!!\n");}else if(npc2.HP<=0){text5.setText(name2+"挂了!!!\n");text6.setText(name2+"挂了!!!\n");area.append(name2+"挂了!!!\n");}}else if(e.getSource()==button1){text1.setText(null);text2.setText(null);text3.setText(null);text4.setText(null);text5.setText(null);text6.setText(null);area.setText(null);label6.setText("被治疗次数:"+0+" 被攻击次数:"+0);label7.setText("被治疗次数:"+0+" 被攻击次数:"+0);l1.setText("姓名1");l2.setText("姓名2");}}}class NPCC{String name,s;int HP,gongji,fangyv;int HPP=0;int hurt=0;NPCC(String name){=name;}public void shuxing(){HP=(int)(Math.random()*1000)+2000;gongji=(int)(Math.random()*150)+80;fangyv=(int)(Math.random()*30)+50;}public String damage(int gongji){int a=(int)(Math.random()*10);switch(a){case 1:s="受到普通攻击";hurt=gongji;HPP=0;break;case 2:s="受到爆击";hurt=gongji*2;HPP=0;break;case 3:s="喝了瓶红药,生命增加100";HPP=HPP+100;hurt=0;break;case 4:s="受到毒害";hurt=gongji*3;HPP=0;break;case 5:s="吃了灵芝,生命增加300";HPP=HPP+300;hurt=0;break;case 6:s="受到法术伤害";hurt=gongji*4;HPP=0;break;case 7:s="受到围殴";hurt=gongji*5;HPP=0;break;case 8:s="受到致命一击";hurt=gongji*6;HPP=0;break;case 9:s="吃了颗复活丹,生命增加800";HPP=HPP+800;hurt=0;break;default:s="发生未知意外";break;}return s;}}public class text{public static void main(String ars[]) {new Game("名字打架小游戏");}}。

JAVA小游戏代码(剪刀石头布)

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 + "。

初学JAVA好玩的小游戏代码

初学JAVA好玩的小游戏代码

很简单的小游戏import javax.swing.JOptionPane;public class GameWithNumbers_GroupProject{public static void main(String[] args){//Create buttons for you to choose the game.Object[] options ={ "Game fight", "Find mere", "Guess numbers","Quit" };int button = JOptionPane.showOptionDialog(null, "Which action you want to do next?", "Combat Control Panel",JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);if (button == JOptionPane.YES_OPTION){{Object[] options1 ={ "Attack", "Heal", "Quit" };int myap = 0 ;int enap = 0 ;int myhp = 500;int enemyhp = 500;JOptionPane.showMessageDialog(null, "This is a Fighting Game \nYou and your enemy both have 500 blood \nYou can choose attack your enemy or heal yourself next");while (myhp > 0 && enemyhp > 0){int myattack = (int)(Math.random()*100);int enemyattack = (int)(Math.random()*100);int myheal = (int)(Math.random()*50);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]);if (i == JOptionPane.YES_OPTION){if (myap != 100){enemyhp-=myattack;enap += 25;if(enemyhp <= 0){JOptionPane.showMessageDialog(null,"You have attacked your enemy this turn \nYour HP: " + myhp + ", \nYour enemy's HP:" + "0" + " \nGet into your enemy's turn?");break;}else{JOptionPane.showMessageDialog(null,"You have attacked your enemy this turn \nYour HP: " + myhp + ", \nYour enemy's HP:" + enemyhp + " \nGet into your enemy's turn?");}}else{enemyhp-=myattack*2;enap += 25;myap = 0 ;if(enemyhp <= 0){JOptionPane.showMessageDialog(null,"You have attacked your enemy"+ " critically this turn \nYour HP: " + myhp + ", \nYour enemy's HP:" + "0" +" \nGet into your enemy's turn?");break;}else{JOptionPane.showMessageDialog(null,"You have attacked your enemy critially this "+ "turn \nYour HP: " + myhp + ", \nYour enemy's HP:" + enemyhp +" \nGet into your enemy's turn?");}}if (i == JOptionPane.NO_OPTION){myhp+=myheal;if (myhp >= 1000){myhp = 1000;}}JOptionPane.showMessageDialog(null,"You have healed yourself this turn \nYour HP: " + myhp + ", \nYour enemy's HP:" + enemyhp + " \nGet into your enemy's turn?");}if (i == JOptionPane.CANCEL_OPTION){break;}int enemyif = (int)(Math.random()*2);if (enemyif == 0){if(enap !=100){myhp-=enemyattack;myap+=25;很简单的小游戏if(myhp>=0){JOptionPane.showMessageDialog(null,"Your enemy has attacked you this turn \nYour HP: " + myhp + ", \nYour enemy's HP: " + enemyhp + " \nDo you want to get into your turn?");}else{JOptionPane.showMessageDialog(null,"Your enemy has attacked you this turn \nYour HP: " + "0" + ", \nYour enemy's HP: " + enemyhp + " \nDo you want to get into your turn?"); break;}}else{myhp-=enemyattack*2;myap+=25;enap = 0;if(myhp>=0){JOptionPane.showMessageDialog(null,"Your enemy has attacked you "+ "critically this turn \nYour HP: " + myhp +", \nYour enemy's HP: " + enemyhp + " \nDo you want to get "+ "into your turn?");}else{JOptionPane.showMessageDialog(null,"Your enemy has attacked you "+ "critically this turn \nYour HP: " + "0" +", \nYour enemy's HP: " + enemyhp + " \nDo you want to get "+ "into your turn?");break;}}}if (enemyif == 1){enemyhp+=enemyheal;if(enemyhp >= 1000){enemyhp = 1000;}JOptionPane.showMessageDialog(null,"Your enemy has healed himself this turn \nyour HP: " + myhp + ", \nYour enemy's HP:" + enemyhp + " \nDo you want to get into your turn?");}}if (myhp <= 0){JOptionPane.showMessageDialog(null,"You die, Game Over");}if (enemyhp <= 0){JOptionPane.showMessageDialog(null,"Your enemy die, You are the winner!");}else{JOptionPane.showMessageDialog(null,"The Player Quit The Game");}}}if (button == JOptionPane.NO_OPTION){//Prompt user enter his or her birthday.int birthmonth=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the month "+ "you were born in(1 to 12):"));int birthdate=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the day "+ "you were born in:"));Constellation1(birthmonth,birthdate);}if (button == JOptionPane.CANCEL_OPTION){//Create the number and tell reader whether it is prime number:int guess=(int)(Math.random()*99+2);int guess1=(int)(Math.pow(guess,0.5));String judge="";for (int check=2; check<=guess1;check++){if(guess % check == 0)judge="The number you will guess is not a prime number";elsejudge="The number you will guess is a prime number";}JOptionPane.showMessageDialog(null,judge);//Prompt user to input the numberint user=Integer.parseInt(JOptionPane.showInputDialog(null,"Guess the number(2 to 100): "));do{if(user<guess)JOptionPane.showMessageDialog(null,"The number you guessed is too low, please try again!");if(user>guess)JOptionPane.showMessageDialog(null,"The number you guessed is too large, please try again!");u很简单的小游戏if(myhp>=0){JOptionPane.showMessageDialog(null,"Your enemy has attacked you this turn \nYour HP: " + myhp + ", \nYour enemy's HP: " + enemyhp + " \nDo you want to get into your turn?");}else{JOptionPane.showMessageDialog(null,"Your enemy has attacked you this turn \nYourHP: " + "0" + ", \nYour enemy's HP: " + enemyhp + " \nDo you want to get into your turn?"); break;}}else{myhp-=enemyattack*2;myap+=25;enap = 0;if(myhp>=0){JOptionPane.showMessageDialog(null,"Your enemy has attacked you "+ "critically this turn \nYour HP: " + myhp +", \nYour enemy's HP: " + enemyhp + " \nDo you want to get "+ "into your turn?");}else{JOptionPane.showMessageDialog(null,"Your enemy has attacked you "+ "critically this turn \nYour HP: " + "0" +", \nYour enemy's HP: " + enemyhp + " \nDo you want to get "+ "into your turn?");break;}}}if (enemyif == 1){enemyhp+=enemyheal;if(enemyhp >= 1000){enemyhp = 1000;}JOptionPane.showMessageDialog(null,"Your enemy has healed himself this turn \nyour HP: " + myhp + ", \nYour enemy's HP:" + enemyhp + " \nDo you want to get into your turn?");}}if (myhp <= 0){JOptionPane.showMessageDialog(null,"You die, Game Over");}if (enemyhp <= 0){JOptionPane.showMessageDialog(null,"Your enemy die, You are the winner!");}else{JOptionPane.showMessageDialog(null,"The Player Quit The Game");}}}if (button == JOptionPane.NO_OPTION){//Prompt user enter his or her birthday.int birthmonth=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the month "+ "you were born in(1 to 12):"));int birthdate=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the day "+ "you were born in:"));Constellation1(birthmonth,birthdate);}if (button == JOptionPane.CANCEL_OPTION){//Create the number and tell reader whether it is prime number:int guess=(int)(Math.random()*99+2);int guess1=(int)(Math.pow(guess,0.5));String judge="";for (int check=2; check<=guess1;check++){if(guess % check == 0)judge="The number you will guess is not a prime number";elsejudge="The number you will guess is a prime number";}JOptionPane.showMessageDialog(null,judge);//Prompt user to input the numberint user=Integer.parseInt(JOptionPane.showInputDialog(null,"Guess the number(2 to 100): "));do{if(user<guess)JOptionPane.showMessageDialog(null,"The number you guessed is too low, please try again!");if(user>guess)JOptionPane.showMessageDialog(null,"The number you guessed is too large, please try again!");U很简单的小游戏ser=Integer.parseInt(JOptionPane.showInputDialog(null,"Guess the number(2 to 100): "));}while(user != guess);JOptionPane.showMessageDialog(null,"You got the right answer!","Congratulations!",2);}}public static int Constellation1(int month, int date){if((month==3 && date>=21 && date<=31)||(month==4 && date>=1 && date<=19)) {JOptionPane.showMessageDialog(null,"You are Aries!");}else if((month==4 && date>=20 && date<=31)||(month==5 && date>=1 && date<=20)) {JOptionPane.showMessageDialog(null,"You are Taurus!");}else if((month==5 && date>=21 && date<=31)||(month==6 && date>=1 && date<=21)) {JOptionPane.showMessageDialog(null,"You are Gemini!");}else if((month==6 && date>=22 && date<=30)||(month==7 && date>=1 && date<=22)) {JOptionPane.showMessageDialog(null,"You are Cancer!");}else if((month==7 && date>=23 && date<=31)||(month==8 && date>=1 && date<=22)) {JOptionPane.showMessageDialog(null,"You are Leo!");}else if((month==9 && date>=1 && date<=22)||(month==8 && date>=23 && date<=31)) {JOptionPane.showMessageDialog(null,"You are Virgo!");}else if((month==9 && date>=23 && date<=30)||(month==10 && date>=1 && date<=22)) {JOptionPane.showMessageDialog(null,"You are Libra!");}else if((month==11 && date>=1 && date<=21)||(month==10 && date>=23 && date<=31)) {JOptionPane.showMessageDialog(null,"You are Scorpio!");}else if((month==11 && date>=22 && date<=30)||(month==12 && date>=1 && date<=21)) {JOptionPane.showMessageDialog(null,"You are Sagittarius!");}else if((month==1 && date>=1 && date<=19)||(month==12 && date>=22 && date<=31)) {JOptionPane.showMessageDialog(null,"You are Capricorn!");}else if((month==1 && date>=20 && date<=31)||(month==2 && date>=1 && date<=18)) {JOptionPane.showMessageDialog(null,"You are Aquarius!");}else{JOptionPane.showMessageDialog(null,"You are Pisces!");}return Constellation2(month,date);}public static int Constellation2(int month, int date){month=(int)(Math.random()*12+1);if(month==4 || month==6 || month==9 || month==11)date=(int)(Math.random()*31+1);else if(month==2)date=(int)(Math.random()*29+1);elsedate=(int)(Math.random()*30+1);String monthname="";switch(month){case 1:monthname="January";break;case 2:monthname="Feburary";break;case 3:monthname="March";break;case 4:monthname="April";break;case 5:monthname="May";break;case 6:monthname="June";break;case 7:monthname="July";break;case 8:monthname="August";break;case 9:monthname="September";break;case 10:monthname=&quot;October";break;case 11:monthname="November";break;default:monthname="December";break;}JOptionP很简单的小游戏ser=Integer.parseInt(JOptionPane.showInputDialog(null,"Guess the number(2 to 100): ")); }while(user != guess);JOptionPane.showMessageDialog(null,"You got the right answer!","Congratulations!",2);}}public static int Constellation1(int month, int date){if((month==3 && date>=21 && date<=31)||(month==4 && date>=1 && date<=19)) {JOptionPane.showMessageDialog(null,"You are Aries!");}else if((month==4 && date>=20 && date<=31)||(month==5 && date>=1 && date<=20)) {JOptionPane.showMessageDialog(null,"You are Taurus!");}else if((month==5 && date>=21 && date<=31)||(month==6 && date>=1 && date<=21)) {JOptionPane.showMessageDialog(null,"You are Gemini!");}else if((month==6 && date>=22 && date<=30)||(month==7 && date>=1 && date<=22)) {JOptionPane.showMessageDialog(null,"You are Cancer!");}else if((month==7 && date>=23 && date<=31)||(month==8 && date>=1 && date<=22)) {JOptionPane.showMessageDialog(null,"You are Leo!");}else if((month==9 && date>=1 && date<=22)||(month==8 && date>=23 && date<=31)) {JOptionPane.showMessageDialog(null,"You are Virgo!");}else if((month==9 && date>=23 && date<=30)||(month==10 && date>=1 && date<=22)) {JOptionPane.showMessageDialog(null,"You are Libra!");}else if((month==11 && date>=1 && date<=21)||(month==10 && date>=23 && date<=31)) {JOptionPane.showMessageDialog(null,"You are Scorpio!");}else if((month==11 && date>=22 && date<=30)||(month==12 && date>=1 && date<=21)) {JOptionPane.showMessageDialog(null,"You are Sagittarius!");}else if((month==1 && date>=1 && date<=19)||(month==12 && date>=22 && date<=31)) {JOptionPane.showMessageDialog(null,"You are Capricorn!");}else if((month==1 && date>=20 && date<=31)||(month==2 && date>=1 && date<=18)) {JOptionPane.showMessageDialog(null,"You are Aquarius!");}else{JOptionPane.showMessageDialog(null,"You are Pisces!");}return Constellation2(month,date);}public static int Constellation2(int month, int date){month=(int)(Math.random()*12+1);if(month==4 || month==6 || month==9 || month==11)date=(int)(Math.random()*31+1);else if(month==2)date=(int)(Math.random()*29+1);elsedate=(int)(Math.random()*30+1);String monthname="";switch(month){case 1:monthname="January"; break;case 2:monthname="Feburary"; break;case 3:monthname="March"; break;case 4:monthname="April"; break;case 5:monthname="May"; break;case 6:monthname="June"; break;case 7:monthname="July"; break;case 8:monthname="August"; break;case 9:monthname="September"; break;case 10:monthname=&quot;October";break;case 11:monthname="November"; break;default:monthname="December"; break;}JOptionPane.showMessageDialog(null, "You should find a fere whose birthday is "+date+ "th of "+monthname);System.exit(0);return Constellation1(month,date);}}。

小游戏系统代码

小游戏系统代码

小游戏系统
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小游戏源代码

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实现2048小游戏(含注释)

java实现2048小游戏(含注释)

java实现2048⼩游戏(含注释)本⽂实例为⼤家分享了java实现2048⼩游戏的具体代码,供⼤家参考,具体内容如下实现⽂件APP.javaimport javax.swing.*;public class APP {public static void main(String[] args) {new MyFrame();}}类⽂件import javax.swing.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.util.Random;//定义⾃⼰的类(主类)去继承JFrame类并实现KeyListener接⼝和ActionListener接⼝public class MyFrame extends JFrame implements KeyListener, ActionListener {//⽤于存放游戏各位置上的数据int[][] data = new int[4][4];//⽤于判断是否失败int loseFlag = 1;//⽤于累计分数int score = 0;//⽤于切换主题String theme = "A";//设置三个菜单项⽬JMenuItem item1 = new JMenuItem("经典");JMenuItem item2 = new JMenuItem("霓虹");JMenuItem item3 = new JMenuItem("糖果");//核⼼⽅法public MyFrame(){//初始化窗⼝initFrame();//初始化菜单initMenu();//初始化数据initData();//绘制界⾯paintView();//为窗体提供键盘监听,该类本⾝就是实现对象this.addKeyListener(this);//设置窗体可见setVisible(true);}//窗体初始化public void initFrame(){//设置尺⼨setSize(514,538);//设置居中setLocationRelativeTo(null);//设置总在最上⾯setAlwaysOnTop(true);setLayout(null);}//初始化菜单public void initMenu() {//菜单栏⽬JMenuBar menuBar = new JMenuBar();JMenu menu1 = new JMenu("换肤");JMenu menu2 = new JMenu("关于我们");//添加上menuBarmenuBar.add(menu1);menuBar.add(menu2);//添加上menumenu1.add(item1);menu1.add(item2);menu1.add(item3);//注册监听item1.addActionListener(this);item2.addActionListener(this);item3.addActionListener(this);//添加进窗体super.setJMenuBar(menuBar);}//初始化数据,在随机位置⽣成两个2public void initData(){generatorNum();generatorNum();}//重新绘制界⾯的⽅法public void paintView(){//调⽤⽗类中的⽅法清空界⾯getContentPane().removeAll();//判断是否失败if(loseFlag==2){//绘制失败界⾯JLabel loseLable = new JLabel(new ImageIcon("D:\\Download\\BaiDu\\image\\"+theme+"-lose.png"));//设置位置和⾼宽loseLable.setBounds(90,100,334,228);//将该元素添加到窗体中getContentPane().add(loseLable);}//根据现有数据绘制界⾯for(int i=0;i<4;i++) {//根据位置循环绘制for (int j = 0; j < 4; j++) {JLabel image = new JLabel(new ImageIcon("D:\\Download\\BaiDu\\image\\"+theme+"-"+data[i][j]+".png"));//提前计算好位置image.setBounds(50 + 100 * j, 50+100*i, 100, 100);//将该元素添加进窗体getContentPane().add(image);}}//绘制背景图⽚JLabel background = new JLabel(new ImageIcon("D:\\Download\\BaiDu\\image\\"+theme+"-Background.jpg")); //设置位置和⾼宽background.setBounds(40,40,420,420);//将该元素添加进窗体getContentPane().add(background);//得分模板设置JLabel scoreLable = new JLabel("得分:"+score);//设置位置和⾼宽scoreLable.setBounds(50,20,100,20);getContentPane().repaint();}//⽤不到的但是必须重写的⽅法,⽆需关注@Overridepublic void keyTyped(KeyEvent e) {}//键盘被按下所触发的⽅法,在此⽅法中加⼊区分上下左右的按键@Overridepublic void keyPressed(KeyEvent e) {//keyCode接收按键信息int keyCode = e.getKeyCode();//左移动if(keyCode == 37){moveToLeft(1);generatorNum();}//上移动else if(keyCode==38){moveToTop(1);generatorNum();}//右移动else if(keyCode==39){moveToRight(1);generatorNum();}//下移动else if(keyCode==40){moveToBottom(1);generatorNum();}//忽视其他按键else {return;}//检查是否能够继续移动check();//重新根据数据绘制界⾯paintView();}//左移动的⽅法,通过flag判断,传⼊1是正常移动,传⼊2是测试移动 public void moveToLeft(int flag) {for(int i=0;i<data.length;i++){//定义⼀维数组接收⼀⾏的数据int[] newArr = new int[4];//定义下标⽅便操作int index=0;for(int x=0;x<data[i].length;x++){//将有数据的位置前移if(data[i][x]!=0){newArr[index]=data[i][x];index++;}}//赋值到原数组data[i]=newArr;//判断相邻数据是否相邻,相同则相加,不相同则略过for(int x=0;x<3;x++){if(data[i][x]==data[i][x+1]){data[i][x]*=2;//如果是正常移动则加分if(flag==1){score+=data[i][x];}//将合并后的数据都前移,实现数据覆盖for(int j=x+1;j<3;j++){data[i][j]=data[i][j+1];}//末尾补0data[i][3]=0;}//右移动的⽅法,通过flag判断,传⼊1是正常移动,传⼊2是测试移动 public void moveToRight(int flag) {//翻转⼆维数组reverse2Array();//对旋转后的数据左移动moveToLeft(flag);//再次翻转reverse2Array();}//上移动的⽅法,通过flag判断,传⼊1是正常移动,传⼊2是测试移动 public void moveToTop(int flag) {//逆时针旋转数据anticlockwise();//对旋转后的数据左移动moveToLeft(flag);//顺时针还原数据clockwise();}//下移动的⽅法,通过flag判断,传⼊1是正常移动,传⼊2是测试移动 public void moveToBottom(int flag) {//顺时针旋转数据clockwise();//对旋转后的数据左移动moveToLeft(flag);//逆时针旋转还原数据anticlockwise();}//检查能否左移动public boolean checkLeft(){//开辟新⼆维数组⽤于暂存数据和⽐较数据int[][] newArr = new int[4][4];//复制数组copyArr(data,newArr);//测试移动moveToLeft(2);boolean flag = false;//设置break跳出的for循环标记lo:for (int i = 0; i < data.length; i++) {for (int j = 0; j < data[i].length; j++) {//如果有数据不相同,则证明能够左移动,则返回trueif(data[i][j]!=newArr[i][j]){flag=true;break lo;}}}//将原本的数据还原copyArr(newArr,data);return flag;}//检查能否右移动,与checkLeft()⽅法原理相似public boolean checkRight(){int[][] newArr = new int[4][4];copyArr(data,newArr);moveToRight(2);boolean flag = false;lo:for (int i = 0; i < data.length; i++) {for (int j = 0; j < data[i].length; j++) {if(data[i][j]!=newArr[i][j]){flag=true;break lo;}}}copyArr(newArr,data);//检查能否上移动,与checkLeft()⽅法原理相似public boolean checkTop(){int[][] newArr = new int[4][4];copyArr(data,newArr);moveToTop(2);boolean flag = false;lo:for (int i = 0; i < data.length; i++) {for (int j = 0; j < data[i].length; j++) {if(data[i][j]!=newArr[i][j]){flag=true;break lo;}}}copyArr(newArr,data);return flag;}//检查能否下移动,与checkLeft()⽅法原理相似public boolean checkBottom(){int[][] newArr = new int[4][4];copyArr(data,newArr);moveToBottom(2);boolean flag = false;lo:for (int i = 0; i < data.length; i++) {for (int j = 0; j < data[i].length; j++) {if(data[i][j]!=newArr[i][j]){flag=true;break lo;}}}copyArr(newArr,data);return flag;}//检查是否失败public void check(){//上下左右均不能移动,则游戏失败if(checkLeft()==false&&checkRight()==false&&checkTop()==false&&checkBottom()==false){ loseFlag = 2;}}//复制⼆维数组的⽅法,传⼊原数组和新数组public void copyArr(int[][] src,int[][] dest){for (int i = 0; i < src.length; i++) {for (int j = 0; j < src[i].length; j++) {//遍历复制dest[i][j]=src[i][j];}}}//键盘被松开@Overridepublic void keyReleased(KeyEvent e) {}//翻转⼀维数组public void reverseArray(int[] arr){for(int start=0,end=arr.length-1;start<end;start++,end--){int temp = arr[start];arr[start] = arr[end];arr[end] = temp;}}//翻转⼆维数组public void reverse2Array(){for (int i = 0; i < data.length; i++) {reverseArray(data[i]);//顺时针旋转public void clockwise(){int[][] newArr = new int[4][4];for(int i=0;i<4;i++){for(int j=0;j<4;j++){//找规律啦~newArr[j][3-i] = data[i][j];}}data = newArr;}//逆时针旋转public void anticlockwise(){int[][] newArr = new int[4][4];for(int i=0;i<4;i++){for(int j=0;j<4;j++){//规律newArr[3-j][i] = data[i][j];}}data = newArr;}//空位置随机⽣成2public void generatorNum(){int[] arrarI = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; int[] arrarJ = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; int w=0;for (int i = 0; i < data.length; i++) {for (int j = 0; j < data[i].length; j++) {if(data[i][j]==0){//找到并存放空位置arrarI[w]=i;arrarJ[w]=j;w++;}}}if(w!=0){//随机数找到随机位置Random r= new Random();int index = r.nextInt(w);int x = arrarI[index];int y = arrarJ[index];//空位置随机⽣成2data[x][y]=2;}}//换肤操作@Overridepublic void actionPerformed(ActionEvent e) {//接收动作监听,if(e.getSource()==item1){theme = "A";}else if(e.getSource()==item2){theme = "B";}else if(e.getSource()==item3){theme = "C";}//换肤后重新绘制paintView();}}//测试失败效果的数据/*int[][] data = {{2,4,8,4},{16,32,64,8},{128,2,256,2},{512,8,1024,2048}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

Java猜拳小游戏源代码

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小游戏源代码
第一个Java文件: import java.util.Scanner;
Java 小游戏
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抓螃蟹小游戏源代码

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编写的俄罗斯方块(小游戏)
short i,j;
for (i=0; i<xblocks; i++)
{
for (j=0; j<yblocks; j++)
{
screendata[i][j]=0;
}
ห้องสมุดไป่ตู้ }
score=0;
emptyline=-1;
int objectdx;
short objecttype;
short objectcolor;
int objectrotation;
int objectrotationd=0;
short objectptr;
short checkptr;
final short itemcount=7;
fmsmall = g.getFontMetrics();
g.setFont(largefont);
fmlarge = g.getFontMetrics();
gameInit();
}
//初始化游戏
public void gameInit()
{
0,0, 1,0, 0,1, -1,1, // 被旋转180度
0,0, 0,-1, 1,0, 1,1, // 被旋转270度
0,0, 1,0, -1,0, 0,-1, // L形1,正常状态
0,0, 0,1, 0,-1, -1,0, // 被旋转90度
short screencount=40;
boolean showtitle=true;
int items[]={
0,0, -1,0, 0,-1, -1,-1, // 四方形, 正常状态

java小游戏连连看源代码

java小游戏连连看源代码

Java小游戏——连连看源码连连看java源代码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。

2020年java小游戏源代码

2020年java小游戏源代码

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:"
{
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 [i]=i; //System.out.println(base[i]);
} }
void process()
{
r and();
while ( right != area ) {
s canf();
c ompare();
p rint();
c heck();
}
}
void rand()
{
f or ( i =0; i < area ; i ++)

小游戏JAVA代码--贪吃蛇

小游戏JAVA代码--贪吃蛇
}
//******************菜单监听******************************
public void actionPerformed(ActionEvent e)
{
iHale Waihona Puke (e.getSource()==kaiShiYouXi)
private JCheckBoxMenuItem cJianDan,cPuTong,cKunNan;
private int length = 6;
private Toolkit toolkit;
private int i,x,y,z,objectX,objectY,object=0,growth=0,time;//bojectX,Y为食物坐标,z为蛇前进方向
{
object=0;
growth=1;
toolkit.beep();
}
//****************产生食物坐标**********************
if(object==0)
{
object=1;
nanDuMenu.add(cPuTong);
nanDuMenu.add(cKunNan);
//******************设置分数菜单***************
fenShuMenu.add(fenShuItem);
//*****************设置游戏菜单****************
{
JOptionPane.showMessageDialog(this, "北京java编程爱好者制作"+"\n\n"+" "+"QQ号:860695120"+"\n");

初学JAVA 好玩的打架小游戏代码 -

初学JAVA 好玩的打架小游戏代码 -
+ "into your turn?");
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 +

新人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 = 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简易小游戏制作代码

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实现的打地鼠小游戏完整示例【附源码下载】

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. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

连连看java源代码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<j){ //如果第二个按钮的Y坐标小于空按钮的Y坐标说明第一按钮在第二按钮右边for (i=y+1;i<=j ;i++ ){ //判断第二按钮左侧直到第一按钮中间有没有按钮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<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();}}}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 (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 (x==i) {rowPassOne();}}if (k==2){if (y0==y) {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();}}}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<j){ //第一按钮同行空按钮在与第二按钮之间for (i=y0+1;i<=j ;i++){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 (x0<i) {for (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。

相关文档
最新文档