JAVA 炸弹人(二)

JAVA音效
JMF,JAVA多媒体框架。用这个框架播放音乐,和视频代码比较简单,只需要引入相关jar,就OK了。本来是想用这个框架的,后来还是用了JDK自带的。
        在把整个项目打成jar运行的时候,资源出现了路径错误,找不到这些音乐资源,如果用流去读这些资源,就可以解决此问题。
        下面是主要代码,音效类和音效管理类:
package util;

 

import java.io.BufferedInputStream;

import java.io.IOException;
import java.io.InputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

/***
 * 
 * @author Jack Lei
 * @Time 上午11:51:18 2016年1月13日
 * @desc
 */
public class Music {
	private MusicType type;
	private String filePath;
    private InputStream inputStream;
    private boolean running;
    private final int byteChunkSize = 1024;
    private byte[] muteData;

 
    public Music(MusicType type,String filePath){
        this.type = type;
        running = false;
        muteData = setMuteData();
        this.filePath = filePath;
    }
    
	public void playMusic() {
	try {
		    inputStream= this.getClass().getResourceAsStream(this.filePath);
	        inputStream = new BufferedInputStream(inputStream);
		    AudioInputStream in = AudioSystem.getAudioInputStream(inputStream);
			
	        AudioInputStream din = null;
	        AudioFormat baseFormat = in.getFormat();
	        AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
	                                                    baseFormat.getSampleRate(),
	                                                    16,
	                                                    baseFormat.getChannels(),
	                                                    baseFormat.getChannels() * 2,
	                                                    baseFormat.getSampleRate(),
	                                                    false);
	        din = AudioSystem.getAudioInputStream(decodedFormat, in);
	        stream(decodedFormat, din);
	        in.close();
		} catch (UnsupportedAudioFileException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	 private void stream(AudioFormat targetFormat, AudioInputStream din){
	        try{
	            byte[] data = new byte[byteChunkSize];
	            SourceDataLine line = getLine(targetFormat);
	            if(line != null){
	                line.start();
	                int nBytesRead = 0;
	                while(nBytesRead != -1 ){
	                    nBytesRead = din.read(data, 0, data.length);
	                    if(nBytesRead != -1){
                         line.write(data, 0, nBytesRead);
	                    }
	                    
//	                    while(pause && running){
//	                        wait(15);
//	                    }
	                }
	                line.drain();
	                line.stop();
	                line.close();
	                din.close();
	            }
	        }catch(Exception e){
	            System.err.println("Problem playing audio!");
	            e.printStackTrace();
	        }
	    }
	 
	 private SourceDataLine getLine(AudioFormat audioFormat){
	        SourceDataLine res = null;
	        DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
	        
	        try{
	            res = (SourceDataLine) AudioSystem.getLine(info);
	            res.open(audioFormat);
	        }catch(Exception e){
	            System.err.println("Could not get audio line!");
	            e.printStackTrace();
	        }

	        return res;
	    }
 
 
 
    public boolean isPlaying(){
        return running;
    }
    
    public void stop(){
    	this.running =false;
    }
    
    public void play(){
    	this.running = true;
    }
   
 
 
    private byte[] setMuteData(){
        byte[] x = new byte[byteChunkSize];
        for(int i = 0; i < x.length; i++){
            x[i] = 0;
        }

        return x;
    }
 
	/**
	 * @return the muteData
	 */
	public byte[] getMuteData() {
		return muteData;
	}
	/**
	 * @return the byteChunkSize
	 */
	public int getByteChunkSize() {
		return byteChunkSize;
	}

	/**
	 * @return the type
	 */
	public MusicType getType() {
		return type;
	}
	
	
    
	
    
}

/**
 * 
 */
package util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author Jack Lei
 * @Time 下午5:33:25 2016年1月11日
 * @desc 
 */
public class MusicManager {
	private static MusicManager instance ;
	private Thread musicThread;
	private static Map<MusicType,Music> musics = new HashMap<MusicType, Music>();
	
