当前位置:   article > 正文

java开发的小游戏 恐龙在奔跑_奔跑的小恐龙代码

奔跑的小恐龙代码

项目名称是Dinosaur

 在src文件中,建立了4个包,依次是com.mr.main,com.mr.modle,com.mr.service,com.mr.view。

 代码文件分别是Start.java,Dinosaur.java,Obstacle.java,FreshThread.java,MusicPlayer.java,ScoreRecorder.java,sound.java,BackgroundImage.java,GamePanel.java,MainFrame.java,ScoreDialog.java。

 上图是其他文件夹的结构,我会把图片文件和音乐文件也上传。

那个data文件夹的source,里面的内容是

870,1160,1970

 下面开始上代码:

Start.java

  1. package com.mr.main; //入口包
  2. import com.mr.view.MainFrame;
  3. //启动类
  4. public class Start
  5. {
  6. public static void main(String[] args)
  7. {
  8. MainFrame m1 = new MainFrame();
  9. m1.setVisible(true);
  10. }
  11. }

Dinosaur.java

  1. package com.mr.modle;
  2. import java.awt.Rectangle;
  3. import java.awt.image.BufferedImage;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import javax.imageio.ImageIO;
  7. import javax.xml.crypto.dsig.keyinfo.RetrievalMethod;
  8. import com.mr.service.FreshThread;
  9. import com.mr.service.Sound;
  10. //模型包
  11. //恐龙类
  12. public class Dinosaur
  13. {
  14. public BufferedImage image; //主图片
  15. private BufferedImage image1,image2,image3; //跑步图片
  16. public int x,y; //坐标
  17. private int jumpValue = 0; //跳跃的增变量
  18. private boolean jumpState = false; //跳跃状态
  19. private int stepTimer = 0; //踏步计时器
  20. private final int JUMP_HEIGHT = 105; //跳起最大高度
  21. private final int LOWEST_Y = 120; //落地最低坐标
  22. private final int FREASH = FreshThread.FREASH; //刷新时间
  23. public Dinosaur()
  24. {
  25. this.x = 50;
  26. this.y = LOWEST_Y;
  27. try
  28. {
  29. image1 = ImageIO.read(new File("image/konglong1.png"));
  30. image2 = ImageIO.read(new File("image/konglong2.png"));
  31. image3 = ImageIO.read(new File("image/konglong3.png"));
  32. } catch (IOException e)
  33. {
  34. e.printStackTrace();
  35. }
  36. }
  37. private void step()
  38. {
  39. //每过250毫秒,更换一张图片。因为有3张,所以除以3取余,轮流
  40. int temp = (stepTimer / 250) % 3;
  41. switch (temp)
  42. {
  43. case 1:
  44. image = this.image1;
  45. break;
  46. case 2:
  47. image = this.image2;
  48. break;
  49. default:
  50. image = this.image3;
  51. break;
  52. }
  53. stepTimer += FREASH;
  54. }
  55. public void jump()
  56. {
  57. if (!jumpState)
  58. {
  59. Sound.jump(); //播放跳跃的音效
  60. }
  61. jumpState = true; //处于跳跃状态
  62. }
  63. public void move()
  64. {
  65. step();
  66. if (jumpState)
  67. {
  68. if (y >= LOWEST_Y)
  69. {
  70. jumpValue = -4; //如果纵坐标大于等于最低点
  71. }
  72. if (y <= LOWEST_Y - JUMP_HEIGHT)
  73. {
  74. jumpValue = 4; //如果跳过最高点
  75. }
  76. y+= jumpValue;
  77. if (y >= LOWEST_Y)
  78. {
  79. jumpState = false; //如果再次落地
  80. }
  81. }
  82. }
  83. public Rectangle getFootBounds()
  84. {
  85. return new Rectangle(x+30,y+59,29,18);
  86. }
  87. public Rectangle getHeadBounds()
  88. {
  89. return new Rectangle(x+66,y+25,32,22);
  90. }
  91. }

