⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 world.java

📁 Multiagent system programmed using Java with Jason to simulate player interactivity in an MMORPG. Mu
💻 JAVA
字号:
//============================================================================================================================
// OpenGL Environment for Jason
// Author: Chris Willcocks
// Version: 1.1
//============================================================================================================================

import jason.asSyntax.Literal;
import jason.asSyntax.Structure;
import jason.asSyntax.Term;
import jason.environment.Environment;

import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Iterator;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.logging.Logger;

import javax.media.opengl.GLCanvas;

import com.sun.opengl.util.Animator;

public class world extends Environment
{

	// =======================================================================================================================
	// Agent Commands
	// =======================================================================================================================
	public static final Term jw = Literal.parseLiteral("joinEnv");
	public static final Term mv = Literal.parseLiteral("move");
	public static final Term mt = Literal.parseLiteral("moveTowards");
	public static final Term ch = Literal.parseLiteral("checkHealth");
	public static final Term b1 = Literal.parseLiteral("behaviour(1)");
	public static final Term b2 = Literal.parseLiteral("behaviour(2)");
	public static final Term b3 = Literal.parseLiteral("behaviour(3)");
	public static final Term ak = Literal.parseLiteral("attack");

	// Some basic colours
	public static final float[] red = { 1.0f, 0.0f, 0.0f };
	public static final float[] green = { 0.0f, 1.0f, 0.0f };
	public static final float[] blue = { 0.0f, 0.5f, 1.0f };
	public static final float[] purple = {1.0f, 1.0f, 0.0f };
	
	public static final int SPEED = 5; // Sleep time for each thread

	static Logger logger = Logger.getLogger(world.class.getName());

	// Used to return agent behaviour in O(log n) time complexity:
	protected static SortedMap<String, agent> agents = new TreeMap<String, agent>();

	private AgentActions agentActions;
	private SimulationEnvironment simulationEnvironment;
	private GLCanvas canvas;

	@Override
	public void init(String[] args)
	{
		agentActions = new AgentActions();
		setView(new SimulationEnvironment(agentActions));
	}

	@Override
	public boolean executeAction(String ag, Structure action)
	{
		logger.info(ag + " doing: " + action);
		try {
			if (action.equals(jw)) {
				agentActions.joinWorld(ag);
			} else if (action.equals(mv)) {
				agentActions.move(ag);
			} else if (action.equals(mt)) {
				agentActions.move(ag);
			} else if (action.equals(ch)) {
				agentActions.checkHealth(ag);
			} else if (action.equals(b1)) {
				agentActions.setBehaviour(ag, 'R');
			} else if (action.equals(b2)) {
				agentActions.setBehaviour(ag, 'S');
			} else if (action.equals(b3)) {
				agentActions.setBehaviour(ag, 'T');
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			Thread.sleep(SPEED);
		} catch (Exception e) {
			return true;
		}
		return true;
	}

	/** creates the agents perception */
	void updateControllerPercepts(String name)
	{
		clearPercepts();
		
		logger.info("ADDING " + name + " PERCEPTS");
		
		if (agents != null) {
			Iterator<String> iterator = agents.keySet().iterator();
			while (iterator.hasNext()) {
				String key;
				try {
					key = iterator.next();
				} catch (Exception e) {
					// Don't die if something goes wrong.
					return;
				}
				
				Literal health = Literal.parseLiteral("health(" +key+ ")," + agents.get(key).health);
				addPercept(name,health);
				
				// Literal die = Literal.parseLiteral(".kill_agent("+key+").");
				// addPercept(die);
			}
		}

	}

	public void setView(SimulationEnvironment view)
	{
		this.simulationEnvironment = view;
	}

	public SimulationEnvironment getView()
	{
		return simulationEnvironment;
	}

	class AgentActions
	{

		void joinWorld(String name) throws Exception
		{
			agent myAgent = new agent();
			if (name.charAt(0) == 'p') // Player agent joining, set the colours,
			// and the agent type
			{
				myAgent.type = 'P';
				myAgent.colour = blue;
			} else if (name.charAt(0) == 'e') // Enemy agent joining, set the
			// colours, and the agent type
			{
				myAgent.type = 'E';
				myAgent.colour = red;
			}

			if (agents != null)
				agents.put(name, myAgent);
		}

		void move(String name) throws Exception
		{
			if (agents.get(name) != null) {
				if (agents.get(name).health > 0) {
					agents.get(name).Update(0.5f);
					//if (agents.get(name).type == 'P') 

					// Player
					boolean wasCollision = false;
					Iterator<String> iterator = agents.keySet().iterator();
					while (iterator.hasNext()) {
						String key;
						try {
							key = iterator.next();
						} catch (Exception e) {
							// Very important: It's better not to render the frame than try and render a failed frame
							return;
						}

						if (agents.get(key).type != agents.get(name).type)
							if (agents.get(name).CollisionThreshold( // Reasoning process: If agent see's another of a different class, within threshold, attack
									agents.get(key).pos, 10.0f)) {   // else continue normal behaviour
								if (agents.get(key).health >= 0) {
									agents.get(name).MoveTowards(
											agents.get(key).pos, 0.5f);
									attack(name, key);
									wasCollision = true;
								}
							}

						if (!wasCollision) {
							// Init colours
							if (agents.get(name).type == 'P')
								agents.get(name).colour = blue;
							else
								agents.get(name).colour = red;
						}
					}
				}
			}

		}

		void checkHealth(String name) throws Exception
		{
			updateControllerPercepts(name);
		}
		
		void setBehaviour(String name, char type) throws Exception
		{
			agents.get(name).behaviour = type;
		}

		void attack(String name, String opponent)
		{
			if (agents.get(name) != null) {
				if (agents.get(opponent) != null)
					if (agents.get(name) != agents.get(opponent)) {
						if (agents.get(name).CollisionThreshold(
								agents.get(opponent).pos, 3.0f)) {
							if (agents.get(name).type == 'P')
								agents.get(name).colour = green;
							else
								agents.get(name).colour = purple;
							
							Literal health = Literal.parseLiteral("weak_opponent(" +opponent+ ")," + agents.get(opponent).health);
							addPercept(name,health);
							
							agents.get(opponent).health--;
							
							if (agents.get(opponent).health <= 0)
							{
								Literal deadAgent = Literal.parseLiteral("deadAgent(" +opponent+ ")");
								addPercept("controller",deadAgent);
							}
						} else {
						}
					}
			}
		}
	}

	class SimulationEnvironment
	{

		private static final long serialVersionUID = -3632480210943958117L;

		public SimulationEnvironment(AgentActions model)
		{
			Frame frame = new Frame("MMORPG World Simulation");
			frame.setSize(700, 600);
			frame.setVisible(true);
			canvas = new GLCanvas();
			canvas.addGLEventListener(new start());
			frame.add(canvas);
			final Animator animator = new Animator(canvas);
			frame.addWindowListener(new WindowAdapter()
			{
				public void windowClosing(WindowEvent e)
				{
					new Thread(new Runnable()
					{
						public void run()
						{
							animator.stop();
							System.exit(0);
						}
					}).start();
				}
			});
			frame.setVisible(true);
			animator.start();
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -