最新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源代码完整版

游戏贪吃蛇的JAVA源代码一.文档说明a)本代码主要功能为实现贪吃蛇游戏,GUI界面做到尽量简洁和原游戏相仿。

目前版本包含计分,统计最高分,长度自动缩短计时功能。

b)本代码受计算机系大神指点,经许可后发布如下,向Java_online网致敬c)运行时请把.java文件放入default package 即可运行。

二.运行截图a)文件位置b)进入游戏c)游戏进行中三.JAVA代码import java.awt.*;import java.awt.event.*;import static ng.String.format;import java.util.*;import java.util.List;import javax.swing.*;public class Snake extends JPanel implements Runnable { enum Dir {up(0, -1), right(1, 0), down(0, 1), left(-1, 0);Dir(int x, int y) {this.x = x; this.y = y;}final int x, y;}static final Random rand = new Random();static final int WALL = -1;static final int MAX_ENERGY = 1500;volatile boolean gameOver = true;Thread gameThread;int score, hiScore;int nRows = 44;int nCols = 64;Dir dir;int energy;int[][] grid;List<Point> snake, treats;Font smallFont;public Snake() {setPreferredSize(new Dimension(640, 440));setBackground(Color.white);setFont(new Font("SansSerif", Font.BOLD, 48));setFocusable(true);smallFont = getFont().deriveFont(Font.BOLD, 18);initGrid();addMouseListener(new MouseAdapter() {@Overridepublic void mousePressed(MouseEvent e) {if (gameOver) {startNewGame();repaint();}}});addKeyListener(new KeyAdapter() {@Overridepublic void keyPressed(KeyEvent e) {switch (e.getKeyCode()) {case KeyEvent.VK_UP:if (dir != Dir.down)dir = Dir.up;break;case KeyEvent.VK_LEFT:if (dir != Dir.right)dir = Dir.left;break;case KeyEvent.VK_RIGHT:if (dir != Dir.left)dir = Dir.right;break;case KeyEvent.VK_DOWN:if (dir != Dir.up)dir = Dir.down;break;}repaint();}});}void startNewGame() {gameOver = false;stop();initGrid();treats = new LinkedList<>();dir = Dir.left;energy = MAX_ENERGY;if (score > hiScore)hiScore = score;score = 0;snake = new ArrayList<>();for (int x = 0; x < 7; x++)snake.add(new Point(nCols / 2 + x, nRows / 2));doaddTreat();while(treats.isEmpty());(gameThread = new Thread(this)).start();}void stop() {if (gameThread != null) {Thread tmp = gameThread;gameThread = null;tmp.interrupt();}}void initGrid() {grid = new int[nRows][nCols];for (int r = 0; r < nRows; r++) {for (int c = 0; c < nCols; c++) {if (c == 0 || c == nCols - 1 || r == 0 || r == nRows - 1)grid[r][c] = WALL;}}}@Overridepublic void run() {while (Thread.currentThread() == gameThread) {try {Thread.sleep(Math.max(75 - score, 25));} catch (InterruptedException e) {return;}if (energyUsed() || hitsWall() || hitsSnake()) {gameOver();} else {if (eatsTreat()) {score++;energy = MAX_ENERGY;growSnake();}moveSnake();addTreat();}repaint();}}boolean energyUsed() {energy -= 10;return energy <= 0;}boolean hitsWall() {Point head = snake.get(0);int nextCol = head.x + dir.x;int nextRow = head.y + dir.y;return grid[nextRow][nextCol] == WALL;}boolean hitsSnake() {Point head = snake.get(0);int nextCol = head.x + dir.x;int nextRow = head.y + dir.y;for (Point p : snake)if (p.x == nextCol && p.y == nextRow)return true;return false;}boolean eatsTreat() {Point head = snake.get(0);int nextCol = head.x + dir.x;int nextRow = head.y + dir.y;for (Point p : treats)if (p.x == nextCol && p.y == nextRow) {return treats.remove(p);}return false;}void gameOver() {gameOver = true;stop();}void moveSnake() {for (int i = snake.size() - 1; i > 0; i--) {Point p1 = snake.get(i - 1);Point p2 = snake.get(i);p2.x = p1.x;p2.y = p1.y;}Point head = snake.get(0);head.x += dir.x;head.y += dir.y;}void growSnake() {Point tail = snake.get(snake.size() - 1);int x = tail.x + dir.x;int y = tail.y + dir.y;snake.add(new Point(x, y));}void addTreat() {if (treats.size() < 3) {if (rand.nextInt(10) == 0) { // 1 in 10if (rand.nextInt(4) != 0) { // 3 in 4int x, y;while (true) {x = rand.nextInt(nCols);y = rand.nextInt(nRows);if (grid[y][x] != 0)continue;Point p = new Point(x, y);if (snake.contains(p) || treats.contains(p))continue;treats.add(p);break;}} else if (treats.size() > 1)treats.remove(0);}}}void drawGrid(Graphics2D g) {g.setColor(Color.lightGray);for (int r = 0; r < nRows; r++) {for (int c = 0; c < nCols; c++) {if (grid[r][c] == WALL)g.fillRect(c * 10, r * 10, 10, 10);}}}void drawSnake(Graphics2D g) {g.setColor(Color.blue);for (Point p : snake)g.fillRect(p.x * 10, p.y * 10, 10, 10);g.setColor(energy < 500 ? Color.red : Color.orange);Point head = snake.get(0);g.fillRect(head.x * 10, head.y * 10, 10, 10);}void drawTreats(Graphics2D g) {g.setColor(Color.green);for (Point p : treats)g.fillRect(p.x * 10, p.y * 10, 10, 10);}void drawStartScreen(Graphics2D g) {g.setColor(Color.blue);g.setFont(getFont());g.drawString("Snake", 240, 190);g.setColor(Color.orange);g.setFont(smallFont);g.drawString("(click to start)", 250, 240);}void drawScore(Graphics2D g) {int h = getHeight();g.setFont(smallFont);g.setColor(getForeground());String s = format("hiscore %d score %d", hiScore, score);g.drawString(s, 30, h - 30);g.drawString(format("energy %d", energy), getWidth() - 150, h - 30); }@Overridepublic void paintComponent(Graphics gg) {super.paintComponent(gg);Graphics2D g = (Graphics2D) gg;g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);drawGrid(g);if (gameOver) {drawStartScreen(g);} else {drawSnake(g);drawTreats(g);drawScore(g);}}public static void main(String[] args) {SwingUtilities.invokeLater(() -> {JFrame f = new JFrame();f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setTitle("Snake");f.setResizable(false);f.add(new Snake(), BorderLayout.CENTER);f.pack();f.setLocationRelativeTo(null);f.setVisible(true);});}}。

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⼩游戏代码(剪⼑⽯头布) /** 创建⼀个类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实现快速打字游戏

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

j a v a小游戏源代码 Document number:NOCG-YUNOO-BUYTT-UU986-1986UTJava小游戏第一个Java文件:import class GameA_B {public static void main(String[] args) {Scanner reader=new Scanner;int area;"Game Start…………Please enter the area:(1-9)" +'\n'+"1,2,3 means easy"+'\n'+"4,5,6 means middle"+'\n'+"7,8,9 means hard"+'\n'+"Please choose:");area=();switch((area-1)/3){case 0:"You choose easy! ");break;case 1:"You choose middle! ");break;case 2:"You choose hard! ");break;}"Good Luck!");GameProcess game1=new GameProcess(area);();}}第二个Java文件:import class GameProcess {int area,i,arrcount,right,midright,t;int base[]=new int[arrcount],userNum[]=newint[area],sysNum[]=new int[area];Random random=new Random();Scanner reader=new Scanner;GameProcess(int a){area=a;arrcount=10;right=0;midright=0;t=0;base=new int[arrcount];userNum=new int[area];sysNum=new int[area];for(int i=0;i<arrcount;i++){base[i]=i;// }}void process(){rand();while(right!=area){scanf();compare();print();check();}}void rand(){for(i=0;i<area;i++){t=(arrcount);//sysNum[i]=base[t];delarr(t);}}void delarr(int t){for(int j=t;j<arrcount-1;j++)base[j]=base[j+1];arrcount--;}void scanf(){"The system number has created!"+"\n"+"Please enter "+area+" Numbers");for(int i=0;i<area;i++){userNum[i]=();}}void check(){if(right==area)"You win…………!");}boolean check(int i){return true;}void compare(){int i=0,j=0;right=midright=0;for(i=0;i<area;i++){for(j=0;j<area;j++){if(userNum[i]==sysNum[j]){if(i==j)right++;elsemidright++;}}}}void print(){" A "+right+" B "+midright);}}。

java推箱子游戏源代码

java推箱子游戏源代码

}
/** * 设置内容面板 */ void initContentPane() {
zhuobu.setBackground(Color.red); zhuobu.setLayout(null);
//调用父类的属性和方法 super.setContentPane(zhuobu);
}
/** * 把某个图片以组件的方式加入窗体 * @param imgPath 图片路径
* @param x
x
* @param y * @param width
y 宽度
* @param height 高度
* @return
添加完的组件
*/
void addComponent(int tag, String imgPath, int x, int y) {
ImageIcon img = new ImageIcon(imgPath); //创建 JLabel 并把 ImageIcon 通过构造方法传参传入 //把食物放到盘子里
gameFrame.setResizable(false); gameFrame.setImgSize(48); gameFrame.addComponent(3, "workerUp.png", 400, 100); gameFrame.addComponent(1, "box.png", 160, 60); gameFrame.addComponent(2, "goal.png", 80, 520); int[][] wallLocations ={
for (int i = 0; i < walls.length; i++) { //创建没每一个围墙,他们使用的是同一个图片 walls[i] = new JLabel(wallImg);

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源代码

最新整理java游戏外挂Java源代码

Java代码package game;import java x.swing。

*;import java。

awt。

*;import java.awt。

event。

*;import java x.swing.event。

*;import ng。

*;import java.io。

*;//主类public class Action{static int TimeNumber=0;public static void main(String[]args) {ViewFlow vf=new ViewFlow();vf。

addActionlistener();}}Java代码package game;import java x。

swing。

*;import java.awt。

*;import java.awt。

event.*;import java x。

swing。

event.*; import ng.*;import java。

io.*;//主类public class Action{static int TimeNumber=0;public static void main(String[]args) {ViewFlow vf=new ViewFlow();vf。

addActionlistener();}}package game;import java x。

swing.*;import java。

awt。

*;import java。

awt.event.*;import java x。

swing.event.*;import ng。

*;import java.io.*;//主类public class Action{static int TimeNumber=0;public static void main(String[]args){ViewFlow vf=new ViewFlow();vf.addActionlistener();}}Java代码package game;import java x.swing。

java推箱子游戏源代码(含推箱子的判断)

java推箱子游戏源代码(含推箱子的判断)

第一个Java 文件:package ziaoA; import import import import j ava•awt•Color;java•awt•ReadiessException; j ava•awt•event•KeyEvent; j ava•awt•event•KeyListener ;import import importimport import j avaz•swing•Imageicon; j avax•swing•JFrame; j avax•swing•JLabel; j avax•swing•JOptionPane; j avax•swing•JPanel; public JPanel〃匸人 JLabel class GameFrame extends JFrame { zhuobu = new JPanel(); worker = null;//箱r JLabelbox = null; //目的地 JLabel goal = null; JLabel[] walls = null; public static final int SPEED = 12; //设s 图片人小 int imgSize = 48; public void setImgSize (int imgSize){ this •imgSize = imgSize; public GameFrame(String title) throws HeadlessException { super {title); //构造方法中调用本类的其它方法 this •initContentPane(); this •addKeyListener (new KeyListener() { //键盘按下爭件 public void keyPressed(KeyEvent e) { //E2.5]使匸人可以移动 int 次Speed = 0, ySpeed = 0; switch (e•getKeyCode()){case KeyEvent• VK LEFT :xSpeed = -SPEED;worker . seticon (new Imageicon {'* image / workerUp • gif'*)); break;case KeyEvent• VK」工GHT :xSpeed = SPEED;worker.seticon(new Imageicon("image/workerUp•gif")); break;case KeyEvent•VK_UP :ySpeed = -SPEED;worker . seticon (new Imageicon (image/workerUp . gif ")); break;case KeyEvent•VK_DOWN :ySpeed = SPEED;worker . seticon (new Imageicon {'* image/workerUp • gif'*)); break;default:return;worker • setBounds (x-zorker • getX () + KSpeed, worker • getY () + ySpeed, worker•getWidth(), worker•getHeight());//[2.7]判断匸人是否撞到墙壁for (int i = 0; i < walls.length; i++) {if (worker•getBounds{).intersects(walls[i].getBounds())) { worker • setBounds (x-zorker • getX () - :龙Speed, worker • getY () - ySpeed, worker•getWidth(), worker•getHeight());//E3.2]使I:人可以推动箱rif (worker•getBounds()•intersects(box•getBounds())){box•setBounds(box•getX() + xSpeed, box•getY () + ySpeed, box•getWidth(), box•getHeight());//[3.3]判断箱r是否撞到墙壁for (int i = 0; i < walls.length; i++) {if (box•getBounds()•intersects(walls[i].getBounds())) {worker•setBounds(worker•getX () - xSpeed, worker•getY () ySpeed, worker•getWidth(), worker•getHeight());box•setBounds(box•getX() - xSpeed, box•getY() - ySpeed, box•getWidth(), box•getHeight());//[3.4]判断是否胜利if (box•getX{)==goal•getX() && box•getY()==goal•getY()){JOptionPane > showMessageDialog(null, ”您贏啦!;public void keyReleased(KeyEvent e) {public void keyTyped(KeyEvent e) { }});*设置内容面板public void initContentPane() {zhuobu •setBackground(Color•red); zhuobu •setLayout (null);//调用父类的厲性和方法super •setcontentPane(zhuobu);public void addComponent (int tag. String imgPath, int x, int y) { Imageicon img = new Imageicon{imgPath); //创建JLabel^把工mage 工oon 通过构造方法传参传入〃把食物放到盘J"里JLabel componet = new JLabel(img);//设置盘f 在桌布上的位置和人小componet.setBounds(z, y, imgSize, imgSize);//把盘r 放到桌布上zhuobu •add(componet);switch (tag) {case 1:box = componet; break;case 2:*把某个图片以组件的力式加入窗体图片路径* @parain* Oparam* @param imgPath * Oparam 、* @param : * fireturn y width height y 宽度 拓度添加完的组件int index = 0;分别设置各个图片位置r(int i = 0; i < 14; i++) {//左边墙walls [index].setBounds(0, izhuobu •add (walls [index]); index++; //右边墙walls [index].setBounds(20 *for * imgSize , imgSize , imgSize );imgSize , i * imgSize , imgSize ,imgSize);zhuobu .add (walls [index]); index+-s-; for (int i = 0; i < 19; i++) {//上边墙walls [index].setBounds((i +1) * imgSize , 0, imgSize ,imgSize);zhuobu .add (walls [index]);index-5-+; //下边墙walls [index]•setBounds((i + 1) imgSize);zhuobu •add (walls [index]);inde:<++; * imgSize, 13 * imgSize, imgSize,goal = componet; break;case 3:worker = componet; break;for (int i = 0; i < walls .length; i++) {//创建没每■个闱墙,他们使用的是同 个图片walls [i] = new JLabel(walllmg);for (int i = 0; i < walls .length; i++) {//创建没每■个鬧墙,他们使用的是同■个图片walls [i] = new JLabel(walllmg);//添加中间障碍耦介解耦for (int i = 0; i < loactions.length; i++) {public void addWall(String Imageicon walllmg = new walls = new JLabel[66 +imgPath, int [][] loactions) {Imageicon(imgPath); loactions•length];walls[index]•setBounds(loactions[i][0]* imgSize, loactions[i][1]* imgSize, imgSize, imgSize);zhuobu.add(walls[index]);inde:<++;第二个Java文件:pubUc class Run {pubUc static void niain(String[] args) {GameFrame gameFramc = new GameFrame("推箱子游戏…”); 〃设置大小gameFrame.seiBoundsdOO. 50. 21 *48 + 5, 14*48 + 25); 〃窗体大小不可变ganieFrame.selRcsizable(false); ganieFrame5ClInigSize(48);ganieFrame.addComponenU3. '*workerUp.png"\ 4{M). 100):ganieFrame.addComponentf U "box,png*\ 160,60): ganieFrame.addComponenU2,"goal.png". 80.520); int[][] wallLocalions ={{4.5}.{5.5b(6.5|,{7.5},{8-5}.{9.51,(10,5}.{6-8}.{7-8}.{&8}・{9.8}.{10,8b{11.5}ganieFrame.addWall("wall.png"\ wallLocations);ganieFrame.setVisibleCtrue);。

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俄罗斯方块小游戏代码package keshe;import java.awt.Color; //颜色import java.awt.Font; //字体import java.awt.Graphics; //绘图import java.awt.event.ActionEvent; //动作import java.awt.event.ActionListener; //事件处理importjava.awt.event.KeyAdapter; //接受键盘信息import java.awt.event.KeyEvent; //键盘信息处理import javax.swing.JFrame; //窗体import javax.swing.JMenu; //菜单import javax.swing.JMenuBar; //菜单条import javax.swing.JMenuItem; //菜单项import javax.swing.JOptionPane; //消息提示框import javax.swing.JPanel; //中间容器import javax.swing.Timer; //时间public class ddddddd extends JFrame{public static void main(String[] args) {ddddddd te = new ddddddd();te.setVisible(true);}private TetrisPanel tp;JMenuItem itemPause;JMenuItem itemContinue;JMenuItem itemgnd;JMenuItem itemdnd;public ddddddd() {this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.setLocation(500, 200);this.setSize(220, 275);this.setResizable(false);tp = new TetrisPanel();this.getContentPane().add(tp);//添加菜单JMenuBar menubar = new JMenuBar();this.setJMenuBar(menubar);JMenu menuGame = new JMenu("游戏");menubar.add(menuGame);JMenuItem itemNew = new JMenuItem("新游戏"); itemNew.setActionCommand("new");itemgnd = new JMenuItem("提高难度");itemgnd.setActionCommand("gnd"); itemdnd = new JMenuItem("降低难度");itemdnd.setActionCommand("dnd");itemPause = new JMenuItem("暂停");itemPause.setActionCommand("pause");itemContinue = new JMenuItem("继续");itemContinue.setActionCommand("continue");itemContinue.setEnabled(false);itemdnd.setEnabled(false);menuGame.add(itemNew);menuGame.add(itemPause);menuGame.add(itemContinue);menuGame.add(itemgnd);menuGame.add(itemdnd);MenuListener menuListener = new MenuListener();itemNew.addActionListener(menuListener);itemPause.addActionListener(menuListener);itemContinue.addActionListener(menuListener);itemgnd.addActionListener(menuListener);itemdnd.addActionListener(menuListener);//让整个JFrame添加键盘监听this.addKeyListener( tp.listener );}class MenuListener implements ActionListener{ public void actionPerformed(ActionEvent e) { //玩新游戏if(e.getActionCommand().equals("new")){tp.newGame();}if(e.getActionCommand().equals("pause")){ timer.stop();itemContinue.setEnabled(true);itemPause.setEnabled(false);}if(e.getActionCommand().equals("continue")){ timer.restart(); itemContinue.setEnabled(false);itemPause.setEnabled(true);}if(tp.nandu==1){itemdnd.setEnabled(false);}else itemdnd.setEnabled(true);if(tp.nandu==9)itemgnd.setEnabled(false);else itemgnd.setEnabled(true);if(e.getActionCommand().equals("gnd")){ tp.delay/=1.3;tp.nandu+=1;timer.setDelay(tp.delay);}if(e.getActionCommand().equals("dnd")){ tp.delay*=1.3;tp.nandu-=1;timer.setDelay(tp.delay);}}}private Timer timer; class TetrisPanel extends JPanel{// 方块的形状:// 第一维代表方块类型(包括7种:S、Z、L、J、I、O、T)// 第二维代表旋转次数// 第三四维代表方块矩阵// shapes[type][turnState][i] i--> block[i/4][i%4]int shapes[][][] = new int[][][] {// I (※把版本1中的横条从第1行换到第2行){ { 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0 } }, // S{ { 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },{ 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0 } }, // Z{ { 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, { 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 } }, // J{ { 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, { 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, // O{ { 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, // L{ { 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 }, { 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, // T{ { 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 }, { 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0 } } };private int blockType;//方块类型private int turnState;//旋转状态private int dierkuai;private int dierState;private int x;//方块的位置x--列的位置--列号private int y;//方块的位置y--行的位置--行号private int map[][]=new int[13][23];//地图:12列22行。

一个简单又有趣的JAVA小游戏代码

一个简单又有趣的JAVA小游戏代码

一个简单又有趣的JAVA小游戏代码猜数字import java.util.*;import java.io.*;public class CaiShu{public static void main(String[] args) throws IOException{Random a=new Random();int num=a.nextInt(100);System.out.println("请输入一个100以内的整数:");for (int i=0;i<=9;i++){BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); String str=bf.readLine();int shu=Integer.parseInt(str);if (shu>num)System.out.println("输入的数大了,输小点的!");else if (shu<num)System.out.println("输入的数小了,输大点的!");else {System.out.println("恭喜你,猜对了!");if (i<=2)System.out.println("你真是个天才!");else if (i<=6)System.out.println("还将就,你过关了!"); else if (i<=8)System.out.println("但是你还……真笨!"); elseSystem.out.println("你和猪没有两样了!"); break;}import java.util.Scanner;import java.util.Random;public class Fangfa{static int sum,sum1=0;public static void main(String [] args){int a=1,b=1,c=1;int k=0,m=1;int money =5000;int zhu =0;boolean flag = true;Random rand = new Random();Scanner input = new Scanner(System.in);while(m==1){while(flag){System.out.println("掷色子开始!");System.out.println("请下注注:下注金额只能是50的倍数且不能超过1000"); zhu=input.nextInt();if(zhu%50==0&&zhu<=1000&&zhu<=money){System.out.println("下注成功");System.out.println("买大请输入数字1,买小输入数字2");k=input.nextInt();a= rand.nextInt(6)+1;b= rand.nextInt(6)+1;c= rand.nextInt(6)+1;sum=a+b+c;if(k==1){if(sum>9){money+=zhu;System.out.println("恭喜您猜对了,骰子点数为"+sum+"结果是大"+"余额为"+money); }else{money-=zhu;System.out.println("很遗憾,骰子点数为"+sum+"结果是小"+"余额为"+money);}}if(k==2){if(sum<=9){money+=zhu;System.out.println("恭喜您猜对了,骰子点数为"+sum+"结果是小"+"余额为"+money); }else{money-=zhu;System.out.println("很遗憾,骰子点数为"+sum+"结果是大"+"余额为"+money);}}flag= false;System.out.println("继续请按1,退出请按任意键");m=input.nextInt();if(m==1){flag=true;System.out.println("您选择的是继续");}else{flag=false;System.out.println("欢迎您下次再来玩");}}else{System.out.println("下注失败"+"余额为"+money); }}}}。

JAVA抓螃蟹小游戏源代码

JAVA抓螃蟹小游戏源代码

鼠标点击事件:package muitl;import java.applet.Applet;import java.awt.Cursor;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.io.File;import .MalformedURLException;import javax.swing.JLabel;public class Catcher extends MouseAdapter{public void mousePressed(MouseEvent e){if (e.getButton() != MouseEvent.BUTTON1)return;Object source = e.getSource();//获取事件源if (source instanceof JLabel) { // 如果事件源是标签组件JLabel carb = (JLabel) source; // 强制转换为JLabel标签if (carb.getIcon() != null) {carb.setIcon(Image.crab2); // 为该标签添加螃蟹图片}}//螃蟹叫声try{CommUtil.audioClip = Applet.newAudioClip(new File(Class.class.getResource("/com/insigma/music/cap.au").getPath()).toURI().toURL());} catch (MalformedURLException e1){// TODO Auto-generated catch blocke1.printStackTrace();}CommUtil.audioClip.play();// 播放try{Thread.sleep(1000);} catch (InterruptedException e2){// TODO Auto-generated catch blocke2.printStackTrace();} // 使线程休眠1秒}public void mouseReleased(MouseEvent e) {if (e.getButton() != MouseEvent.BUTTON1)return;Object source = e.getSource(); // 获取事件源,即螃蟹标签if (source instanceof JLabel) { // 如果事件源是标签组件JLabel carb = (JLabel) source; // 强制转换为JLabel标签carb.setIcon(null);// 清除标签中的螃蟹图片}}}图片类:package muitl;import javax.swing.ImageIcon;public class Image{/*** 背景图片*/public static final ImageIcon background = new ImageIcon(Class.class.getResource("/com/insigma/images/background.jpg").getPath());/*** 螃蟹图片*/public static final ImageIcon crab1 = new ImageIcon(Class.class.getResource("/com/insigma/images/crab.png").getPath());public static final ImageIcon crab2 = new ImageIcon(Class.class.getResource("/com/insigma/images/crab2.png").getPath());/*** 鼠标图片*/public static final ImageIcon hand1 = new ImageIcon(Class.class.getResource("/com/insigma/images/hand.jpg").getPath());public static final ImageIcon hand2 = new ImageIcon(Class.class.getResource("/com/insigma/images/hand2.jpg").getPath());}背景音乐:package muitl;import java.applet.Applet;import java.applet.AudioClip;import java.io.File;import .MalformedURLException;public class PlayMusic extends Thread{public void run(){// 以下是编写背景音乐类,并加入到main方法中启动while (true){if (CommUtil.audioClip == null){try{try{CommUtil.audioClip = Applet.newAudioClip(new File(Class.class.getResource("/com/insigma/music/backgroup.au").getPath()).toURI().toURL());} catch (MalformedURLException e1){e1.printStackTrace();}CommUtil.audioClip.play();// 播放CommUtil.audioClip.loop(); // 循环播放} catch (Exception e){e.printStackTrace();}}}}}工具类:package muitl;import java.applet.AudioClip;public class CommUtil{public static AudioClip audioClip = null; }。

用Java编程语言编写石头剪刀布游戏示例

用Java编程语言编写石头剪刀布游戏示例

用Java编程语言编写石头剪刀布游戏示例文章标题:用Java编程语言编写石头剪刀布游戏示例介绍内容:石头剪刀布游戏是一种简单而受欢迎的游戏,编程语言可以帮助我们实现一个可以和计算机进行对战的石头剪刀布游戏程序。

本文将介绍如何使用Java编程语言编写一个简单而有趣的石头剪刀布游戏示例。

首先,我们需要创建一个Java类,作为我们的游戏程序的主类。

接下来,我们可以使用Java的输入输出和随机数生成的类来实现游戏的逻辑。

下面是一个示例代码,用于实现一个石头剪刀布游戏:```javaimport java.util.Scanner;import java.util.Random;public class RockPaperScissorsGame {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);Random random = new Random();String[] gestures = {"石头", "剪刀", "布"};System.out.println("欢迎来到石头剪刀布游戏!");while (true) {System.out.print("请输入你的选择(石头、剪刀、布):");String playerGesture = scanner.nextLine();if (!isValidGesture(playerGesture)) {System.out.println("无效的手势,请重新输入。

");continue;}int computerChoice = random.nextInt(3);String computerGesture = gestures[computerChoice];System.out.println("你的选择:" + playerGesture);System.out.println("电脑的选择:" + computerGesture);String result = calculateResult(playerGesture, computerGesture);System.out.println(result);System.out.print("是否要继续游戏?(是/否):");String continueChoice = scanner.nextLine();if (continueChoice.equalsIgnoreCase("否")) {break;}}System.out.println("谢谢你玩石头剪刀布游戏!");}private static boolean isValidGesture(String gesture) {return gesture.equals("石头") || gesture.equals("剪刀") || gesture.equals("布");}private static String calculateResult(String playerGesture, String computerGesture) {if (playerGesture.equals(computerGesture)) {return "平局!";} else if ((playerGesture.equals("石头") && computerGesture.equals("剪刀")) ||(playerGesture.equals("剪刀") && computerGesture.equals("布")) ||(playerGesture.equals("布") && computerGesture.equals("石头"))) {return "你赢了!";} else {return "你输了!";}}}```在上述Java代码中,我们首先使用Scanner类来接收玩家输入,使用Random类来生成电脑的随机选择。

JAVA小程序—贪吃蛇源代码

JAVA小程序—贪吃蛇源代码

JAVA贪吃蛇源代码SnakeGame.javapackage SnakeGame;import javax.swing.*;public class SnakeGame{public static void main( String[] args ){JDialog.setDefaultLookAndFeelDecorated( true ); GameFrame temp = new GameFrame();}}Snake.javapackage SnakeGame;import java.awt.*;import java.util.*;class Snake extends LinkedList{public int snakeDirection = 2;public int snakeReDirection = 4;public Snake(){this.add( new Point( 3, 3 ) );this.add( new Point( 4, 3 ) );this.add( new Point( 5, 3 ) );this.add( new Point( 6, 3 ) );this.add( new Point( 7, 3 ) );this.add( new Point( 8, 3 ) );this.add( new Point( 9, 3 ) );this.add( new Point( 10, 3 ) );}public void changeDirection( Point temp, int direction ) {this.snakeDirection = direction;switch( direction ){case 1://upthis.snakeReDirection = 3;this.add( new Point( temp.x, temp.y - 1 ) );break;case 2://rightthis.snakeReDirection = 4;this.add( new Point( temp.x + 1, temp.y ) );break;case 3://downthis.snakeReDirection = 1;this.add( new Point( temp.x, temp.y + 1 ) );break;case 4://leftthis.snakeReDirection = 2;this.add( new Point( temp.x - 1, temp.y ) );break;}}public boolean checkBeanIn( Point bean ){Point temp = (Point) this.getLast();if( temp.equals( bean ) ){return true;}return false;}public void removeTail(){this.remove( 0 );}public void drawSnake( Graphics g, int singleWidthX, int singleHeightY, int cooPos ) {g.setColor( ColorGroup.COLOR_SNAKE );Iterator snakeSq = this.iterator();while ( snakeSq.hasNext() ){Point tempPoint = (Point)snakeSq.next();this.drawSnakePiece( g, tempPoint.x, tempPoint.y,singleWidthX, singleHeightY, cooPos );}}public void drawSnakePiece( Graphics g, int temp1, int temp2,int singleWidthX, int singleHeightY, int cooPos ){g.fillRoundRect( singleWidthX * temp1 + 1,singleHeightY * temp2 + 1,singleWidthX - 2,singleHeightY - 2,cooPos,cooPos );}public void clearEndSnakePiece( Graphics g, int temp1, int temp2, int singleWidthX, int singleHeightY, int cooPos ){g.setColor( ColorGroup.COLOR_BACK );g.fillRoundRect( singleWidthX * temp1 + 1,singleHeightY * temp2 + 1,singleWidthX - 2,singleHeightY - 2,cooPos,cooPos );}}GameFrame.javapackage SnakeGame;import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.*;import java.awt.geom.*;class GameFrame extends JFrame{private Toolkit tempKit;private int horizontalGrid, verticalGrid;private int singleWidthX, singleHeightY;private int cooPos;private Snake mainSnake;private LinkedList eatedBean;{eatedBean = new LinkedList();}private Iterator snakeSq;public javax.swing.Timer snakeTimer;private int direction = 2;private int score;private String info;private Point bean, eatBean;{bean = new Point();}private boolean flag;private JMenuBar infoMenu;private JMenu[] tempMenu;private JMenuItem[] tempMenuItem;private JRadioButtonMenuItem[] levelMenuItem, versionMenuItem;private JLabel scoreLabel;{scoreLabel = new JLabel();}private Graphics2D g;private ImageIcon snakeHead;{snakeHead = new ImageIcon( "LOGO.gif" );}private ConfigMenu configMenu;private boolean hasStoped = true;public GameFrame(){this.tempKit = this.getToolkit();this.setSize( tempKit.getScreenSize() );this.setGrid( 60, 40, 5 );this.getContentPane().setBackground( ColorGroup.COLOR_BACK );this.setUndecorated( true );this.setResizable( false );this.addKeyListener( new KeyHandler() );GameFrame.this.snakeTimer = new javax.swing.Timer( 80, new TimerHandler() ); this.getContentPane().add( scoreLabel, BorderLayout.SOUTH );this.scoreLabel.setFont( new Font( "Fixedsys", Font.BOLD, 15 ) );this.scoreLabel.setText( "Pause[SPACE] - Exit[ESC]" );this.configMenu = new ConfigMenu( this );this.setVisible( true );}public void setGrid( int temp1, int temp2, int temp3 ){this.horizontalGrid = temp1;this.verticalGrid = temp2;this.singleWidthX = this.getWidth() / temp1;this.singleHeightY = this.getHeight() / temp2;this.cooPos = temp3;}private class KeyHandler extends KeyAdapter{public void keyPressed( KeyEvent e ){if( e.getKeyCode() == 27 ){snakeTimer.stop();if( JOptionPane.showConfirmDialog( null, "Are you sure to exit?" ) == 0 ) {System.exit( 0 );}snakeTimer.start();}else if( e.getKeyCode() == 37 && mainSnake.snakeDirection != 2 )//left {direction = 4;}else if( e.getKeyCode() == 39 && mainSnake.snakeDirection != 4 )//right {direction = 2;}else if( e.getKeyCode() == 38 && mainSnake.snakeDirection != 3 )//up {direction = 1;}else if( e.getKeyCode() == 40 && mainSnake.snakeDirection != 1 )//down {direction = 3;}else if( e.getKeyCode() == 32 ){if( !hasStoped ){if( !flag ){snakeTimer.stop();configMenu.setVisible( true );configMenu.setMenuEnable( false );flag = true;}else{snakeTimer.start();configMenu.setVisible( false );configMenu.setMenuEnable( true );flag = false;}}}}}private class TimerHandler implements ActionListener{public synchronized void actionPerformed( ActionEvent e ){Point temp = (Point) mainSnake.getLast();snakeSq = mainSnake.iterator();while ( snakeSq.hasNext() ){Point tempPoint = (Point)snakeSq.next();if( temp.equals( tempPoint ) && snakeSq.hasNext() != false ){snakeTimer.stop();stopGame();JOptionPane.showMessageDialog( null,"Your Score is " + score + "&#92;n&#92;nYou Loss!" );}}System.out.println( temp.x + " " + temp.y );if( (temp.x == 0 && direction == 4) ||(temp.x == horizontalGrid-1 && direction == 2) ||(temp.y == 0 && direction == 1) ||(temp.y == verticalGrid-1 && direction == 3) ){snakeTimer.stop();stopGame();JOptionPane.showMessageDialog( null,"Your Score is " + score + "&#92;n&#92;nYou Loss!" );}if( direction != mainSnake.snakeReDirection ){moveSnake( direction );}mainSnake.drawSnake( getGraphics(), singleWidthX, singleHeightY, cooPos ); drawBeanAndEBean( getGraphics() );}}public void stopGame(){this.hasStoped = true;this.snakeTimer.stop();Graphics2D g = (Graphics2D) GameFrame.this.getGraphics();g.setColor( ColorGroup.COLOR_BACK );super.paint( g );configMenu.setVisible( true );}public void resetGame(){System.gc();this.hasStoped = false;Graphics2D g = (Graphics2D) GameFrame.this.getGraphics();g.setColor( ColorGroup.COLOR_BACK );super.paint( g );this.mainSnake = new Snake();this.createBean( bean );this.eatedBean.clear();mainSnake.drawSnake( getGraphics(), singleWidthX, singleHeightY, cooPos ); this.snakeTimer.start();this.direction = 2;this.score = 0;this.scoreLabel.setText( "Pause[SPACE] - Exit[ESC]" );}private void moveSnake( int direction ){if( mainSnake.checkBeanIn( this.bean ) ){this.score += 100;this.scoreLabel.setText( + " Current Score:" + this.score );this.eatedBean.add( new Point(this.bean) );this.createBean( this.bean );}mainSnake.changeDirection( (Point) mainSnake.getLast(), direction );Point temp = (Point) mainSnake.getFirst();if( eatedBean.size() != 0 ){if( eatedBean.getFirst().equals( temp ) ){eatedBean.remove( 0 );}else{mainSnake.clearEndSnakePiece( getGraphics(), temp.x, temp.y, singleWidthX, singleHeightY, cooPos );mainSnake.removeTail();}}else{mainSnake.clearEndSnakePiece( getGraphics(), temp.x, temp.y, singleWidthX, singleHeightY, cooPos );mainSnake.removeTail();}}private void drawBeanAndEBean( Graphics g ){g.setColor( ColorGroup.COLOR_BEAN );this.drawPiece( g, this.bean.x, this.bean.y );g.setColor( ColorGroup.COLOR_EATEDBEAN );snakeSq = eatedBean.iterator();while ( snakeSq.hasNext() ){Point tempPoint = (Point)snakeSq.next();this.drawPiece( g, tempPoint.x, tempPoint.y );}}private void drawPiece( Graphics g, int x, int y ){g.fillRoundRect( this.singleWidthX * x + 1,this.singleHeightY * y + 1,this.singleWidthX - 2,this.singleHeightY - 2,this.cooPos,this.cooPos );}private void createBean( Point temp ){LP:while( true ){temp.x = (int) (Math.random() * this.horizontalGrid);temp.y = (int) (Math.random() * this.verticalGrid);snakeSq = mainSnake.iterator();while ( snakeSq.hasNext() ){if( snakeSq.next().equals( new Point( temp.x, temp.y ) ) ){continue LP;}}break;}}}ConfigMenu.javapackage SnakeGame;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class ConfigMenu extends JMenuBar{GameFrame owner;JMenu[] menu;JMenuItem[] menuItem;JRadioButtonMenuItem[] speedItem, modelItem, standardItem; private UIManager.LookAndFeelInfo looks[];public ConfigMenu( GameFrame owner ){this.owner = owner;owner.setJMenuBar( this );String[] menu_name = {"Snake Game", "Game Configure", "Game Help"}; menu = new JMenu[menu_name.length];for( int i = 0; i < menu_name.length; i++ ){menu[i] = new JMenu( menu_name[i] );menu[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );this.add( menu[i] );}String[] menuItem_name = {"Start Game", "Stop Game", "Exit Game", "Game Color","About..."};menuItem = new JMenuItem[menuItem_name.length];for( int i = 0; i < menuItem_name.length; i++ ){menuItem[i] = new JMenuItem( menuItem_name[i] );menuItem[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) ); menuItem[i].addActionListener( new ActionHandler() );}menu[0].add( menuItem[0] );menu[0].add( menuItem[1] );menu[0].addSeparator();menu[0].add( menuItem[2] );menu[1].add( menuItem[3] );menu[2].add( menuItem[4] );String[] inner_menu_name = {"Game Speed", "Window Model", "Game Standard "}; JMenu[] inner_menu = new JMenu[inner_menu_name.length];for( int i = 0; i < inner_menu_name.length; i++ ){inner_menu[i] = new JMenu( inner_menu_name[i] );inner_menu[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );menu[1].add( inner_menu[i] );}ButtonGroup temp1 = new ButtonGroup();String[] speedItem_name = {"Speed-1", "Speed-2", "Speed-3", "Speed-4", "Speed-5"}; speedItem = new JRadioButtonMenuItem[speedItem_name.length];for( int i = 0; i < speedItem_name.length; i++ ){speedItem[i] = new JRadioButtonMenuItem( speedItem_name[i] );inner_menu[0].add( speedItem[i] );speedItem[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );speedItem[i].addItemListener( new ItemHandler() );temp1.add( speedItem[i] );}ButtonGroup temp2 = new ButtonGroup();String[] modelItem_name = { "Linux", "Mac", "Windows" };modelItem = new JRadioButtonMenuItem[modelItem_name.length];for( int i = 0; i < modelItem_name.length; i++ ){modelItem[i] = new JRadioButtonMenuItem( modelItem_name[i] );inner_menu[1].add( modelItem[i] );modelItem[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );modelItem[i].addItemListener( new ItemHandler() );temp2.add( modelItem[i] );}ButtonGroup temp3 = new ButtonGroup();String[] standardItem_name = { "60 * 40", "45 * 30", "30 * 20" };standardItem = new JRadioButtonMenuItem[standardItem_name.length];for( int i = 0; i < standardItem_name.length; i++ ){standardItem[i] = new JRadioButtonMenuItem( standardItem_name[i] );inner_menu[2].add( standardItem[i] );standardItem[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );standardItem[i].addItemListener( new ItemHandler() );temp3.add( standardItem[i] );}looks = UIManager.getInstalledLookAndFeels();}private class ActionHandler implements ActionListener{public void actionPerformed( ActionEvent e ){if( e.getSource() == menuItem[0] ){owner.resetGame();ConfigMenu.this.setVisible( false );}else if( e.getSource() == menuItem[1] ){owner.stopGame();ConfigMenu.this.setVisible( true );ConfigMenu.this.setMenuEnable( true );}else if( e.getSource() == menuItem[2] ){System.exit( 0 );}else if( e.getSource() == menuItem[3] ){ConfigDialog temp = new ConfigDialog( owner );temp.setVisible( true );}else if( e.getSource() == menuItem[4] ){JOptionPane.showMessageDialog( null, "Sanke Game 2.0 Version!&#92;n&#92;n" + "Author: FinalCore&#92;n&#92;n" );}}}private class ItemHandler implements ItemListener{public void itemStateChanged( ItemEvent e ){for( int i = 0; i < speedItem.length; i++ ){if( e.getSource() == speedItem[i] ){owner.snakeTimer.setDelay( 150 - 30 * i );}}if( e.getSource() == standardItem[0] ){owner.setGrid( 60, 40, 5 );}else if( e.getSource() == standardItem[1] ){owner.setGrid( 45, 30, 10 );}else if( e.getSource() == standardItem[2] ){owner.setGrid( 30, 20, 15 );}for( int i = 0; i < modelItem.length; i++ ){if( e.getSource() == modelItem[i] ){try{UIManager.setLookAndFeel( looks[i].getClassName() ); }catch(Exception ex){}}}}}public void setMenuEnable( boolean temp ){menu[1].setEnabled( temp );}}。

用Java编写的猜拳小游戏

用Java编写的猜拳小游戏

⽤Java编写的猜拳⼩游戏学习⽬标:熟练掌握各种循环语句例题:代码如下:// 综合案例分析,猜拳案例// isContinue为是否开始游戏时你所输⼊的值char isContinue;//y为开始,n为借宿System.out.println("是否开始游戏(y/n)");Scanner sc = new Scanner(System.in);String str = sc.next();// 获取你输⼊字符串的第⼀个字符isContinue = str.charAt(0);// mcount代表玩家赢的局数,pcount代表电脑赢的局数int mcount = 0, pcount = 0;//你的名字System.out.println("请输⼊您的名字");String pName = sc.next();System.out.println("您的名字是:" + pName);System.out.println("请选择您的对⼿:1、貂蝉, 2、⼩肥⽺,3、吕布");// cpuName电脑名字String cpuName = null;int num3 = sc.nextInt();if(num3 >= 1 && num3 <= 3) {switch (num3) {case 1 : {cpuName = "貂蝉";} break;case 2 : {cpuName = "⼩肥⽺";} break;case 3 : {cpuName = "吕布";}}System.out.println(pName + " VS " + cpuName);// 让⼤⼩写都能运⾏if(isContinue == 'y' || isContinue == 'Y' || isContinue == 'n' || isContinue == 'N') {while(isContinue == 'y' || isContinue == 'Y') {System.out.println("请输⼊您要出的东西:1、布, 2、拳头,3、剪⼑");int num = sc.nextInt();switch(num) {case 1 : {System.out.println(pName + "出的是布");} break;case 2 : { System.out.println(pName + "出的是拳头"); }; break;case 3 : { System.out.println(pName + "出的是剪⼑"); }; break;default : { System.out.println(pName + "的输⼊不规范,请重新输⼊"); }//输⼊出错,跳出当前循环回到while,重新输⼊continue;}// 让电脑随机⽣成1~3的随机数Random num2 = new Random();// +1是因为前⾯代码⽣成的是0~2,+1后就变成了1~3int cpt = num2.nextInt(3) + 1;// 判断电脑产⽣的随机数switch(cpt) {case 1 : {System.out.println(cpuName + "出的是布");}; break;case 2 : {System.out.println(cpuName + "的是拳头");}; break;case 3 : {System.out.println(cpuName + "的是剪⼑");}; break;}// 把⾃⼰输⼊的数与电脑随机产⽣的随机数相⽐较if(num == cpt) {System.out.println(pName + "和" + cpuName + "这局打平!");} else if((num == 1 && cpt == 2) || (num == 2 && cpt == 3) || (num == 3 && cpt == 1)) {System.out.println(pName + "赢了!");mcount++;} else {System.out.println(cpuName + "赢了!");pcount++;}System.out.println(pName + "共赢了" + mcount + "局" + " " + cpuName + "共赢了" + pcount + "局"); System.out.println("是否继续游戏(y/n)");str = sc.next();isContinue = str.charAt(0);}} else {System.out.println("您输⼊的不符合规则,游戏结束!");}} else {System.out.println("您输⼊的数据不符合规范!");}运⾏效果:是否开始游戏(y/n)y请输⼊您的名字lalal您的名字是:lalal请选择您的对⼿:1、貂蝉, 2、⼩肥⽺,3、吕布1lalal VS 貂蝉请输⼊您要出的东西:1、布, 2、拳头,3、剪⼑3lalal出的是剪⼑貂蝉的是剪⼑lalal和貂蝉这局打平!lalal共赢了0局貂蝉共赢了0局是否继续游戏(y/n)y请输⼊您要出的东西:1、布, 2、拳头,3、剪⼑5lalal的输⼊不规范,请重新输⼊请输⼊您要出的东西:1、布, 2、拳头,3、剪⼑1lalal出的是布貂蝉的是拳头lalal赢了!lalal共赢了1局貂蝉共赢了0局是否继续游戏(y/n)nProcess finished with exit code 0总结:以上就是⽤Java编写的猜拳⼩游戏了,代码仅供参考。

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游戏源代码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();}}。

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

Java小游戏第一个Java文件:import java.util.Scanner;public class GameA_B {public static void main(String[] args) {Scanner reader=new Scanner(System.in);int area;System.out.println("Game Start…………Please enter the area:(1-9)"+ '\n'+"1,2,3 means easy"+'\n'+"4,5,6 means middle"+'\n'+"7,8,9 means hard"+'\n'+"Please choose:");a rea=reader.nextInt();s witch((area-1)/3){c ase 0:System.out.println("You choose easy! ");break;c ase 1:System.out.println("You choose middle! ");break;c ase 2:System.out.println("You choose hard! ");break;}S ystem.out.println("Good Luck!");G ameProcess game1=new GameProcess(area);game1.process();}}第二个Java文件:import java.util.Random;import java.util.Scanner;public class GameProcess {int area,i,arrcount,right,midright,t;int base[]=new int[arrcount],userNum[]=new int[area],sysNum[]=new int[area];Random random=new Random();Scanner reader=new Scanner(System.in);GameProcess(int a){area=a;arrcount=10;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 = Res.values();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;}}}}。

相关文档
最新文档