Obstacle.java

  1. package com.mr.modle;
  2. import java.awt.Rectangle;
  3. import java.awt.image.BufferedImage;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import java.util.Random;
  7. import javax.imageio.ImageIO;
  8. import com.mr.view.BackgroundImage;
  9. //障碍类
  10. public class Obstacle
  11. {
  12. public int x,y;
  13. public BufferedImage image;
  14. private BufferedImage stone; //石头
  15. private BufferedImage cacti; //仙人掌
  16. private int speed; //移动速度
  17. public Obstacle()
  18. {
  19. try
  20. {
  21. stone = ImageIO.read(new File("image/stone.jpg"));
  22. cacti = ImageIO.read(new File("image/cacti.jpg"));
  23. } catch (IOException e)
  24. {
  25. e.printStackTrace();
  26. }
  27. Random r1 = new Random();
  28. if (r1.nextInt(2) == 0)
  29. {
  30. image = cacti; //0,仙人掌
  31. }
  32. else
  33. {
  34. image = stone; //1,石头
  35. }
  36. x = 800;
  37. y = 220 - image.getHeight();
  38. speed = BackgroundImage.SPEED; // 移动速度与背景速度一致
  39. }
  40. public void move()
  41. {
  42. x -= speed;
  43. }
  44. public boolean isLive()
  45. {
  46. if (x <= -image.getWidth())
  47. {
  48. return false;
  49. }
  50. return true;
  51. }
  52. public Rectangle getBounds()
  53. {
  54. if (image == cacti)
  55. {
  56. return new Rectangle(x+7,y,15,image.getHeight()); //仙人掌
  57. }
  58. return new Rectangle(x+5,y+4,23,21); //石头
  59. }
  60. }

FreshThread.java

  1. package com.mr.service;
  2. import java.awt.Container;
  3. import com.mr.view.GamePanel;
  4. import com.mr.view.MainFrame;
  5. import com.mr.view.ScoreDialog;
  6. //服务包
  7. //刷新帧线程
  8. public class FreshThread extends Thread
  9. {
  10. public static final int FREASH = 20; //刷新时间
  11. GamePanel panel; //游戏面板
  12. public FreshThread(GamePanel p)
  13. {
  14. this.panel = p;
  15. }
  16. public void run()
  17. {
  18. while (!panel.isFinish())
  19. {
  20. panel.repaint();
  21. try
  22. {
  23. Thread.sleep(FREASH);
  24. } catch (InterruptedException e)
  25. {
  26. e.printStackTrace();
  27. }
  28. }
  29. Container container1 = panel.getParent();
  30. while (!(container1 instanceof MainFrame))
  31. {
  32. container1 = container1.getParent();
  33. }
  34. MainFrame frame = (MainFrame)container1;
  35. new ScoreDialog(frame);
  36. frame.restart();
  37. }
  38. }

MusicPlayer.java

  1. package com.mr.service;
  2. import java.io.File;
  3. import java.io.FileNotFoundException;
  4. import java.io.IOException;
  5. import javax.sound.sampled.AudioFormat;
  6. import javax.sound.sampled.AudioInputStream;
  7. import javax.sound.sampled.AudioSystem;
  8. import javax.sound.sampled.DataLine;
  9. import javax.sound.sampled.LineUnavailableException;
  10. import javax.sound.sampled.SourceDataLine;
  11. import javax.sound.sampled.UnsupportedAudioFileException;
  12. //音乐播放器类
  13. public class MusicPlayer implements Runnable
  14. {
  15. File soundFile; //音乐文件
  16. Thread thread; //父线程
  17. boolean circulate; //循环播放
  18. public MusicPlayer(String filePath,boolean circulate) throws FileNotFoundException
  19. {
  20. this.circulate = circulate;
  21. soundFile = new File(filePath);
  22. if (!soundFile.exists())
  23. {
  24. throw new FileNotFoundException(filePath + "未找到");
  25. }
  26. }
  27. public void run()
  28. {
  29. byte[] auBuffer = new byte[1024 * 128]; //128k缓冲区
  30. do
  31. {
  32. AudioInputStream audioInputStream = null; //音频输入流
  33. SourceDataLine auLine = null; //混频器数据行
  34. try
  35. {
  36. audioInputStream = AudioSystem.getAudioInputStream(soundFile);
  37. AudioFormat format = audioInputStream.getFormat();
  38. DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
  39. auLine = (SourceDataLine)AudioSystem.getLine(info);
  40. auLine.open(format);
  41. auLine.start();
  42. int byteCount = 0;
  43. while (byteCount != -1)
  44. {
  45. byteCount = audioInputStream.read(auBuffer,0,auBuffer.length);
  46. if (byteCount >= 0)
  47. {
  48. auLine.write(auBuffer, 0, byteCount);
  49. }
  50. }
  51. }catch (IOException e)
  52. {
  53. e.printStackTrace();
  54. }
  55. catch (UnsupportedAudioFileException e)
  56. {
  57. e.printStackTrace();
  58. }
  59. catch (LineUnavailableException e)
  60. {
  61. e.printStackTrace();
  62. }finally
  63. {
  64. auLine.drain();
  65. auLine.close();
  66. }
  67. } while (circulate);
  68. }
  69. public void play()
  70. {
  71. thread = new Thread(this);
  72. thread.start();
  73. }
  74. public void stop()
  75. {
  76. thread.stop();
  77. }
  78. }

