java小游戏源代码

合集下载

java小游戏连连看源代码

java小游戏连连看源代码

JAVA小游戏报告院别电子信息工程专业计算机科学与技术班级01班学号121040210116姓名姚银杰西安思源学院教务处制二零一四年连连看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。

初学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);}}。

java打字小游戏源码_java实现快速打字游戏

java打字小游戏源码_java实现快速打字游戏

java打字⼩游戏源码_java实现快速打字游戏本⽂实例为⼤家分享了java实现打字游戏的具体代码,供⼤家参考,具体内容如下import java.util.Random;import java.util.Scanner;public class Game {public Game(Player player) {}public Game() {}public String printStr(Player player) {StringBuffer a=new StringBuffer();for(int i=0;iint num=(int)(Math.random()*(7));switch(num) {case 1:a.append(">");break;case 2:a.append("break;case 3:a.append("+");break;case 4:a.append("-");break;case 5:a.append("*");break;case 6:a.append("/");break;case 0:break;}}String str=a.toString();System.out.println(str);return str;}public void printResult(Player player) {String num1=this.printStr(player);Scanner input=new Scanner(System.in);player.setStartTime();String num2=input.next();long currentTime=System.currentTimeMillis();player.setElapsedTime(currentTime,player.getStartTime());if (num1.equals(num2)) {if ((currentTime-player.getStartTime())/1000>LevelParam.levels[player.getLevelNo()-1].getTimeLimit()) {System.out.println("你输⼊太慢了,输⼊超时,退出。

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小程序源代码

一个Java小程序源代码(反转字符串)//BorderLayoutTest.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;import javax.swing.event.*;public class test1{public static void main(String[] args){cloneFrame frame = new cloneFrame();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.show();}}class cloneFrame extends JFrame{public cloneFrame(){setTitle("机试程序");setSize(600, 400);JPanel buttonPanel = new JPanel();buttonPanel.setBackground(new Color(56,43,85));Button1 = new JButton("点击复制反转字符串");Button1.addActionListener(new turnListener());buttonPanel.add(Button1);JPanel textPanel = new JPanel();textPanel.setBackground(new Color(100,100,100));field1 = new JTextField("姓名:老孙;学号:2004132028", 20);field2 = new JTextField("反转", 20);field2.setEditable(false);textPanel.add(field1);textPanel.add(field2);JPanel tuPanel = new JPanel();JLabel label = new JLabel(new ImageIcon("006.gif"));tuPanel.add(label);tuPanel.setBackground(new Color(100,100,100));Container contentPane = getContentPane();contentPane.add(buttonPanel, BorderLayout.SOUTH);contentPane.add(textPanel, BorderLayout.NORTH);contentPane.add(tuPanel, BorderLayout.CENTER);contentPane.setBackground(new Color(100,100,100));}private class turnListenerimplements ActionListener{public void actionPerformed(ActionEvent event){String gets = field1.getText();int i = gets.length();StringBuffer buffer = new StringBuffer(i);for(int j=i-1;j>=0;j--){buffer.append(gets.charAt(j));}String gets2 = buffer.toString();field2.setText(gets2);}}Container contentPane = getContentPane();contentPane.add(buttonPanel, BorderLayout.SOUTH);contentPane.add(textPanel, BorderLayout.NORTH);contentPane.add(tuPanel, BorderLayout.CENTER);contentPane.setBackground(new Color(100,100,100)); }private class turnListenerimplements ActionListener{public void actionPerformed(ActionEvent event){String gets = field1.getText();int i = gets.length();StringBuffer buffer = new StringBuffer(i);for(int j=i-1;j>=0;j--){buffer.append(gets.charAt(j));}String gets2 = buffer.toString();field2.setText(gets2);}}private JButton Button1;private JTextField field1;private JTextField field2;}Java1package com.kenki.emp;import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;import java.sql.SQLException;import java.sql.*;public class emp extends HttpServlet {private static final String CONTENT_TYPE = "text/html; charset=GBK";//Initialize global variablespublic void init() throws ServletException {}//Process the HTTP Get requestpublic void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {response.setContentType(CONTENT_TYPE);PrintWriter out = response.getWriter();String code = request.getParameter("code");String name = request.getParameter("name");String pay = request.getParameter("pay");System.out.println("empcode:" + code);System.out.println("name:" + name);System.out.println("pay:" + pay);//创建驱动new com.microsoft.jdbc.sqlserver.SQLServerDriver();String strd ="jdbc:microsoft:sqlserver://localhost:1433;databasename=emp_dates"; String username = "sa";String pws = "";try {java.sql.Connection conn = java.sql.DriverManager.getConnection( strd, username, pws);String strs = "insert into emp values(?,?,?)";java.sql.PreparedStatement pre = conn.prepareStatement(strs);pre.setString(1, code);pre.setString(2, name);pre.setString(3, pay);pre.execute();pre.close();conn.close();//重定向至查询页面out.println("成功保存!!");response.sendRedirect("emp.html");} catch (SQLException ss) {ss.printStackTrace();response.sendRedirect("/WebModule1/error.html");}}//Process the HTTP Post requestpublic void doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {doGet(request, response);}//Clean up resourcespublic void destroy() {}}Java2-聊天程序//这是个聊天程序,在ECLIPSE 运行 Client.java 就可以了。

Java语言实现拼图游戏源代码

Java语言实现拼图游戏源代码

Java语言实现拼图游戏源代码/** JA V A小游戏-拼图我做的第一个小游戏* Cell类是继承的按钮类,并加上相应图形,形成方格*MyCanvas是一个面板,加载Cell类的对象〔方格〕,是这三个类中的核心*/import java.awt.Rectangle;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JOptionPane;import javax.swing.JPanel;import java.awt.BorderLayout;import java.awt.Button;import java.awt.Choice;import java.awt.Color;import java.awt.Container;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.Icon;import javax.swing.JButton;public class MyMainFrame extends JFrame implements ActionListener { MyCanvas myCanvas;JPanel panelNorth,panelPreview;//定义上方的面板,及预览所需的面板Button start,preview,set;//定义开始,预览,设定按钮Container container;//容器,得到内容面板public MyMainFrame() {//初使化container=this.getContentPane();start=new Button("开始");start.addActionListener(this);preview=new Button("预览");preview.addActionListener(this);set = new Button("设置");set.addActionListener(this);panelPreview=new JPanel();panelPreview.setLayout(null);Icon icon=new ImageIcon("pic_"+MyCanvas.pictureID+".jpg");JLabel label=new JLabel(icon);label.setBounds(0,0,300,300);panelPreview.add(label);panelNorth=new JPanel();panelNorth.setBackground(Color.red);panelNorth.add(start);panelNorth.add(preview);panelNorth.add(set);myCanvas=new MyCanvas();container.add(myCanvas,BorderLayout.CENTER);container.add(panelNorth,BorderLayout.NORTH);this.setTitle("拼图小游戏-明");this.setLocation(300,200);this.setSize(308,365);this.setResizable(false);this.setVisible(true);this.setDefaultCloseOperation(3);}public static void main(String[] args) {// TODO 自动生成方法存根new MyMainFrame();}public void actionPerformed(ActionEvent arg0) {//对三个按钮事件的处理// TODO 自动生成方法存根Button button=(Button)arg0.getSource();if(button==start){myCanvas.Start();}else if(button==preview){if(button.getLabel()=="预览"){container.remove(myCanvas);container.add(panelPreview);panelPreview.updateUI();container.repaint();button.setLabel("返回");}else{container.remove(panelPreview);container.add(myCanvas);container.repaint();button.setLabel("预览");}}else if(button==set){//修改所选图片Choice pic = new Choice();pic.add("小猫");pic.add("小猪");pic.add("云");pic.add("QQ");pic.add("卡通");pic.add("花");int i=JOptionPane.showConfirmDialog(this, pic, "选择图片", JOptionPane.OK_CANCEL_OPTION);if(i==JOptionPane.YES_OPTION){MyCanvas.pictureID=pic.getSelectedIndex()+1;myCanvas.reLoadPictrue();Icon icon=new ImageIcon("pic_"+MyCanvas.pictureID+".jpg");JLabel label=new JLabel(icon);label.setBounds(0,0,300,300);panelPreview.removeAll();panelPreview.add(label);panelPreview.repaint();}}}}class MyCanvas extends JPanel implements MouseListener {boolean hasAddActionListener=false;//设置方格的动作监听器的标志位,TRUE为已经添加上动作事件,FALSE是尚未添加动作事件Cell cell[];//定义方格Rectangle cellNull;//定义空方格区域public static int pictureID=1;//当前选择的图片代号public MyCanvas() {this.setLayout(null);this.setSize(400,400);cellNull=new Rectangle(200,200,100,100);//空方格区域在第三行每三列cell=new Cell[9];Icon icon;for (int i = 0; i < 3; i++) {//为9个方格加载图片,并初使化坐标,形成三行三列for(int j=0;j<3;j++){icon=new ImageIcon("pic_"+pictureID+"_"+(i*3+j+1)+".jpg");cell[i*3+j]=new Cell(icon);cell[i*3+j].setLocation(j*100,i*100);this.add(cell[i*3+j]);}}this.remove(cell[8]);//移除最后一个多余的方格}文章转自上海青大实训:。

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小游戏连连看源代码[教学]

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]=newJButton(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.getT ext())));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疯狂java简介疯狂Java是广州为学教育科技有限公司(原广州捷途教育科技有限公司)旗下品牌,由李刚老师、肖文吉老师联合创建,作为一家专注于javaEE和3G/4G技术的专业培训服务机构,疯狂Java怀抱“软件强国”的理想,立志以务实的技术来改变中国的软件教育。

java小游戏源代码教学文案

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简易⼩游戏制作代码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文件: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小程序源代码

一个Java小程序源代码(反转字符串)//BorderLayoutTest.javaimport java.awt.*;import java.awt.eve nt.*;import javax.swi ng.*;import javax.swi ng.border.*;import javax.swi ng.eve nt.*;public class test1{public static void main(String[] args){cion eFrame frame = new cion eFrame();frame.setDefaultCloseOperatio n( JFrame.EXIT_ON_CLOSE);frame.show();}}class cion eFrame exte nds JFrame{public cion eFrame()setTitle("机试程序");setSize(600, 400);JPa nel butt onPanel = new JPa nel();butto nPan el.setBackgrou nd( new Color(56,43,85));Button1 = new JButton(”点击复制反转字符串");Butt on 1.addActio nListe ner(new turnListe ner());butto nPa nel.add(Butto n1);JPa nel textPa nel = new JPa nel();textPa nel.setBackgrou nd(new Color(100,100,100));field1 = new JTextField(" 姓名:老孙;学号:2004132028", 20);field2 = new JTextField(" 反转", 20);field2.setEditable(false);textPa nel.add(field1);textPa nel.add(field2);JPa nel tuPa nel = new JPa nel();JLabel label = new JLabel (new Imagelc on ("006.gif"));tuPa nel.add(label);tuPa nel.setBackgrou nd( new Color(100,100,100));Container conten tPa ne = getC onten tPa ne();conten tPa ne.add(butto nPa nel, BorderLayout.SOUTH);con te ntPa ne.add(textPa nel, BorderLayout.NORTH);co nte ntPa ne.add(tuPa nel, BorderLayout.CENTER);con te ntPa ne.setBackgrou nd(new Color(100,100,100));} private class tur nListe nerimpleme nts Acti on Liste ner{public void actio nPerformed(Actio nEve nt eve nt){String gets = field1.getText();int i = gets」en gth();Stri ngBuffer buffer = new Stri ngBuffer(i);for(i nt j二i-1;j>=0;j--)buffer.appe nd(gets.charAt(j));String gets2 = buffer.toString();field2.setText(gets2);Container conten tPa ne = getC onten tPa ne();conten tPa ne.add(butto nPanel, BorderLayout.SOUTH);con te ntPa ne.add(textPa nel, BorderLayout.NORTH);co nte ntPa ne.add(tuPa nel, BorderLayout.CENTER);co nte ntPa ne.setBackgrou nd(new Color(100,100,100)); }private class tur nListe nerimpleme nts Acti on Liste ner public void actionPerformed(Actio nEve nt eve nt)String gets = field1.getText();int i = gets」en gth();Stri ngBuffer buffer = new Stri ngBuffer(i);for(i nt j二i-1;j>=0;j--){buffer.appe nd(gets.charAt(j));}String gets2 = buffer.toString();field2.setText(gets2);}}private JButton Button1;private JTextField field1;private JTextField field2;}Javalpackage com.ke nki.emp;import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;import java.sql.SQLExceptio n;import java.sql.*;public class emp exte nds HttpServlet { private static final Stri ng CONTENT_TYPE = "text/html; charset=GBK";//In itialize global variablespublic void init() throws ServletException {}//Process the HTTP Get request public void doGet(HttpServletRequest request, HttpServletResp onseresp on se) throwsServletExcepti on, I OExceptio n { respo nse.setCo ntentType(CONTENT_TYPE);Prin tWriter out = resp on se.getWriter();Stri ng code = request.getParameter("code");Stri ng n ame = request.getParameter(” name");Stri ng pay = request.getParameter("pay");System.out.pri ntl n("empcode:" + code);System.out.pri ntl n(" name:" + n ame);System.out.pri ntl n("pay:" + pay);//创建驱动new com.microsoft.jdbc.sqlserver.SQLServerDriver();Stri ng strd ="jdbc:microsoft:sqlserver://localhost:1433;database name=emp_dates"; Stri ng user name = "sa";Stri ng pws ="";try {java.sql.Connection conn = java.sql.DriverManager.getConnection( strd, user name, pws);Stri ng strs = "in sert into emp values(?,?,?)";java.sql.PreparedStateme nt pre = conn .prepareStateme nt(strs); pre.setStri ng(1, code);pre.setStri ng(2, n ame);pre.setStri ng(3, pay); pre.execute();//重定向至查询页面out.pri ntln(” 成功保存!!");resp on se.se ndRedirect("emp.html");} catch (SQLExcepti on ss) {ss.pri ntStackTrace();resp on se.se ndRedirect("/WebModule1/error.html");}//Process the HTTP Post requestpublic void doPost(HttpServletRequest request, HttpServletResp onse resp on se) throwsServletExcepti on, I OExceptio n {doGet(request, resp on se);}//Clea n up resourcespublic void destroy() {连接是:Java2-聊天程序//这是个聊天程序, 在ECLIPSE 运行Client.java 就可以了 localhost//Server 代码,package message;import java.io.*;import java .n et.*;import java.util.*;public class Server { public static void main(String[] args) throws Exception{ System.out.pri nt("Server");ServerSocket socket=new ServerSocket(8888);Vector v=new Vector();while(true){Socket sk=socket.accept();Datal nputStream in=new Datal nputStream(sk.getl nputStream()); DataOutputStream out=new DataOutputStream(sk.getOutputStream()); v.add(sk);new ServerThread(i n, v).start();//ServerThread.java 代码package message; import java .n et.*;import java.io.*;import java.util.*;public class ServerThread exte nds Thread{DataInputStream in;Vector all;public ServerThread(Data In putStream in, Vector v){ this.i n=in;public void run()try{Stri ng s1=i n.readUTF();for(int i=O;i<all.size();i++){Object obj=all.get(i);Socket socket=(Socket)obj; DataOutputStream out=newDataOutputStream(socket.getOutputStream()); out.writeUTF(s1);System.out.pri nt(i);out.flush();}System.out.pri nt("Message send over!");}catch(Excepti on e){e.pri ntStackTrace();};package message;import java.awt.*;import java.awt.eve nt.*;import javax.swi ng.*;import java .n et.*;import java.io.*;public class Clie ntFrame exte nds JFrame impleme nts Actio nListe ner{JButton b1= new JButton ("Se ndMessage");JButton b2=new JButt on ("L ink Server");JTextField t1= new JTextField(20);JTextField t2=new JTextField(20);JLabel l=new JLabel(" 输入服务器名字:");JTextArea area=new JTextArea(10,20);JPanel p1= new JPanel();JPa nel p2=new JPa nel();JPanel p3=new JPa nel();JPanel p4=new JPan el();Socket socket;this.getC on te ntPa ne().add(p1); p2.add( new JScrollPa ne(area)); p3.add(t1);p4.add(b2);p2.setLayout(new FlowLayout());p3.setLayout(new FlowLayout());p4.setLayout(new FlowLayout());p1.setLayout (new BorderLayout()); p1.add("North",p2);p1.add("Ce nter",p3);p1.add("South",p4);bl.addActi on Liste ner(this);b2.addActio nListe ner(this);this.pack();Java3 -猜数字游戏/*1、编写一个猜数字的游戏,由电脑随机产生一个 100以内的整数,让用户去猜,如果用户猜的比电脑大,贝U输出“大了,再小点!”,反之则输出“小了,再大点!” ,用户总共只能猜十次,并根据用户正确猜出答案所用的次数输出相应的信息,女口:只用一次就猜对,输出“你是个天才!”,八次才猜对,输出“笨死了!”,如果十次还没有猜对,则游戏结束!*/import java.util.*;import java.io.*;public class CaiShu{public static void main( Stri ng[] args) throws IOExceptio n{Ran dom a=new Ran dom();int num=a. nextl nt(100);System.out.println(” 请输入一个 100 以内的整数:");for (int i=0;i<=9;i++){BufferedReader bf=new BufferedReader( newIn putStreamReader(System.i n));Stri ng str=bf.readL in e();int shu=ln teger.parse In t(str);if (shu >num)System.out.pri ntl n(”输入的数大了,输小点的!");else if (shu vnum)System.out.pri ntl n(”输入的数小了,输大点的!");else {System.out.pri ntln(”恭喜你,猜对了!");if (i<=2)System.out.pri ntln(”你真是个天才!");else if (i<=6)System.out.pri ntln(”还将就,你过关了!");else if (i<=8)System.out.println(”........... 但是你还真笨!”);elseSystem.out.pri ntl n("你和猪没有两样了!");break;}}package GuessNumber;import java.io.*;import java.io.BufferedWriter;public class GuessNumber {public void show() {Data In putStream stdi n = new Datal nputStream(System.i n);BufferedI nputStream buffi n = new BufferedI nputStream(stdi n);number = (int) (Math.ra ndom() * 10000);try {while (flag) {System.out.pri ntln(”产生的随机数是:"+n umber);System.out.println(”这是一个猜数字的小游戏,请您输入一个从0到10000的数字!");in put = std in. readL in e();// guess nu mber =ln teger.parse In t(i nput);/*if(Character.isLetter(guess nu mber)){"); flag=true; } "); flag=true; } System.out.println(" 你输入的不是数字,请输入一个数字!*/ /** if(!Character.isDigit(input)){* System.out.println(" 你输入的不是数字,请输入一个数字!*/guessnumber = Integer.parseInt(input);// guessnumber=Integer.valueOf(stdin.readLine()).intValue();System.out.println(" 你输入的数是: " + guessnumber);{if (number < guessnumber)System.out.println(" 你输入的数大了请重新输入 !");if (number > guessnumber)System.out.println(" 你输入的数小了请重新输入! "); count++;flag = true;}if (number == guessnumber) {System.out.println(" 你真历害这么快你就猜对了 !");System.out.println(" 你一共猜了 " + count + " 次 "); flag = false; System.out.println(" 请输入你的名字: ");String name = stdin.readLine();byte names[] = name.getBytes("ISO-8859-1"); userName = new String(names); System.out.println(" 姓名: " + userName); System.out.println(" 记录是: " + count + " 次"); SaveFile save = new SaveFile();save.output(userName, 0, userName.length());}// guessnumber=Integer.parseInt(stdin.readLine());}stdin.close();buffin.close();} catch (IOException e) { e.getMessage();// e.toString();System.out.println(" 产生了异常! ");}}public static void main(String[] args) {GuessNumber gus = new GuessNumber();gus.show();/** catch(IOException e){}*/}private static String input;用户开始输入数字或字母// private static int number;产生的随机数// private static int用户输入的的数字guessnumber;// private用统计用户猜的次数static int count = 0; //标记继续输入数字进行猜private boolean flag = true;用来记录猜对的用户名字// private String userName;class SaveFile {//// 这个方法是将传过来的名字写入文件里}public void output(String name, int a, intlength) {try {FileWriter sout = new FileWriter("Gamererecord.txt");BufferedWriter out = new BufferedWriter(sout);sout.write(name, 0, length);sout.close();out.close();} catch (IOExcepti on e) {System.out.pri ntln ("IO Error" + e);可以直接出结果的,不过你得先建立一个名为GuessNumber的包,在此包下建立一个名为GuessNumber的类,然后将些段代码粘贴进来根据提示就可以出结果的JAVA小游戏代码 int player1wi n,player2wi n;protected synchroni zed void keyPressed(i nt keyCode){ else if(action == Canvas.FIRE){ if(chesses[selectedY][selectedX]==null){ chesses[selectedY][ selectedX]=new Chesses(this.isPlayer1); if(checkWin()){String winner;if(isPlayer1){winner=" 白方胜利 "; player1win++;}else{winner=" 红方胜利 "; player2win++;}try{Thread.sleep(3000); }catch(Exception e){}Alert winAlert=new Alert("",winner+"\n 白方 "+player1win+":"+player2win+" 红方 " null,); winAlert.setTimeout(Alert.FOREVER); Display.getDisplay(gobang).setCurrent(winAlert,this); init(); repaint();}this.isPlayer=!this.isPlayer1;// 切换下棋方}}repaint();}private boolean checkWin(){int num=1;if(num<5){num=1;for(int i=1;i<4;i++){ if(isPlayer1(selectedX-i,selectedY)){ num++; }ease break;}for(int i=1;i<4;i++){ if(isPlayer1(selectedX+1,selectedY)){num++;}else break;}}if(num<5){num=1;for(int i=1;i<4;i++){if(isPlayer1(selectedX-i,selectedY)){ num++;}ease break;}for(int i=1;i<4;i++){if(isPlayer1(selectedX+1,selectedY)){ num++;}else break;}} if(num<5{ num=1;for(int i=1;i<=4;i++){ if(isPlayer1(sesectedX,selectedY-i)){ num++; }ease break;}for(int i=1;i<=4;i++){if(isPlayer1(selectedX.,selectedY+i)) num++;else break;}}if(num<5){num=1;for(int i=1;i<=4;i++){ if(isPlayer1(selectedX+i,selectedY-i)) num++; else break;}for(int i=1;i<=4;i++){if(isPlayer1(selectedX-i,selectedY+i)) num++;else break;}}if(num >=5)return true;elsereturn false;}private boolea n isPlayer1(i nt y,i nt x){if(x<=15 && x>=0 && y<=15 && y>=0 && chesses[x][y]!=n ull){ if(chesses[x][y].isPlayer1==this.isPlayer1)return true;elsereturn false;}else return fale;}JAVA计算器源代码import java.awt.*;import java.awt.eve nt.*;import java .Ian g.*;import javax.swi ng.*;public class Coun ter exte nds Frame{//声明三个面板的布局GridLayout gl1,gl2,gl3;Panel p0,p1,p2,p3;JTextField tf1;TextField tf2;Butt onb0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,b1 9,b20,b21,b22,b23,b24,b25,b26;Stri ngBuffer str;// 显示屏所显示的字符串double x,y;//x 和y都是运算数int乙//Z 表示单击了那一个运算符.0表示"+",1表示"-",2表示"*",3表示"/" static double m;// 记忆的数字public Coun ter(){gl仁new GridLayout(1,4,10,0);〃实例化三个面板的布局gl2=new GridLayout(4,1,0,15);gl3=new GridLayout(4,5,10,15);tf1= new JTextField(27);〃显示屏tfl.setHorizo ntalAlig nmen t(JTextField.RIGHT); tfl.setE nabled(false); tf1.setText("0");tf2=n ew TextField(10);〃显示记忆的索引值tf2.setEditable(false);//实例化所有按钮、设置其前景色并注册监听器b0=new Butt on ("Backspace");b0.setForegro un d(Color.red);b0.addActio nListe ner(n ew Bt());b1= new Butto n("CE");b1.setForegro un d(Color.red);b1.addActi on Liste ner(new Bt());b2=new Butto n("C");b2.setForegro un d(Color.red);b2.addActio nListe ner(n ew Bt());b3=new Butto n("MC");b3.setForegro un d(Color.red);b3.addActio nListe ner(n ew Bt());b4=new Butto n( "MR");b4.setForegro un d(Color.red);b4.addActi on Liste ner(new Bt());b5=new Button("MS");b5.setForegro un d(Color.red); b5.addActio nListe ner(new Bt()); b6=new Button("M+");b6.setForegro un d(Color.red); b6.addActio nListe ner( new Bt()); b7=new Butt on ("7");b7.setForegro un d(Color.blue); b7.addActio nListe ner(new Bt()); b8=new Butt on ("8");b8.setForegro un d(Color.blue); b8.addActio nListe ner(n ew Bt()); b9=new Butt on ("9");b9.setForegro un d(Color.blue); b9.addActio nListe ner( new Bt()); b10=new Butto n("/"); b10.setForegro un d(Color.red); b10.addActio nListe ner(new Bt()); b1 仁new Butt on ("sqrt"); b11.setForegro un d(Color.blue);b11.addActio nListe ner(new Bt()); b12=new Butt on ("4");b12.setForegro un d(Color.blue);b12.addActio nListe ner(new Bt()); b13=new Butt on ("5"); b13.setForegro un d(Color.blue);b13.addActio nListe ner(new Bt()); b14=new Butt on ("6"); b14.setForegro un d(Color.blue);b14.addActio nListe ner(new Bt()); b15=new Button("*"); b15.setForegro un d(Color.red);b15.addActio nListe ner(new Bt()); b16=new Butt on ("%"); b16.setForegro un d(Color.blue);b16.addActio nListe ner(new Bt()); b17=new Butto n("1"); b17.setForegro un d(Color.blue);b17.addActio nListe ner(new Bt()); b18=new Butto n("2"); b18.setForegro un d(Color.blue);b18.addActio nListe ner(new Bt()); b19=new Butt on ("3"); b19.setForegro un d(Color.blue);b19.addActio nListe ner(new Bt());b20=new Butto n("-"); b20.setForegro un d(Color.red); b20.addActio nListe ner(new Bt());b2 仁new Butto n("1/X"); b21.setForegro un d(Color.blue); b21.addActio nListe ner(new Bt());b22=new Butt on ("0"); b22.setForegro un d(Color.blue); b22.addActio nListe ner(new Bt());b23=new Butto n("+/-"); b23.setForegro un d(Color.blue); b23.addActio nListe ner(new Bt());b24=new Butt on ("."); b24.setForegro un d(Color.blue); b24.addActio nListe ner(new Bt());b25=new Butt on ("+"); b25.setForegro un d(Color.red); b25.addActio nListe ner(new Bt());b26=new Butt on ("="); b26.setForegro un d(Color.red); b26.addActio nListe ner(new Bt());p1= new Pan el();p2=new Pan el();p3=new Pan el();//创建一个空字符串缓冲区str=new Stri ngBuffer();//添加面板p0中的组件和设置其在框架中的位置和大小pO.add(tfl);pO.setBou nds(10,25,300,40);//添加面板p1中的组件和设置其在框架中的位置和大小p1.setLayout(gl1);p1.add(tf2);p1.add(b0);p1.add(b1);p1.add(b2);p1.setBou nds(10,65,300,25);//添加面板p2中的组件并设置其的框架中的位置和大小p2.setLayout(gl2); p2.add(b3);p2.setBou nds(10,110,40,150);//添加面板p3中的组件并设置其在框架中的位置和大小p3.setLayout(gl3);〃设置 p3 的布局p3.add(b7);p3.add(b8);p3.add(b9);p3.add(b10);p3.add(b14);p3.add(b15);p3.add(b16);p3.add(b17);p3.add(b18);p3.add(b19);p3.add(b20);p3.add(b21); p3.add(b22);p3.add(b26);p3.setBou nds(60,110,250,150);//设置框架中的布局为空布局并添加4个面板setLayout (n ull);add(p0);add(p1);add(p2);add(p3);setResizable(false);// 禁止调整框架的大小//匿名类关闭窗口addWi ndowListe ner(new Win dowAdapter(){ public void win dowClos in g(Wi ndowEve nt e1){System.exit(0);}});setBackgro un d(Color.lightGray); setBou nds(100,100,320,280); setVisible(true);class Bt impleme nts Actio nListe ner{ public void actio nPerformed(Actio nEve nt e2) try{if(e2.getSource()==b1)〃选择"CE"清零{tf1.setText("0");〃把显示屏清零str.setLe ngth(0);〃清空字符串缓冲区以准备接收新的输入运算数}else if(e2.getSource()==b2)〃选择"C"清零{tf1.setText("0");〃把显示屏清零str.setLe ngth(0);}else if(e2.getSource()==b23)〃单击"+/-"选择输入的运算数是正数还是负数{x=Double.parseDouble(tf1.getText().trim());值{x=Double.parseDouble(tf1.getText().trim());str.setLe ngth(O);//清空缓冲区以便接收新的另一个运算数y=Od;z=0;}else if(e2.getSource()==b20)〃 单击减号按钮获得x 的值和z 的值并清空y 的 值{x=Double.parseDouble(tf1.getText().trim());str.setLe ngth(0);y=0d;z=1;} elseif(e2.getSource()==b15)〃单击乘号按钮获得x 的值和z 的值并清空y 的 值{x=Double.parseDouble(tf1.getText().trim());}else if(e2.getSource()==b10)〃单击除号按钮获得x的值和z的值并空y的值{x=Double.parseDouble(tf1.getText().trim());str.setLe ngth(0);y=0d;z=3;}else if(e2.getSource()==b26)〃单击等号按钮输出计算结果{str.setLe ngth(0);switch(z){case 0 : tf1.setText(""+(x+y));break;case 1 : tf1.setText(""+(x-y));break;case 2 : tf1.setText(""+(x*y));break;case 3 : tf1.setText(""+(x/y));break;else if(e2.getSource()==b24)〃单击"."按钮输入小数{if(tf1.getText().trim().indexOf( ' )!=-1)〃判断字符串中是否已经包含了小数点{{if(tf1.getText().trim().equals("0"))〃如果初时显示为 0tf1.setText((str.appe nd("0"+e2.getActio nComma nd())).toStri ng());}else if(tf1.getText().trim().equals(""))〃如果初时显示为空则不做任何操作{}else{tf1.setText(str.appe nd(e2.getActio nComma nd()).toStri ng());。

Java游戏源代码

Java游戏源代码

Java游戏源代码import java.awt.*;import java.awt.event.*;import javax.swing.*;public class MyClass {public static void main(String args[]){JFrame w = new JFrame();w.setSize(800,600);BallPanel bp=new BallPanel();w.add(bp);w.addMouseListener(bp);bp.addMouseListener(bp);w.addMouseMotionListener(bp);bp.addMouseMotionListener(bp);Thread t=new Thread(bp);t.start();w.show();}}class BallPanel extends JPanel implements Runnable,MouseListener,MouseMotionListener{private int x=30;private int y=30;private int flag=0;private int count=0;private int point[][]=new int[1000][4];public void paint(Graphics g){super.paint(g);g.fillOval(x, y, 20, 20);for(int i=0;i<count+1;i++)g.fillRect(point[i][0],point[i][1],point[i][2]-point[i][0],point[i][3]-point[i][1]);}public void mousePressed(MouseEvent m) {point[count][0]=m.getX();point[count][1]=m.getY();}public void run(){while(true){if(flag==0){x++;y++;if(x>760){flag=1;}if(y>540){flag=3;}for(int i=0;i<count;i++){if((y==point[i][1])&&x>=point[i][0]&&x<=point[i][2]) {flag=3;}if((x==point[i][0])&&y>=point[i][1]&&y<=point[i][3]) {flag=1;}}}if(flag==1){x--;y++;if(x<0){flag=0;}if(y>540){flag=2;}for(int i=0;i<count;i++){if((x==(point[i][2]))&&y>=point[i][1]&&y<=point[i][3]){flag=0;//System.out.println("aaaa");}if((y==point[i][1])&&x>=point[i][0]&&x<=point[i][2]) {flag=2;//System.out.println("bbb");}}}if(flag==2){x--;y--;if(x<0){flag=3;}if(y<0){flag=1;}for(int i=0;i<count;i++){if((y==point[i][3])&&x>=point[i][0]&&x<=point[i][2]) {flag=1;}if((x==point[i][2])&&y>=point[i][1]&&y<=point[i][3]) {flag=3;}}}if(flag==3){x++;y--;if(y<0){flag=0;}if(x>760){flag=2;}for(int i=0;i<count;i++){if((y==point[i][3])&&x>=point[i][0]&&x<=point[i][2]) {flag=0;}if((x==point[i][0])&&y>=point[i][1]&&y<=point[i][3]) {flag=2;}}}try{Thread.sleep(5);}catch(Exception e){}repaint();}}public void mouseReleased(MouseEvent arg0) {count++;}public void mouseEntered(MouseEvent arg0) {}public void mouseExited(MouseEvent arg0) {}public void mouseClicked(MouseEvent arg0) {}public void mouseMoved(MouseEvent arg0) {}public void mouseDragged(MouseEvent m) {point[count][2]=m.getX(); point[count][3]=m.getY(); r</count;i++)</count;i++)</count;i++)</count;i++)</count+1;i++)epaint();}}。

java小程序源代码

java小程序源代码
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*;
class CalculatorPanel extends JPanel implements ActionListener {
//
}
//
//
});
Container contentPane=getContentPane();
} }
contentPane.add(new CalculatorPanel());
public class Calculator_2 { public static void main(String[] args) { JFrame frame=new CalculatorFrame(); frame.show(); Calculator_2 a=new Calculator_2(); } }
class CalculatorFrame extends JFrame {
public CalculatorFrame() {
setTitle("Calculator"); setLocation(500,200); setSize(200,200); setResizable(true);
//关闭窗口事件响应,有两种方法
view.add(newItem); view.add(newItem2); view.add(newItem3);
help.add(newItem4); newItem4.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

j a v a小游戏源代码 Document number:NOCG-YUNOO-BUYTT-UU986-1986UT
Java小游戏
第一个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[]=new
int[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++;
else
midright++;
}
}
}
}
void print()
{
" A "+right+" B "+midright);
}
}。

相关文档
最新文档