	private MusicManager(){
		musics.put(MusicType.BACK_GROUND,new Music(MusicType.BACK_GROUND, "/sound/back_sound.wav"));
		musics.put(MusicType.READY, new Music(MusicType.READY, "/sound/ready.wav"));
		musics.put(MusicType.BOOM, new Music(MusicType.BOOM, "/sound/boom.wav"));
		musics.put(MusicType.MOVE, new Music(MusicType.MOVE, "/sound/move.wav"));
		musics.put(MusicType.SET_BOMB, new Music(MusicType.SET_BOMB, "/sound/setbomb.wav"));
		musics.put(MusicType.WIN, new Music(MusicType.WIN, "/sound/win.wav"));
		musics.put(MusicType.FILE, new Music(MusicType.FILE, "/sound/faile.wav"));
		musics.put(MusicType.GET_ITEM, new Music(MusicType.GET_ITEM, "/sound/getItem.wav"));
		musics.put(MusicType.ENEMY_BOOM, new Music(MusicType.GET_ITEM, "/sound/enemy.wav"));
	}
	
	public static MusicManager getInstance(){
		if(instance == null){
			instance = new MusicManager();
		}
		return instance;
	}
	
	public void run(){
		musicThread = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
	 
					 while(true){
						 Iterator<Music> musicIterator = musics.values().iterator();
						 while(musicIterator.hasNext()){
							 Music music = musicIterator.next();
							 	if(music.getType() != MusicType.BACK_GROUND){
									 if(music.isPlaying()){
										 music.playMusic();;
										 music.stop();
								 }
							 }
						 
						 }
						 
						 
						 try {
							Thread.sleep(Common.THREAD_SLEEP_TIME);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					 }
			 
			}
		});
		
		musicThread.start();
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(true){
					musics.get(MusicType.BACK_GROUND).playMusic();;
					 
					 try {
						Thread.sleep(Common.THREAD_SLEEP_TIME);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
	
	public  void playerMusic(MusicType type){
		musics.get(type).play();
	}
	
	public void stopMusic(MusicType type){
		musics.get(type).stop();
	}
 
}

源代码:
后续:
这次就没写整个开发过程了,我会在新年假期时,写一个RPG类型,记录整个开发过程,希望自己能完成。哈哈。
Java中实现炸弹人的游戏源码会涉及到一些基本的游戏设计概念,包括用户界面、角色管理、碰撞检测、事件处理等。下面是一个简单的概述: 1. **创建角色类**:比如Player类和Bomb类,分别代表玩家和炸弹。它们通常包含位置、移动速度、生命值等属性。 2. **地图管理**:可以使用维数组表示游戏地图,每个元素对应一个格子,可能是空地、障碍物、玩家或炸弹。 3. **碰撞检测**:当炸弹爆炸或者玩家碰到炸弹时,需要检查周围是否有其他角色受到影响,并更新他们的状态。 4. **事件循环**:游戏主循环不断接收用户的输入并更新游戏状态,同时定时检查炸弹的计时器是否到达。 5. **图形绘制**:使用SwingJavaFX库来绘制游戏画面,显示角色和地图。 6. **控制台版本**:如果是在命令行环境中,可能只需要打印字符表示地图和玩家状态。 以下是一个简化的伪代码示例: ```java public class Bomberman { private Board board; private Player player; private Bomb[] bombs; public void startGame() { // 初始化地图和角色 board = new Board(); player = new Player(); bombs = new Bomb[board.getSize() * board.getSize()]; while (true) { handleInput(); // 处理用户输入 update(); // 更新游戏状态 render(); // 绘制游戏画面 } } private void handleInput() { if (keyPressed == 'b') { // 按B放置炸弹 placeBomb(player.getPosition()); } } private void update() { for (Bomb bomb : bombs) { if (bomb.explode()) { // 爆炸并检查碰撞 } } } private void render() { // 打印地图和角色 } } // 定义Player和Bomb类... ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值