ScoreRecorder.java

  1. package com.mr.service;
  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileNotFoundException;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.io.InputStreamReader;
  10. import java.io.OutputStreamWriter;
  11. import java.util.Arrays;
  12. //分数记录器类
  13. public class ScoreRecorder
  14. {
  15. private static final String SCOREFILE = "data/source"; //成绩记录文件
  16. private static int scroes[] = new int[3]; //前三名
  17. public static void init()
  18. {
  19. File file1 = new File(SCOREFILE);
  20. if (!file1.exists())
  21. {
  22. try
  23. {
  24. file1.createNewFile();
  25. } catch (IOException e)
  26. {
  27. e.printStackTrace();
  28. }
  29. return;
  30. }
  31. FileInputStream fileInputStream1 = null;
  32. InputStreamReader inputStreamReader1 = null;
  33. BufferedReader bufferedReader1 = null;
  34. try
  35. {
  36. fileInputStream1 = new FileInputStream(file1); //文件字节输入流
  37. inputStreamReader1 = new InputStreamReader(fileInputStream1); //字节流转字符流
  38. bufferedReader1 = new BufferedReader(inputStreamReader1); //缓冲字节流
  39. String value = bufferedReader1.readLine(); //读取一行
  40. if (!(value ==null || "".equals(value))) //如果不为空
  41. {
  42. String vs[] = value.split(","); //分隔字符串
  43. if (vs.length < 3) //小于3
  44. {
  45. Arrays.fill(scroes, 0); //成绩填充0
  46. }
  47. else
  48. {
  49. for (int i = 0; i < 3; i++)
  50. {
  51. scroes[i] = Integer.parseInt(vs[i]);
  52. }
  53. }
  54. }
  55. } catch (FileNotFoundException e)
  56. {
  57. e.printStackTrace();
  58. }
  59. catch (IOException e)
  60. {
  61. e.printStackTrace();
  62. }
  63. finally
  64. {
  65. try
  66. {
  67. bufferedReader1.close();
  68. } catch (IOException e2)
  69. {
  70. e2.printStackTrace();
  71. }
  72. try
  73. {
  74. inputStreamReader1.close();
  75. } catch (IOException e2)
  76. {
  77. e2.printStackTrace();
  78. }
  79. try
  80. {
  81. fileInputStream1.close();
  82. } catch (IOException e2)
  83. {
  84. e2.printStackTrace();
  85. }
  86. }
  87. }
  88. public static void saveScore()
  89. {
  90. String value = scroes[0] + "," + scroes[1] + "," + scroes[2]; //
  91. FileOutputStream fileOutputStream1 = null;
  92. OutputStreamWriter outputStreamWriter1 = null;
  93. BufferedWriter bufferedWriter1 = null;
  94. try
  95. {
  96. fileOutputStream1 = new FileOutputStream(SCOREFILE);
  97. outputStreamWriter1 = new OutputStreamWriter(fileOutputStream1);
  98. bufferedWriter1 = new BufferedWriter(outputStreamWriter1);
  99. bufferedWriter1.write(value);
  100. bufferedWriter1.flush();
  101. } catch (FileNotFoundException e)
  102. {
  103. e.printStackTrace();
  104. }
  105. catch (IOException e)
  106. {
  107. e.printStackTrace();
  108. }
  109. finally
  110. {
  111. try
  112. {
  113. bufferedWriter1.close();
  114. } catch (IOException e2)
  115. {
  116. e2.printStackTrace();
  117. }
  118. try
  119. {
  120. outputStreamWriter1.close();
  121. } catch (IOException e2)
  122. {
  123. e2.printStackTrace();
  124. }
  125. try
  126. {
  127. fileOutputStream1.close();
  128. } catch (IOException e2)
  129. {
  130. e2.printStackTrace();
  131. }
  132. }
  133. }
  134. static public void addNewScore(int score)
  135. {
  136. int temp[] = Arrays.copyOf(scroes, 4);
  137. temp[3] = score;
  138. Arrays.sort(temp);
  139. scroes = Arrays.copyOfRange(temp, 1, 4);
  140. }
  141. static public int[] getScores()
  142. {
  143. return scroes;
  144. }
  145. }

Sound.java

  1. package com.mr.service;
  2. import java.io.FileNotFoundException;
  3. //音效类
  4. public class Sound
  5. {
  6. static final String DIR = "music/";
  7. static final String BACKGROUD = "background.wav";
  8. static final String JUMP = "jump.wav";
  9. static final String HIT = "hit.wav";
  10. //播放声音,参数1,文件名称,参数2,是否循环播放
  11. private static void play(String file,boolean circulate)
  12. {
  13. try
  14. {
  15. MusicPlayer player = new MusicPlayer(file, circulate);
  16. player.play();
  17. } catch (FileNotFoundException e)
  18. {
  19. e.printStackTrace();
  20. }
  21. }
  22. //播放跳跃音效
  23. static public void jump()
  24. {
  25. play(DIR+JUMP, false);
  26. }
  27. //播放撞击音效
  28. static public void hit()
  29. {
  30. play(DIR+HIT, false);
  31. }
  32. //播放背景音乐
  33. static public void backgroud()
  34. {
  35. play(DIR+BACKGROUD, true);
  36. }
  37. }

BackgroundImage.java

  1. package com.mr.view;
  2. import java.awt.Graphics2D;
  3. import java.awt.image.BufferedImage;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import javax.imageio.ImageIO;
  7. //视图包
  8. //滚动背景
  9. public class BackgroundImage
  10. {
  11. public BufferedImage image;
  12. private BufferedImage image1,image2;
  13. private Graphics2D g2d;
  14. public int x1,x2;
  15. public static final int SPEED = 4;
  16. public BackgroundImage()
  17. {
  18. try
  19. {
  20. image1 = ImageIO.read(new File("image/beijing.png"));
  21. image2 = ImageIO.read(new File("image/beijing.png"));
  22. } catch (IOException e)
  23. {
  24. e.printStackTrace();
  25. }
  26. image = new BufferedImage(800, 300, BufferedImage.TYPE_INT_RGB);
  27. g2d = image.createGraphics(); //
  28. x1 = 0; //第一幅图横坐标
  29. x2 = 800; //第二副图坐标
  30. g2d.drawImage(image1, x1, 0, null);
  31. }
  32. public void roll()
  33. {
  34. x1 -= SPEED;
  35. x2 -= SPEED;
  36. if (x1 <= -800)
  37. {
  38. x1 = 800;
  39. }
  40. if (x2 <= -800)
  41. {
  42. x2 = 800;
  43. }
  44. g2d.drawImage(image1, x1, 0, null);
  45. g2d.drawImage(image2, x2, 0, null);
  46. }
  47. }

GamePanel.java

  1. package com.mr.view;
  2. import java.awt.Color;
  3. import java.awt.Font;
  4. import java.awt.Graphics;
  5. import java.awt.Graphics2D;
  6. import java.awt.event.KeyEvent;
  7. import java.awt.event.KeyListener;
  8. import java.awt.image.BufferedImage;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. import javax.swing.JPanel;
  12. import javax.xml.crypto.dsig.keyinfo.RetrievalMethod;
  13. import com.mr.modle.Dinosaur;
  14. import com.mr.modle.Obstacle;
  15. import com.mr.service.FreshThread;
  16. import com.mr.service.ScoreRecorder;
  17. import com.mr.service.Sound;
  18. //游戏面板
  19. public class GamePanel extends JPanel implements KeyListener
  20. {
  21. private BufferedImage image1; //主图片
  22. private BackgroundImage background1;//背景图片
  23. private Dinosaur golden1; //恐龙
  24. private Graphics2D g2d; //主图片绘图对象
  25. private int addObstacleTimer = 0; //障碍计时器
  26. private boolean finish = false; //游戏结束标志
  27. private List<Obstacle> list1 = new ArrayList<>(); //障碍集合
  28. private final int FREASH = FreshThread.FREASH; //刷新时间
  29. int score = 0; //得分
  30. int scoreTimer = 0; //分数计时器
  31. public GamePanel()
  32. {
  33. image1 = new BufferedImage(800, 300, BufferedImage.TYPE_INT_BGR);
  34. g2d = image1.createGraphics();
  35. background1 = new BackgroundImage();
  36. golden1 = new Dinosaur();
  37. list1.add(new Obstacle());
  38. FreshThread thread1 = new FreshThread(this);
  39. thread1.start();
  40. }
  41. private void paintImage()
  42. {
  43. background1.roll();
  44. golden1.move();
  45. g2d.drawImage(background1.image, 0, 0, this);
  46. if (addObstacleTimer == 1300)
  47. {
  48. if (Math.random() * 100 > 40)
  49. {
  50. list1.add(new Obstacle());
  51. }
  52. addObstacleTimer = 0;
  53. }
  54. for (int i = 0; i < list1.size(); i++)
  55. {
  56. Obstacle o1 = list1.get(i);
  57. if (o1.isLive())
  58. {
  59. o1.move();
  60. g2d.drawImage(o1.image, o1.x, o1.y, this);
  61. if (o1.getBounds().intersects(golden1.getFootBounds())|| o1.getBounds().intersects(golden1.getHeadBounds()))
  62. {
  63. Sound.hit();
  64. gameOver();
  65. }
  66. }
  67. else
  68. {
  69. list1.remove(i);
  70. i--;
  71. }
  72. }
  73. g2d.drawImage(golden1.image, golden1.x, golden1.y, this);
  74. if (scoreTimer >= 500)
  75. {
  76. score += 10;
  77. scoreTimer = 0;
  78. }
  79. g2d.setColor(Color.BLACK);
  80. g2d.setFont(new Font("黑体",Font.BOLD,24));
  81. g2d.drawString(String.format("%06d", score), 700, 30);
  82. addObstacleTimer += FREASH;
  83. scoreTimer += FREASH;
  84. }
  85. public void paint(Graphics g)
  86. {
  87. paintImage();
  88. g.drawImage(image1, 0, 0, this);
  89. }
  90. public void gameOver()
  91. {
  92. ScoreRecorder.addNewScore(score);
  93. finish = true;
  94. }
  95. public boolean isFinish()
  96. {
  97. return finish;
  98. }
  99. public void keyPressed(KeyEvent e)
  100. {
  101. int code = e.getKeyCode();
  102. if (code == KeyEvent.VK_SPACE)
  103. {
  104. golden1.jump();
  105. }
  106. }
  107. @Override
  108. public void keyTyped(KeyEvent e)
  109. {
  110. }
  111. @Override
  112. public void keyReleased(KeyEvent e)
  113. {
  114. // TODO Auto-generated method stub
  115. }
  116. }

MainFrame.java

  1. package com.mr.view;
  2. import java.awt.Container;
  3. import java.awt.event.WindowAdapter;
  4. import java.awt.event.WindowEvent;
  5. import javax.swing.JFrame;
  6. import javax.swing.WindowConstants;
  7. import com.mr.service.ScoreRecorder;
  8. import com.mr.service.Sound;
  9. //主窗体
  10. public class MainFrame extends JFrame
  11. {
  12. public MainFrame()
  13. {
  14. restart(); //开始
  15. this.setBounds(340,150,820,260);
  16. this.setTitle("奔跑吧,虾米大王");
  17. Sound.backgroud(); //播放背景音乐
  18. ScoreRecorder.init(); //读取得分记录
  19. addListener(); //添加监听
  20. this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  21. }
  22. public void restart()
  23. {
  24. Container container1 = this.getContentPane();
  25. container1.removeAll(); //删除容器中所有组件
  26. GamePanel panel1 = new GamePanel(); //创建游戏面板
  27. container1.add(panel1);
  28. addKeyListener(panel1); //添加键盘事件
  29. container1.validate(); //验证组件
  30. }
  31. private void addListener()
  32. {
  33. addWindowListener(new WindowAdapter()
  34. {
  35. public void windowClosing(WindowEvent e)
  36. {
  37. ScoreRecorder.saveScore();
  38. }
  39. });
  40. }
  41. }

ScoreDialog.java

  1. package com.mr.view;
  2. import java.awt.BorderLayout;
  3. import java.awt.Color;
  4. import java.awt.Container;
  5. import java.awt.Font;
  6. import java.awt.GridLayout;
  7. import java.awt.event.ActionEvent;
  8. import java.awt.event.ActionListener;
  9. import javax.swing.JButton;
  10. import javax.swing.JDialog;
  11. import javax.swing.JFrame;
  12. import javax.swing.JLabel;
  13. import javax.swing.JPanel;
  14. import com.mr.service.ScoreRecorder;
  15. //成绩对话框
  16. public class ScoreDialog extends JDialog
  17. {
  18. public ScoreDialog(JFrame frame)
  19. {
  20. super(frame,true);
  21. int scores[] = ScoreRecorder.getScores();
  22. JPanel scorePanel = new JPanel(new GridLayout(4,1));
  23. scorePanel.setBackground(Color.WHITE);
  24. JLabel label1 = new JLabel("得分排行榜",JLabel.CENTER);
  25. label1.setFont(new Font("黑体",Font.BOLD,20));
  26. label1.setForeground(Color.RED);
  27. JLabel label2 = new JLabel("第1名:" + scores[2],JLabel.CENTER);
  28. JLabel label3 = new JLabel("第2名:" + scores[1],JLabel.CENTER);
  29. JLabel label4 = new JLabel("第3名:" + scores[0],JLabel.CENTER);
  30. JButton button1 = new JButton("重新开始");
  31. button1.addActionListener(new ActionListener()
  32. {
  33. @Override
  34. public void actionPerformed(ActionEvent e)
  35. {
  36. dispose();
  37. }
  38. });
  39. scorePanel.add(label1);
  40. scorePanel.add(label2);
  41. scorePanel.add(label3);
  42. scorePanel.add(label4);
  43. Container container1 = this.getContentPane();
  44. container1.setLayout(new BorderLayout());
  45. container1.add(scorePanel,BorderLayout.CENTER);
  46. container1.add(button1,BorderLayout.SOUTH);
  47. this.setTitle("游戏结束");
  48. int width,height;
  49. width = 200;
  50. height = 200;
  51. int x = frame.getX() + (frame.getWidth() - width)/2;
  52. int y = frame.getY() + (frame.getHeight() - height)/2;
  53. setBounds(x,y,width,height);
  54. setVisible(true);
  55. }
  56. }

代码结束了。

image文件夹的

beijing.png

 cacti.png

 

konglong1.png

 

 konglong2.png

 konglong3.png

 konglong.png

 stone.png

 music文件的

background.wav

hit.wav

jump.wav

我试过了,上传不上来,你们只好自己去下载wav类型的声音,名称改为一致的。

放个运行结果上来看看吧。

 另外提一句,我下载的wav声音是超级玛丽的游戏音乐,玩起来挺有意思的。

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/889331
推荐阅读
相关标签
  

闽ICP备14008679号