You can subscribe to this list here.
2002 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(4) |
Nov
(25) |
Dec
(29) |
---|
From: <rw...@us...> - 2002-12-31 23:37:00
|
Update of /cvsroot/wett-p2p/org/wettp2p/communicationslayer In directory sc8-pr-cvs1:/tmp/cvs-serv20756/org/wettp2p/communicationslayer Modified Files: CommunicationsHandler.java Log Message: This version tests the DiscoveryManagers. Index: CommunicationsHandler.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/communicationslayer/CommunicationsHandler.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** CommunicationsHandler.java 17 Dec 2002 06:15:58 -0000 1.6 --- CommunicationsHandler.java 31 Dec 2002 23:36:55 -0000 1.7 *************** *** 14,17 **** --- 14,27 ---- * 8 - (Done - rben) Add Initialization method to be used in initializing * communications. + * + * Update 0.6: 12/31/2002 + * Moved the start() and stop() methods to be right after initialize(). It's + * easier to modify the file for testing that way. + * + * start() now creates two DiscoveryManagers on netPeerGroup. One looks for + * PeerAdvertisements and the other looks for PeerGroups. The DiscoveryManager + * classes are derived from Hashtable and you can retrieve the contents of their + * cache by calling get(String key). You'll have to cast the returned object + * into either a PeerAdvertisement or a PeerGroup. */ *************** *** 45,48 **** --- 55,59 ---- import net.jxta.protocol.PeerGroupAdvertisement; import net.jxta.protocol.PeerAdvertisement; + import net.jxta.protocol.PipeAdvertisement; import net.jxta.protocol.ModuleImplAdvertisement; *************** *** 80,84 **** * @author Robert Wei * @author Ray Benjamin ! * @version 0.5, 12/14/2002 * * $Author$ --- 91,95 ---- * @author Robert Wei * @author Ray Benjamin ! * @version 0.6, 12/31/2002 * * $Author$ *************** *** 115,127 **** private PipeService currentPipeService; public static void main(String args[]) { ! CommunicationsHandler myApp = CommunicationsHandler.getInstance(); ! try ! { myApp.initialize(); myApp.start(); } ! finally ! { myApp.stop(); System.exit(0); --- 126,156 ---- private PipeService currentPipeService; + private GroupDiscoveryManager gdm; + private PeerDiscoveryManager pdm; + public static void main(String args[]) { ! CommunicationsHandler myApp = CommunicationsHandler.getInstance(); ! ! try { myApp.initialize(); myApp.start(); + + Thread.sleep(300000); + + System.out.println("Peers found"); + Enumeration keys = myApp.pdm.keys(); + while ( keys.hasMoreElements() ) { + System.out.println((String) keys.nextElement()); + } + + System.out.println("Groups found"); + keys = myApp.gdm.keys(); + while ( keys.hasMoreElements() ) { + System.out.println((String) keys.nextElement()); + } } ! catch ( InterruptedException ie ) { ! } ! finally { myApp.stop(); System.exit(0); *************** *** 154,182 **** /** - * Initializes the JXTA platform and joins the default netPeer group. - **/ - private void startJXTA() { - logger.entering(classStr, "startJXTA"); - try { - logger.fine("Attempting to initialize JXTA"); - netPeerGroup = PeerGroupFactory.newNetPeerGroup(); - logger.fine("JXTA started"); - logger.fine("Joined Peergroup: " + netPeerGroup.getPeerGroupName()); - } - catch (Exception e) { - // Failed to initialize JXTA, print error message and quit. - String str = "Error: JXTA initialization failed due to exception: "; - logger.severe(str); - System.err.println(str); - logger.severe(e.toString()); - System.err.println(e.toString()); - e.printStackTrace(); - // NOTE: should find someway to insure that stacktrace is written into - // log... - System.exit(1); - } - } - - /** * This routine is used to start the CommunicationHandler processes that * receive, respond to, and forward messages. --- 183,186 ---- *************** *** 184,187 **** --- 188,195 ---- private void start() { logger.entering(classStr,"start"); + + pdm = new PeerDiscoveryManager(netPeerGroup); + gdm = new GroupDiscoveryManager(netPeerGroup); + // create input pipe // discover peers *************** *** 198,201 **** --- 206,213 ---- private void stop() { logger.entering(classStr,"stop"); + + pdm.stop(); + gdm.stop(); + // Notify peers of pending shutdown // shutdown propogate pipe *************** *** 203,206 **** --- 215,243 ---- // At this point, the CommunicationsHandler is shutdown and may be // stopped cleanly. + } + + /** + * Initializes the JXTA platform and joins the default netPeer group. + **/ + private void startJXTA() { + logger.entering(classStr, "startJXTA"); + try { + logger.fine("Attempting to initialize JXTA"); + netPeerGroup = PeerGroupFactory.newNetPeerGroup(); + logger.fine("JXTA started"); + logger.fine("Joined Peergroup: " + netPeerGroup.getPeerGroupName()); + } + catch (Exception e) { + // Failed to initialize JXTA, print error message and quit. + String str = "Error: JXTA initialization failed due to exception: "; + logger.severe(str); + System.err.println(str); + logger.severe(e.toString()); + System.err.println(e.toString()); + e.printStackTrace(); + // NOTE: should find someway to insure that stacktrace is written into + // log... + System.exit(1); + } } |
From: <rw...@us...> - 2002-12-31 23:36:12
|
Update of /cvsroot/wett-p2p/org/wettp2p/communicationslayer In directory sc8-pr-cvs1:/tmp/cvs-serv20208/org/wettp2p/communicationslayer Added Files: BasicDiscoveryManager.java Log Message: --- NEW FILE: BasicDiscoveryManager.java --- /* * DiscoveryThread.java * * Created on December 17, 2002, 11:02 AM * * <p>Copyright (C) 2002, Robert Wei</p> * * <p>This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version.</p> * * <p>This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details.</p> * * <p>You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.</p> * * Update 12/31/2002 * This class has been overhauled to serve as the base class for caching * discovery threads. * * Notes: * The base Advertisement class is unable to call the getAdvertisementType() method * without throwing an exception. It is necessary to cast all advertisements * into the correct type before trying to get its type. * * When performing discovery, you will almost certainly recieve more than one * copy of an advertisement per query. It is advisable to set up a cache for * these found advertisements using a well-known and fairly unique key (like * the peer name for peer advertisements) and storing them into the provided * Hashtable. * * It's probably bad object-oriented practice to extend Hashtable in this class * just so that its subclasses get the functionality for less code but hey, * it sounded like a good idea at the time... */ package org.wettp2p.communicationslayer; import java.io.*; import java.util.*; import java.util.logging.*; import org.wettp2p.communicationslayer.event.*; import org.wettp2p.peer.*; import net.jxta.discovery.DiscoveryService; import net.jxta.discovery.DiscoveryEvent; import net.jxta.discovery.DiscoveryListener; import net.jxta.document.AdvertisementFactory; import net.jxta.document.Advertisement; import net.jxta.document.MimeMediaType; import net.jxta.peergroup.PeerGroup; import net.jxta.protocol.DiscoveryResponseMsg; import net.jxta.protocol.PeerAdvertisement; /** * The BasicDiscoveryManager forms the basis for more specialized classes that * are keyed to a certain form of discovery. The discovery parameters are * supplied via one of the two constructors. BasicDiscoveryManager can send out * single discovery messages or be configured to send out messages at a set * interval. In addition to retrieving adverisements into the local cache, * BasicDiscoveryManager is also a DiscoveryListener that can be configured to * process advertisements through subclassing. * * The three major methods of controlling execution are doLocal(), doRemote() * and setInterval(). The thread object can be obtained by calling getThread() * and the associated peergroup can be obtained through getPeerGroup. * * Subclasses of BasicDiscoveryManager should contain a call to super() in their * constructors as the discovery parameters cannot be set any other way and the * background thread capability is also activated through the constructor. * You may also want to call doLocal(), doRemote(), or setInterval() from the * constructor of a subclass depending on the application. The <code>name</code> * variable is protected and defines the type of advertisements that the * associated instance of DiscoveryManager looks for. * * Though BasicDiscoveryManager does not use Hashtable, its subclasses can make * significant use of it as an advertisement cache. * * The BasicDiscoveryManager searches for generic advertisements by default and * stores them into the local cache where other classes can find them. The type * of discovery can be changed but it is still highly recommended that this * class be subclassed to provide specialized handling for specific advertisements. * * @author Robert Wei * @version 1.0 12/31/2002 */ public class BasicDiscoveryManager extends Hashtable implements Runnable, DiscoveryListener { /* Logger */ static Logger logger = Logger.getLogger(Peer.TOP_LOG_NAME + ".communicationshandler"); private static String classStr = "BasicDiscoveryManager"; // DiscoveryService Constants public static final int PEER = DiscoveryService.PEER; public static final int GROUP = DiscoveryService.GROUP; public static final int ADV = DiscoveryService.ADV; public static final int DEFAULT_PRIORITY = 4; protected MimeMediaType mimeXML = new MimeMediaType("text/xml"); protected String name = null; /* Parameters for the getRemoteAdvertisements() method * To be overridden in subclasses that define different DiscoveryThreads */ String peerID = null; int type = ADV; String attribute = null; String value = null; int threshold = 10; private PeerGroup home; // Thread and thread-control variables private volatile Thread myThread; private boolean doLocal = false; private boolean doRemote = false; // The interval between discovery requests. Defaults to -1 private int interval = -1; // Event Listeners // private Vector advertisementListeners = new Vector(); /** * Creates a new DiscoveryThread. * * @param pg The peergroup in which discovery will be performed * @param type Discovery type PEER, GROUP, ADV */ BasicDiscoveryManager(PeerGroup pg, int type) { super(); home = pg; this.type = type; createName(); start(); } /** * Creates a new DiscoveryThread * * @param pg The peergroup in which discovery will be performed * @param type Discovery type PEER, GROUP, ADV * @param attribute Attribute name to narrow disocvery to Valid values for * this parameter are null (don't care), or exact element name in the * advertisement of interest (e.g. "Name") * @param value Value of attribute to narrow disocvery to valid values for * this parameter are null (don't care), Exact value, or use of wild * card(s) (e.g. if a Advertisement defines FooBar , a value of "*bar", * "foo*", or "*ooB*", will return the Advertisement */ BasicDiscoveryManager(PeerGroup pg, int type, String attribute, String value) { this(pg, type); this.attribute = attribute; this.value = value; } /** * Shuts down the thread before destroying this class. */ protected void finalize() throws Throwable { stop(); super.finalize(); } String getPeerID() { return peerID; } int getThreshold() { return threshold; } int getInterval() { return interval; } int getType() { return type; } String getAttribute() { return attribute; } String getValue() { return value; } String getName() { return name; } /** * Generates the name of the object instance based on the type of * advertisement searched for. */ private void createName() { StringBuffer str = new StringBuffer(home.getPeerGroupName()); switch ( type ) { case 0: str.append(" <Peers" ); break; case 1: str.append(" <Groups" ); break; default: str.append(" <Advertisements"); } if ( attribute!=null ) { str.append( attribute ); str.append( "=" ); str.append( value ); } str.append( ">" ); name = str.toString(); } /** * Returns the handle to the thread that runs this class. */ Thread getThread() { logger.entering(classStr,"getThread"); return myThread; } /** * Returns the bound peergroup */ PeerGroup getPeerGroup() { logger.entering(classStr,"getPeerGroup"); return home; } /** * Sets the peerID of a specific peer to query */ void setPeerID(String peerID) { this.peerID = peerID; } /** * Sets the maximum number of discoveries that can be recieved from one peer */ void setThreshold(int threshold) { this.threshold = threshold; } /** * Sets the interval between discovery requests in thread mode. Time in * seconds. If the value is negative, the thread will perform remote * discovery only when it is explicitly told to do so through the doRemote() * method. * * Local discovery can only be called explicitly through doLocal(). */ void setInterval(int interval) { this.interval = interval; if ( interval > 0 ) doRemote(); else doRemote = false; } /** * Tells the thread to perform Remote Discovery on its next execution cycle. */ void doRemote() { logger.entering(classStr,"doRemote"); doRemote = true; } /** * Tells the thread to perform Local Discovery on its next execution cycle. */ void doLocal() { logger.entering(classStr,"doLocal"); doLocal = true; } /** * Starts the thread */ void start() { logger.entering(classStr,"start"); if ( myThread == null ) { myThread = new Thread(this, classStr + name); myThread.setPriority(DEFAULT_PRIORITY); myThread.start(); } } /** * Stops the thread */ void stop() { logger.entering(classStr,"stop"); myThread = null; } /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() * */ public void run() { logger.entering(classStr,"run"); int seconds = interval; Thread thisThread = Thread.currentThread(); while ( thisThread == myThread ) { seconds++; try { // Check to see if there are commands to be executed. if ( seconds > interval ) { seconds = 0; // Sends a remoteDiscoveryMessage and deflags doRemote if // the thread is not in continuous mode. if ( doRemote ) { if ( interval <= 0 ) { doRemote = false; } sendDiscoveryMessage(); } // Performs one local discovery if doLocal is flagged if ( doLocal ) { doLocal = false; discoverLocalAdvertisements(); } } // Wait 1 second Thread.sleep(1000); } catch (InterruptedException ie) { String str = "Thread [" + name + "] Interrupted"; logger.warning(str); System.err.println(str); return; } } } /** * Called by DiscoveryService when a discovery is made. This method * repackages the DiscoveryEvent as an AdvertisementEvent and calls * <code>fireAdvertisementEvent()</code> to send it to all registered * listeners. * * @param discoveryEvent the event message recieved from DiscoveryService */ public void discoveryEvent(net.jxta.discovery.DiscoveryEvent discoveryEvent) { logger.entering(classStr,"discoveryEvent"); DiscoveryResponseMsg res = discoveryEvent.getResponse(); PeerAdvertisement peerAdv; // Find out where the advertisement came from String peerString = res.getPeerAdv(); // Deserialize, cast, and report try { InputStream is = new ByteArrayInputStream( peerString.getBytes() ); peerAdv = (PeerAdvertisement) AdvertisementFactory.newAdvertisement(mimeXML, is); String str = name + ": Got a Discovery Response [" + res.getResponseCount() + " elements] from peer : " + peerAdv.getName(); logger.finest(str); } catch (IOException e) { String str = name + ": Cannot deserialize incoming PeerAdvertisement"; logger.warning(str); return; } // Obtain the enumeration of advertisements Enumeration enum = res.getResponses(); while ( enum.hasMoreElements() ) { String advString = (String) enum.nextElement(); Advertisement adv = null; // Deserialize advertisements try { InputStream is = new ByteArrayInputStream( advString.getBytes() ); adv = AdvertisementFactory.newAdvertisement(mimeXML, is); processAdvertisement(adv); } catch (IOException e) { String str = name + ": Cannot deserialize incoming Advertisement"; logger.warning(str); } } } /** * This method is called by the DiscoveryListener event handler after intial * processing and reporting has been done. The method is empty in the basic * implementation but subclasses can override this method to provide * specialized handling for the advertisements recieved. * * @param Advertisement the advertisement recieved from the * <code>DiscoveryListener</code>. */ protected void processAdvertisement(Advertisement adv) { logger.entering(classStr,"processAdvertisement"); } /** * This method can be called to send a discovery message. If this class is * run as a thread, the run method will call this method at the specified * interval. * * @param Advertisement the advertisement recieved from the * <code>DiscoveryListener</code>. */ void sendDiscoveryMessage() { logger.entering(classStr,"sendDiscoveryMessage"); DiscoveryService disco = home.getDiscoveryService(); disco.getRemoteAdvertisements(peerID, type, attribute, value, threshold, this); logger.finer(name + ": Sending Discovery Request" ); } /** * This method is not called by default in the base class but may be called * from subclasses to process the local cache. * * @param Advertisement the advertisement recieved from the * <code>DiscoveryListener</code>. */ void discoverLocalAdvertisements() { logger.entering(classStr,"discoverLocalAdvertisements"); DiscoveryService disco = home.getDiscoveryService(); try { Enumeration advs = disco.getLocalAdvertisements(type, attribute, value); logger.finer(name + ": Executing Local Discovery" ); while ( advs.hasMoreElements() ) { Advertisement adv = (Advertisement) advs.nextElement(); processAdvertisement(adv); } } catch (IOException ie) { String str = name + ": Cannot deserialize local Advertisement"; logger.warning(str); } } } |
From: <rw...@us...> - 2002-12-31 23:35:40
|
Update of /cvsroot/wett-p2p/org/wettp2p/communicationslayer In directory sc8-pr-cvs1:/tmp/cvs-serv19895/org/wettp2p/communicationslayer Added Files: GroupDiscoveryManager.java Log Message: --- NEW FILE: GroupDiscoveryManager.java --- /* * GroupDiscoveryManager.java * <p>Copyright (C) 2002, Robert Wei</p> * * <p>This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version.</p> * * <p>This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details.</p> * * <p>You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.</p> * * Created on December 31, 2002, 4:01 AM */ package org.wettp2p.communicationslayer; import java.util.*; import java.util.logging.*; import org.wettp2p.peer.*; import net.jxta.document.Advertisement; import net.jxta.exception.PeerGroupException; import net.jxta.peergroup.PeerGroup; import net.jxta.protocol.PeerGroupAdvertisement; /** * The GroupDiscoveryManager is a specialization of BasicDiscoveryManager that * looks for PeerGroups and caches them. This class can be used like a Hashtable * to access the cache of stored PeerGroup objects. * * @author Robert Wei * @version 1.0 12/31/2002 */ class GroupDiscoveryManager extends BasicDiscoveryManager { /* Logger */ static Logger logger = Logger.getLogger(Peer.TOP_LOG_NAME + ".communicationshandler"); private static String classStr = "GroupDiscoveryManager"; /** Creates a new instance of GroupDiscoveryManager */ public GroupDiscoveryManager(PeerGroup pg) { super(pg, GROUP); // Instructs the thread to perform one local discovery doLocal(); // Sets the thread to rebroadcast its discovery request every 60 seconds. setInterval(60); } /** * This method is called by the DiscoveryListener event handler after intial * processing and reporting has been done. The method is empty in the basic * implementation but subclasses can override this method to provide * specialized handling for the advertisements recieved. * * @param Advertisement the advertisement recieved from the * <code>DiscoveryListener</code>. * */ protected void processAdvertisement(Advertisement adv) { logger.entering(classStr, "processAdvertisement"); if ( adv instanceof PeerGroupAdvertisement ) { // Cast the advertisement as a PeerGroupAdvertisement PeerGroupAdvertisement pgadv = (PeerGroupAdvertisement) adv; try { // Create a PeerGroup object from the advertisement and get its name PeerGroup npg = getPeerGroup().newGroup(pgadv); String npgName = npg.getPeerGroupName(); // Add this PeerGroup to the cache if it does not already exist if ( !containsKey(npgName) ) { put(npgName, npg); logger.finer("New PeerGroup [" + npgName + "] discovered and added"); } else { logger.finest("PeerGroup [" + npgName + "] already exists"); } } catch (PeerGroupException pge) { String str = name + ": Unable to create PeerGroup from advertisement"; logger.warning(str); } } else { logger.warning(name + ": Advertisement is not a PeerGroupAdvertisement"); return; } } } |
From: <rw...@us...> - 2002-12-31 23:35:05
|
Update of /cvsroot/wett-p2p/org/wettp2p/communicationslayer In directory sc8-pr-cvs1:/tmp/cvs-serv19550/org/wettp2p/communicationslayer Added Files: PeerDiscoveryManager.java Log Message: --- NEW FILE: PeerDiscoveryManager.java --- /* * PeerDiscoveryManager.java * <p>Copyright (C) 2002, Robert Wei</p> * * <p>This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version.</p> * * <p>This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details.</p> * * <p>You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.</p> * * Created on December 31, 2002, 4:01 AM */ package org.wettp2p.communicationslayer; import java.util.*; import java.util.logging.*; import org.wettp2p.peer.*; import net.jxta.document.Advertisement; import net.jxta.exception.PeerGroupException; import net.jxta.peergroup.PeerGroup; import net.jxta.protocol.PeerAdvertisement; /** * The PeerDiscoveryManager is a specialization of BasicDiscoveryManager that * looks for PeerAdvertisements and caches them. This class can be used like a * Hashtable to access the cache of stored PeerAdvertisement objects. * * @author Robert Wei * @version 1.0 12/31/2002 */ class PeerDiscoveryManager extends BasicDiscoveryManager { /* Logger */ static Logger logger = Logger.getLogger(Peer.TOP_LOG_NAME + ".communicationshandler"); private static String classStr = "PeerDiscoveryManager"; /** Creates a new instance of PeerDiscoveryManager */ public PeerDiscoveryManager(PeerGroup pg) { super(pg, PEER); // Instructs the thread to perform one local discovery doLocal(); // Sets the thread to rebroadcast its discovery request every 60 seconds. setInterval(60); } /** * This method is called by the DiscoveryListener event handler after intial * processing and reporting has been done. The method is empty in the basic * implementation but subclasses can override this method to provide * specialized handling for the advertisements recieved. * * @param Advertisement the advertisement recieved from the * <code>DiscoveryListener</code>. */ protected void processAdvertisement(Advertisement adv) { logger.entering(classStr, "processAdvertisement"); if ( adv instanceof PeerAdvertisement ) { // Cast the advertisement as a PeerAdvertisement PeerAdvertisement padv = (PeerAdvertisement) adv; String pName = padv.getName(); // Add this Peer to the cache if it does not already exist if ( !containsKey(pName) ) { put(pName, padv); logger.finer("New Peer [" + pName + "] discovered and added"); } else { logger.finest("Peer [" + pName + "] already exists"); } } else { logger.warning(name + ": Advertisement is not a PeerAdvertisement"); return; } } } |
From: <rw...@us...> - 2002-12-17 23:39:34
|
Update of /cvsroot/wett-p2p/org/wettp2p/communicationslayer/event In directory sc8-pr-cvs1:/tmp/cvs-serv26198/event Log Message: Directory /cvsroot/wett-p2p/org/wettp2p/communicationslayer/event added to the repository |
From: <rw...@us...> - 2002-12-17 23:37:32
|
Update of /cvsroot/wett-p2p/org/wettp2p/communicationslayer/event In directory sc8-pr-cvs1:/tmp/cvs-serv26436/org/wettp2p/communicationslayer/event Added Files: AdvertisementEvent.java AdvertisementListener.java Log Message: A cloneable event representing a single advertisement and its origin. --- NEW FILE: AdvertisementEvent.java --- /* * AdvertisementEvent.java * * Created on December 17, 2002, 1:19 PM * * <p>Copyright (C) 2002, Robert Wei</p> * * <p>This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version.</p> * * <p>This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details.</p> * * <p>You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.</p> */ package org.wettp2p.communicationslayer.event; import java.util.*; import net.jxta.protocol.PeerAdvertisement; import net.jxta.document.Advertisement; /** * AdvertisementEvent - Encapsulates an advertisement and its origin. * Fired from a DiscoveryThread for each advertisement discovered. * * @author Robert Wei * @version 1.0 12/17/2002 */ public class AdvertisementEvent extends EventObject implements Cloneable{ private PeerAdvertisement origin; private Advertisement advertisement; /** Creates a new instance of AdvertisementEvent */ public AdvertisementEvent(Object src) { super(src); } /** * @return the PeerAdvertisement of the peer who originated this message. */ public PeerAdvertisement getOrigin() { return origin; } public void setOrigin(PeerAdvertisement peerAdv) { origin = peerAdv; } /** * Note: The result of this method must be cast into it's proper type * It is highly recommended that you test it first with getAdvertisementType * before casting. * * @return the Advertisement */ public Advertisement getAdvertisement() { return advertisement; } public void setAdvertisement(Advertisement adv) { advertisement = adv; } /** * Returns a clone of the current object */ public Object clone() { AdvertisementEvent copy = new AdvertisementEvent(source); copy.setOrigin((PeerAdvertisement) origin.clone()); copy.setAdvertisement((Advertisement) advertisement.clone()); return copy; } } --- NEW FILE: AdvertisementListener.java --- /* * AdvertisementListener.java * * Created on December 17, 2002, 1:51 PM * * <p>Copyright (C) 2002, Robert Wei</p> * * <p>This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version.</p> * * <p>This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details.</p> * * <p>You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.</p> */ package org.wettp2p.communicationslayer.event; /** * AdvertisementListener interface - classes that implement this interface can * register themselves with a DiscoveryThread to recieve asynchronous * notification of the arrival of new advertisements. * * @author Robert Wei * @version 1.0 12/17/2002 */ public interface AdvertisementListener extends java.util.EventListener { void advertisementEvent(AdvertisementEvent event); } |
From: <rw...@us...> - 2002-12-17 23:37:14
|
Update of /cvsroot/wett-p2p/org/wettp2p/communicationslayer In directory sc8-pr-cvs1:/tmp/cvs-serv26972/org/wettp2p/communicationslayer Added Files: DiscoveryThread.java Log Message: A dedicated DiscoveryListener that runs in its own thread. --- NEW FILE: DiscoveryThread.java --- /* * DiscoveryThread.java * * Created on December 17, 2002, 11:02 AM * * <p>Copyright (C) 2002, Robert Wei</p> * * <p>This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version.</p> * * <p>This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details.</p> * * <p>You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.</p> * * Comments and Usage Notes * This class basically wraps the DiscoveryService.getRemoteAdvertisements() * method into a thread and to fire off an Event that could be recieved by more * than one listener. It is intended to be run as a low-priority thread that * occasionally scans its peergroup context for new advertisements. It can be * extended to discover peergroups or peers as well as to find specific * advertisement types. * * Problems and Issues * There has to be some way to make this class fire an AdvertisementEvent only * when it receives an advertisement that has not already been cached. * * Future Work * Add a logger and error-reporting code. * With slight changes, instances of this class might be configured to discover * any Advertisement without the need to extend it. */ package org.wettp2p.communicationslayer; import java.io.*; import java.util.*; import org.wettp2p.communicationslayer.event.*; import net.jxta.discovery.DiscoveryService; import net.jxta.discovery.DiscoveryEvent; import net.jxta.discovery.DiscoveryListener; import net.jxta.document.AdvertisementFactory; import net.jxta.document.Advertisement; import net.jxta.document.MimeMediaType; import net.jxta.peergroup.PeerGroup; import net.jxta.protocol.DiscoveryResponseMsg; import net.jxta.protocol.PeerAdvertisement; /** * DiscoveryThread. A thread class that continually searches for * advertisements (of a specific type) in one peergroup. Does initial * processing of the Discovery * * @author Robert Wei * @version 1.0 12/17/2002 */ public class DiscoveryThread implements Runnable, DiscoveryListener { MimeMediaType mimeXML = new MimeMediaType("text/xml"); // The interval between discovery requests. Defaults to 10 seconds protected int requestInterval = 10000; /* Parameters for the getRemoteAdvertisements() method * To be overridden in subclasses that define different DiscoveryThreads */ protected String peerID = null; protected int type = DiscoveryService.ADV; protected String attribute = null; protected String value = null; protected int threshold = 10; private PeerGroup home; // Event Listeners private Vector advertisementListeners = new Vector(); /** * Creates a new DiscoveryThread * * @param <code>pg</code> The peergroup in which discovery will be performed */ public DiscoveryThread(PeerGroup pg) { home = pg; } /** * Changes the time between discovery requests. * * @param <code>interval</code> the new request interval. */ public synchronized void setRequestInterval(int interval) { requestInterval = interval; } /** * @return the current requestInterval */ public int getRequestInterval() { return requestInterval; } /** * @return the name of the peergroup */ public String getPeerGroupName() { return home.getPeerGroupName(); } /** * Package-level access only * * @return the peergroup's reference */ PeerGroup getPeerGroup() { return home; } /** * Sends a copy of the event to each registered listener. */ private synchronized void fireAdvertisementEvent(AdvertisementEvent ev) { Iterator i = advertisementListeners.iterator(); while ( i.hasNext() ) { AdvertisementListener listener = (AdvertisementListener) i.next(); listener.advertisementEvent((AdvertisementEvent) ev.clone()); } } /** * Registers a class as an AdvertisementListener */ public synchronized void addAdvertisementListener(AdvertisementListener listener) { advertisementListeners.add(listener); } /** * Creates a new <code>AdvertisementEvent</code> * from a <code>PeerAdvertisement</code> (originating peer) and * an <code>Advertisement<code> (message content) */ protected AdvertisementEvent createAdvertisementEvent(PeerAdvertisement peerAdv, Advertisement adv) { AdvertisementEvent ev = new AdvertisementEvent(this); ev.setOrigin(peerAdv); ev.setAdvertisement(adv); return ev; } /** * Called by DiscoveryService when a discovery is made. This method * repackages the DiscoveryEvent as an AdvertisementEvent and calls * <code>fireAdvertisementEvent()</code> to send it to all registered * listeners. * * @param discoveryEvent the event message recieved from DiscoveryService */ public void discoveryEvent(net.jxta.discovery.DiscoveryEvent discoveryEvent) { DiscoveryResponseMsg res = discoveryEvent.getResponse(); PeerAdvertisement peerAdv; // Get the responding peer's advertisement String peerString = res.getPeerAdv(); // Deserialize the advertisement. try { InputStream is = new ByteArrayInputStream( peerString.getBytes() ); peerAdv = (PeerAdvertisement) AdvertisementFactory.newAdvertisement(mimeXML, is); String logMsg = "Got a Discovery Response [" + res.getResponseCount() + " elements] from peer : " + peerAdv.getName(); } catch (IOException e) { // Invalid peer, skip this message and log a warning return; } // Obtain the enumeration of advertisements Enumeration enum = res.getResponses(); while ( enum.hasMoreElements() ) { String advString = (String) enum.nextElement(); Advertisement adv = null; // Deserialize advertisements try { InputStream is = new ByteArrayInputStream( advString.getBytes() ); adv = AdvertisementFactory.newAdvertisement(mimeXML, is); String logMsg = "Discovered Advertisement: " + adv.getAdvertisementType(); // Wrap the advertisement into an event and fire it AdvertisementEvent event = createAdvertisementEvent(peerAdv, adv); fireAdvertisementEvent(event); } catch (IOException e) { // Unable to read advertisement, log a warning and skip it } } } /** When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() * */ public void run() { while ( true ) { DiscoveryService disco = home.getDiscoveryService(); disco.getRemoteAdvertisements(peerID, type, attribute, value, threshold, this); Thread.sleep(requestInterval); } } } |
From: <rw...@us...> - 2002-12-17 18:39:37
|
Update of /cvsroot/wett-p2p/org/wettp2p/messagehandler In directory sc8-pr-cvs1:/tmp/cvs-serv14250/org/wettp2p/messagehandler Modified Files: Message.java Log Message: Message.DefaultImpl now implements Serializable Index: Message.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/messagehandler/Message.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Message.java 12 Nov 2002 02:29:38 -0000 1.3 --- Message.java 17 Dec 2002 18:39:00 -0000 1.4 *************** *** 80,87 **** * implementation of the Message interface. * ! * @author Paulo Mouat ! * @version 1.0, 2002/10/25 **/ ! public static class DefaultImpl implements Message { /** the type of the message, stored as a class object */ --- 80,87 ---- * implementation of the Message interface. * ! * @author Paulo Mouat, Robert Wei ! * @version 1.4, 2002/12/16 **/ ! public static class DefaultImpl implements Message, java.io.Serializable { /** the type of the message, stored as a class object */ |
From: <rw...@us...> - 2002-12-17 06:16:02
|
Update of /cvsroot/wett-p2p/org/wettp2p/communicationslayer In directory sc8-pr-cvs1:/tmp/cvs-serv8956/org/wettp2p/communicationslayer Modified Files: CommunicationsHandler.java Log Message: Fixed a bug that prevented the program from properly constructing the WETT group's URL. Modified the main method to properly shut down the system. Index: CommunicationsHandler.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/communicationslayer/CommunicationsHandler.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** CommunicationsHandler.java 17 Dec 2002 03:39:25 -0000 1.5 --- CommunicationsHandler.java 17 Dec 2002 06:15:58 -0000 1.6 *************** *** 100,108 **** // The globally unique ID for the WETT peergroup (generated on 11/21/2002 by Robert Wei) ! private final String WETT_GID = "urn:jxta:uuid-ECFFFA4E82E348AF9043A8A0844FE5CB02"; private static final String WETT_GROUP_NAME = "WETT"; private static final String WETT_GROUP_DESCRIPTION = "Web Enabled Table Top - Peer-to-Peer"; private static final int TIMEOUT = 3000; private PeerGroup netPeerGroup; private PeerGroup wettPeerGroup; --- 100,110 ---- // The globally unique ID for the WETT peergroup (generated on 11/21/2002 by Robert Wei) ! private final String WETT_GID = "jxta:uuid-ECFFFA4E82E348AF9043A8A0844FE5CB02"; private static final String WETT_GROUP_NAME = "WETT"; private static final String WETT_GROUP_DESCRIPTION = "Web Enabled Table Top - Peer-to-Peer"; private static final int TIMEOUT = 3000; + private MimeMediaType mimeXML = new MimeMediaType("text/xml"); + private PeerGroup netPeerGroup; private PeerGroup wettPeerGroup; *************** *** 114,120 **** public static void main(String args[]) { ! CommunicationsHandler myApp = CommunicationsHandler.getInstance(); ! myApp.startJXTA(); ! myApp.initialize(); } --- 116,130 ---- public static void main(String args[]) { ! CommunicationsHandler myApp = CommunicationsHandler.getInstance(); ! try ! { ! myApp.initialize(); ! myApp.start(); ! } ! finally ! { ! myApp.stop(); ! System.exit(0); ! } } *************** *** 134,137 **** --- 144,148 ---- String str = "ERROR: Unable to join or create Wett peergroup."; logger.severe(str); + e.printStackTrace(System.err); System.err.println(str); System.exit(1); // fail *************** *** 214,218 **** try { ! // get the diescvoer and pipe services for the Wett peergroup wettDiscoveryService = wettPeerGroup.getDiscoveryService(); wettPipeService = wettPeerGroup.getPipeService(); --- 225,229 ---- try { ! // get the discovery and pipe services for the Wett peergroup wettDiscoveryService = wettPeerGroup.getDiscoveryService(); wettPipeService = wettPeerGroup.getPipeService(); *************** *** 420,427 **** } /** - * A default-level access method for other communicationslayer classes to - * obtain a reference to the WETT peergroup. - * * @return the WETT peergroup */ --- 431,439 ---- } + // + // Package level accessors for Communications Layer classes + // + /** * @return the WETT peergroup */ |
From: <rw...@us...> - 2002-12-17 04:00:38
|
Update of /cvsroot/wett-p2p/org/wettp2p/communicationslayer In directory sc8-pr-cvs1:/tmp/cvs-serv8001/org/wettp2p/communicationslayer Added Files: OutboundMessageQueue.java Log Message: The default implementation of an OutboundMessageQueue. Logging code has been included. --- NEW FILE: OutboundMessageQueue.java --- /* * OutboundMessageQueue.java * * Created on December 16, 2002, 6:03 PM */ package org.wettp2p.communicationslayer; import org.wettp2p.messagehandler.Message; import org.wettp2p.messagehandler.MessageQueue; import org.wettp2p.messagehandler.MessageConsumer; import net.jxta.document.MimeMediaType; import net.jxta.peergroup.PeerGroup; import net.jxta.pipe.PipeService; import java.util.*; import java.io.*; import org.wettp2p.peer.*; import java.util.logging.*; /** * This is a message queue (similar to Paulo Mouat's <code>MessageQueue</code> * class) that holds * JXTA Messages (class: <code>net.jxta.endpoint.Message</code>) * instead of * WETT Messages (class: <code>org.wettp2p.messagehandler.Message</code>). * It only recieves * input via its <code>MessageConsumer</code> interface. This default * implementation serializes the entire message into an element titled * <code><Wett:SerialMessage></code>. By overriding the processMessage() * method, it is possible to create JXTA Messages in other ways. * * Suggested Usage: * 1. Create the OutboundMessageQueue around a PeerGroup. The queue represents * the queue of messages associated with that particular peergroup. This * implementation defaults to using the WETT peergroup. * * 2. Subscribe the queue to the desired messagetypes or MessageProducers using * one of the the subscribe() methods. * * 3. Pass the queue as an argument to the constructor of a * <code>Transmitter</code> class that will attempt to send messages off of the * queue. * * * To Do: * 1. Add a method to <code>CommunicationsHandler</code> to allow retrieval of * the WETT peergroup. * * 2. Test this class to make sure that the messages it sends are recognized by * the MessageHandler of the recieving peer. * * 2a. If not, reimplement processMessage to get a valid message. * * * Future Work: * 1. Provide facilities to name instances of this class and possibly retrieve * them by name from a queue. * * * Copyright (C) 2002, Robert Wei * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * @author Robert Wei * @version 1.0, 12/16/2002 **/ public class OutboundMessageQueue extends MessageConsumer.DefaultImpl { /* Logger */ static Logger logger = Logger.getLogger(Peer.TOP_LOG_NAME + ".communicationshandler"); private static String classStr = "OutboundMessageQueue"; private PeerGroup group; private LinkedList queue; /** * Default constructor. * This creates an OutboundMessageQueue for the default WettPeerGroup **/ public OutboundMessageQueue() { // Call the constructor on the WETT peergroup this( CommunicationsHandler.getInstance().getWettGroup() ); } /** * Default constructor. * This creates an OutboundMessageQueue for the default WettPeerGroup **/ public OutboundMessageQueue( PeerGroup pg ) { // Associates this MessageQueue with the supplied peergroup. group = pg; } /** * Accessor method on the peergroup for use by other classes in * communicationslayer. * * @return the <code>PeerGroup</code> that this object is associated with. **/ PeerGroup getPeerGroup() { logger.entering(classStr, "getPeerGroup"); return group; } /** * Public accessor method on the peergroup. * * @return the name of the <code>PeerGroup</code> that this object is * associated with. **/ public String getPeerGroupName() { logger.entering(classStr, "getPeerGroupName"); return group.getPeerGroupName(); } /** * Processes the message into a form that can be transmitted over the JXTA * network. * * Override this method in subclasses to process the message in a different * manner. * * @param message the <code>Message</code>. **/ protected net.jxta.endpoint.Message processMessage( Message message ) throws Exception { logger.entering(classStr, "processMessage"); // Serialize the message into a byte array ByteArrayOutputStream bstream = new ByteArrayOutputStream(); try { ObjectOutputStream ostream = new ObjectOutputStream(bstream); ostream.writeObject(message); } catch (IOException ie) { throw new Exception("Failed to serialize message", ie); } byte[] bytes = bstream.toByteArray(); // Create the MimeType MimeMediaType mimeType = new MimeMediaType("application/octet-stream"); // Create a new message using the group's PipeService net.jxta.endpoint.Message msg = group.getPipeService().createMessage(); // Add the bytes as a new element in the message msg.addElement(msg.newMessageElement("Wett:SerialMessage", mimeType, bytes)); return msg; } /** * The MessageConsumer's DefaultImpl calls this method to process messages * it recieves via the MessageHandler. * * @param message the <code>Message</code>. **/ protected synchronized void doIt( Message wettMessage ) { logger.entering(classStr, "doIt"); net.jxta.endpoint.Message jxtaMessage = null; // Process the message if( wettMessage == null ) // disallow nulls return; try { jxtaMessage = processMessage(wettMessage); } catch (Exception e) { String str = "Message failed to process: Not entered into queue"; logger.warning(str); System.err.println(str); return; } queue.add( jxtaMessage ); } /** * Retrieves and removes the first message from the queue or null if there * are none. * * @return the <code>Message</code> at the start of * the queue or <code>null</code> if the queue is empty. **/ public synchronized net.jxta.endpoint.Message get() { logger.entering(classStr, "get"); net.jxta.endpoint.Message first = null; try { first = (net.jxta.endpoint.Message) queue.removeFirst(); } catch( java.util.NoSuchElementException e ) { System.out.println( this + ": get(), queue is empty!" ); // ignore exception silently } return first; } /** * Retrieves (without removing) the <code>Message</code> * at the start of the queue. This method is synchronized. * @return the <code>Message</code> at the start of * the queue or <code>null</code> if the queue is empty. **/ public synchronized net.jxta.endpoint.Message peek() { logger.entering(classStr, "peek"); net.jxta.endpoint.Message first = null; try { first = (net.jxta.endpoint.Message) queue.getFirst(); } catch( java.util.NoSuchElementException e ) { System.out.println( this + ": peek(), queue is empty!" ); // ignore exception silently } return first; } } |
From: <rw...@us...> - 2002-12-17 03:39:28
|
Update of /cvsroot/wett-p2p/org/wettp2p/communicationslayer In directory sc8-pr-cvs1:/tmp/cvs-serv2830/org/wettp2p/communicationslayer Modified Files: CommunicationsHandler.java Log Message: Added: <default> PeerGroup getWettPeerGroup() Allows other members of the communicationslayer to obtain a reference to the WETT peergroup. Removed: MessageConsumer interface and all associated methods The MessageConsumer is now implemented by OutboundMessageQueue and its subclasses. Index: CommunicationsHandler.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/communicationslayer/CommunicationsHandler.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** CommunicationsHandler.java 15 Dec 2002 00:30:30 -0000 1.4 --- CommunicationsHandler.java 17 Dec 2002 03:39:25 -0000 1.5 *************** *** 6,12 **** * * Phase 1 goals: ! * 1 (Done) - Initialize JXTA / join peergroup: netpeer ! * 2 (Done) - Join peergroup: WETT ! * 3 - Implement the MessageConsumer interface * 4 - Implement the MessageProducer interface * 5 - Send messages to every member of the peergroup --- 6,12 ---- * * Phase 1 goals: ! * 1 (Done - rwei) - Initialize JXTA / join peergroup: netpeer ! * 2 (Done - rwei) - Join peergroup: WETT ! * 3 (Done in <code>OutboundMessageQueue</code> - rwei) - Implement the MessageConsumer interface * 4 - Implement the MessageProducer interface * 5 - Send messages to every member of the peergroup *************** *** 90,94 **** * */ ! public class CommunicationsHandler implements MessageConsumer, MessageProducer { /* Logger */ --- 90,94 ---- * */ ! public class CommunicationsHandler implements MessageProducer { /* Logger */ *************** *** 399,411 **** new URL("urn", "", WETT_GID)); } ! ! public void subscribe(Class type) { ! logger.entering(classStr,"subscribe", type); ! } ! ! public void subscribe(String producerName) { ! logger.entering(classStr,"subscribe", producerName); ! } ! private void createTransmitter(OutputPipe pipe, Message message) { logger.entering(classStr,"createTransmitter"); --- 399,403 ---- new URL("urn", "", WETT_GID)); } ! private void createTransmitter(OutputPipe pipe, Message message) { logger.entering(classStr,"createTransmitter"); *************** *** 417,436 **** /** - * Receives the passed <code>Message</code> from the MessageHandler, - * the module that handles communications within the Wett-p2p - * application. - * - * There should be two types of messages we are concerned with: messages - * bound for other peers and messages that are commands to the - * CommunicationsHander. - * - * @param message the <code>Message</code> to be received. - * - */ - public void receive(Message message) { - logger.entering(classStr,"receive", message); - } - - /** * Sends the passed <code>Message</code> to the MessageHandler which * sends the message to it's appropriate destination based on the class --- 409,412 ---- *************** *** 442,445 **** --- 418,431 ---- public void send(Message message) { logger.entering(classStr,"send", message); + } + + /** + * A default-level access method for other communicationslayer classes to + * obtain a reference to the WETT peergroup. + * + * @return the WETT peergroup + */ + PeerGroup getWettGroup() { + return wettPeerGroup; } |
From: <rb...@us...> - 2002-12-15 00:30:32
|
Update of /cvsroot/wett-p2p/org/wettp2p/communicationslayer In directory sc8-pr-cvs1:/tmp/cvs-serv29583 Modified Files: CommunicationsHandler.java Log Message: I've finished refactoring the original code so that we now have more flexible memethods which will be needed when we use peer groups other than wettPeerGroup. I also added variables to track the currentPeerGroup, currentDiscoveryService and currentPipeService. We still need to add processes, probably seperate classes that will handle messages comming in and going out through the MessageHandler interface and messages going out and coming in through the JXTA interface. Index: CommunicationsHandler.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/communicationslayer/CommunicationsHandler.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** CommunicationsHandler.java 11 Dec 2002 04:28:59 -0000 1.3 --- CommunicationsHandler.java 15 Dec 2002 00:30:30 -0000 1.4 *************** *** 62,83 **** * CommunicationsHandler class. Manages and controls network traffic. * ! * Copyright (C) 2002, Robert Wei, Ray Benjamin * ! * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 ! * of the License, or (at your option) any later version. * ! * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ! * GNU General Public License for more details. * ! * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software ! * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * @author Robert Wei ! * @version 0.3, 2002/11/21 * * $Author$ --- 62,84 ---- * CommunicationsHandler class. Manages and controls network traffic. * ! * <p>Copyright (C) 2002, Robert Wei, Ray Benjamin</p> * ! * <p>This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 ! * of the License, or (at your option) any later version.</p> * ! * <p>This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ! * GNU General Public License for more details.</p> * ! * <p>You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software ! * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.</p> * * @author Robert Wei ! * @author Ray Benjamin ! * @version 0.5, 12/14/2002 * * $Author$ *************** *** 106,116 **** private PeerGroup netPeerGroup; private PeerGroup wettPeerGroup; private DiscoveryService wettDiscoveryService; private PipeService wettPipeService; public static void main(String args[]) { CommunicationsHandler myApp = CommunicationsHandler.getInstance(); myApp.startJXTA(); ! myApp.createWettGroup(); } --- 107,120 ---- private PeerGroup netPeerGroup; private PeerGroup wettPeerGroup; + private PeerGroup currentPeerGroup; private DiscoveryService wettDiscoveryService; + private DiscoveryService currentDiscoveryService; private PipeService wettPipeService; + private PipeService currentPipeService; public static void main(String args[]) { CommunicationsHandler myApp = CommunicationsHandler.getInstance(); myApp.startJXTA(); ! myApp.initialize(); } *************** *** 123,127 **** startJXTA(); // try to find the WettGroup ! // if it can't be found, create it try { joinWettGroup(); --- 127,131 ---- startJXTA(); // try to find the WettGroup ! // if it can't be found, create it and join it try { joinWettGroup(); *************** *** 133,137 **** System.exit(1); // fail } ! // Join the Wett group. } --- 137,143 ---- System.exit(1); // fail } ! // Create a propogate pipe and a input pipe and advertise them ! // Create the process that searches for and connects to other members ! // of the group we are currently subscribed to. } *************** *** 162,165 **** --- 168,198 ---- /** + * This routine is used to start the CommunicationHandler processes that + * receive, respond to, and forward messages. + */ + private void start() { + logger.entering(classStr,"start"); + // create input pipe + // discover peers + // discover peer input pipes + // construct output pipe connected to peer input pipes + // send greeting message + // forward peer information to main application + } + + /** + * This methods stops the CommunicationHander processes that receive, + * respond to, and forward messages. + */ + private void stop() { + logger.entering(classStr,"stop"); + // Notify peers of pending shutdown + // shutdown propogate pipe + // shutdown input pipe + // At this point, the CommunicationsHandler is shutdown and may be + // stopped cleanly. + } + + /** * Joins the WettGroup if it exists and creates and joins the group if it * does not exist. *************** *** 170,176 **** logger.info("Attempting to Discover the WettGroup."); // get the discovery service. ! DiscoveryService discoveryService = netPeerGroup.getDiscoveryService(); ! Enumeration ae = null; // holds discovered peers // Loop until we discover WettGroup or until we've exhausted the --- 203,308 ---- logger.info("Attempting to Discover the WettGroup."); + wettPeerGroup = findPeerGroup(netPeerGroup,WETT_GROUP_NAME); + if (wettPeerGroup == null) { + wettPeerGroup = createPeerGroup(netPeerGroup, + WETT_GROUP_NAME, + WETT_GROUP_DESCRIPTION, + mkWettGroupID()); + } + + currentPeerGroup = wettPeerGroup; + + try { + // get the diescvoer and pipe services for the Wett peergroup + wettDiscoveryService = wettPeerGroup.getDiscoveryService(); + wettPipeService = wettPeerGroup.getPipeService(); + + currentDiscoveryService = wettDiscoveryService; + currentPipeService = wettPipeService; + } + catch (Exception e) { + String str = "Error getting services from Wett peergroup"; + logger.severe(str); + System.err.println(str); + throw e; + } + + logger.info("Web Enabled Table Top - Peer-to-Peer is on-line!"); + } // end joinWettGroup() + + /** + * This routine will search for the given group and join it if found or + * create it and join it if it's not found. + * + * @param groupName A <code>String</code> containing the name of the + * desired group. + * + * @param groupDescription A <code>String</code> describing the group. + * + * @param groupID A <code>PeerGroupID</code> associated with the group. + * + * @return A <code>PeerGroup</code> object containing the information about the + * peer group. + */ + private PeerGroup findOrCreateGroup(PeerGroup parentGroup, + String groupName, + String groupDescription, + PeerGroupID groupID) + throws Exception + { + PeerGroup peerGroup = null; + logger.entering(classStr, "findOrCreateGroup"); + + peerGroup = findPeerGroup(parentGroup,groupName); + + if (peerGroup == null) { + peerGroup = createPeerGroup(parentGroup, groupName, groupDescription, groupID); + } + + return peerGroup; + } // end method + + private void moveToPeerGroup(PeerGroup peerGroup) throws Exception { + logger.entering(classStr, "moveToPeerGroup"); + + logger.info("Moving from " + currentPeerGroup.getPeerGroupName() + + " to " + peerGroup.getPeerGroupName() + "."); + currentPeerGroup = peerGroup; + try { + // get the diescvoer and pipe services for the Wett peergroup + currentDiscoveryService = currentPeerGroup.getDiscoveryService(); + currentPipeService = currentPeerGroup.getPipeService(); + } + catch (Exception e) { + String str = "Error getting services from Peer Group " + + currentPeerGroup.getPeerGroupName() + "."; + logger.severe(str); + System.err.println(str); + throw e; + } + } + + /** + * This method searches for the peer group named in the argument + * and returns the group if found or null if the group is not found. + * + * @param <code>groupName</code> a <code>String</code> containing the name + * of the group we are looking for. + * + * @return A reference to the <code>PeerGroup</code> found, it it's found + * or <code>null</code>. + */ + private PeerGroup findPeerGroup(PeerGroup parentGroup, + String groupName) + throws Exception + { + logger.entering(classStr, "findPeerGroup"); + PeerGroup peerGroup = null; + int count = DEFAULT_RETRY_COUNT; + logger.info("Attempting to Discover the " + groupName + " peer group."); + // get the discovery service. ! DiscoveryService discoveryService = parentGroup.getDiscoveryService(); ! Enumeration ae = null; // holds discovered groups // Loop until we discover WettGroup or until we've exhausted the *************** *** 181,185 **** // the Wett peergroup advertisement ae = discoveryService.getLocalAdvertisements( ! DiscoveryService.GROUP, "Name", WETT_GROUP_NAME); // If we found the advetisement, we are done --- 313,317 ---- // the Wett peergroup advertisement ae = discoveryService.getLocalAdvertisements( ! DiscoveryService.GROUP, "Name", groupName); // If we found the advetisement, we are done *************** *** 189,193 **** // If we did not find it, we send a discovery request discoveryService.getRemoteAdvertisements(null, ! DiscoveryService.GROUP, "Name", WETT_GROUP_NAME, 1, null); // Sleep to allow time for peers to respond to the discovery --- 321,325 ---- // If we did not find it, we send a discovery request discoveryService.getRemoteAdvertisements(null, ! DiscoveryService.GROUP, "Name", groupName, 1, null); // Sleep to allow time for peers to respond to the discovery *************** *** 205,319 **** } // end while - PeerGroupAdvertisement wettGroupAdv = null; - - // See if we found the Wett Group advertisement. If we didn't, - // then either we are the first peer to join or no other peers are up. - // In either case, we must create the group. if (ae == null || !ae.hasMoreElements()) { ! logger.info("Could not find the Wett peergroup; creating one"); ! ! try { ! ! // create a new, all-purpose peergroup ! ModuleImplAdvertisement implAdv = ! netPeerGroup.getAllPurposePeerGroupImplAdvertisement(); ! ! wettPeerGroup = netPeerGroup.newGroup(mkGroupID(), ! implAdv, ! WETT_GROUP_NAME, ! WETT_GROUP_DESCRIPTION); ! ! // Get the peer group advertisement ! wettGroupAdv = netPeerGroup.getPeerGroupAdvertisement(); ! } ! catch (Exception e) { ! String str = "Error in creating WETT peergroup."; ! logger.severe(str); ! System.err.println(str); ! throw e; ! } } else { ! // we found the advertisement in the cache; ! // We can join the existing wettPeerGroup. ! ! try { ! wettGroupAdv = (PeerGroupAdvertisement) ae.nextElement(); ! wettPeerGroup = netPeerGroup.newGroup(wettGroupAdv); ! logger.info("Found the WETT Peer Group advertisement; " + ! "joined the existing group."); ! } ! catch (Exception e) { ! String str = "Error in creating Wett peergroup " + ! "from existing advertisement."; ! logger.severe(str); ! System.err.println(str); ! throw e; ! } ! } // end if (wett group adv found) ! ! try { ! // get the diescvoer and pipe services for the Wett peergroup ! wettDiscoveryService = wettPeerGroup.getDiscoveryService(); ! wettPipeService = wettPeerGroup.getPipeService(); ! } ! catch (Exception e) { ! String str = "Error getting services from Wett peergroup"; ! logger.severe(str); ! System.err.println(str); ! throw e; } ! ! logger.info("Web Enabled Table Top - Peer-to-Peer is on-line!"); ! } // end joinWettGroup() ! ! /** ! * Creates and joins the WettPeerGroup. ! */ ! private void createWettGroup() { ! logger.entering(classStr,"createWettGroup"); ! PeerGroupAdvertisement adv = null; ! logger.info("Attempting to create the WETT peergroup"); ! try { ! // Creates an all purpose peergroup advertisement ! ModuleImplAdvertisement implAdv = netPeerGroup.getAllPurposePeerGroupImplAdvertisement(); ! ! // Create the WETT peergroup as a child to netPeer ! wettPeerGroup = netPeerGroup.newGroup((PeerGroupID) IDFactory.fromURL(new URL(WETT_GID)), implAdv, "WETT", "Web-Enabled Table Top"); ! ! // Retrieve the advertisement for the wett peergroup ! adv = wettPeerGroup.getPeerGroupAdvertisement(); ! ! logger.info("WETT peergroup successfully created"); ! } ! catch (Exception e) { ! String str = "Failed to create the WETT group: " + e; ! logger.severe(str); ! System.err.println(str); ! e.printStackTrace(); ! System.exit(1); ! } ! try { ! // Publish the advertisement using the discovery service of netPeer ! DiscoveryService disco = netPeerGroup.getDiscoveryService(); ! disco.remotePublish(adv, DiscoveryService.GROUP); ! logger.info("WETT peergroup successfully published"); } ! catch (Exception ee) { ! String str = "Failed to publish the WETT group: " + ee; logger.severe(str); System.err.println(str); ! ee.printStackTrace(); ! System.exit(1); } } ! private PeerGroupID mkGroupID() throws Exception { return (PeerGroupID) IDFactory.fromURL( new URL("urn", "", WETT_GID)); --- 337,399 ---- } // end while if (ae == null || !ae.hasMoreElements()) { ! // The group wasn't found ! logger.fine("Group " + groupName + " not found."); ! peerGroup = null; } else { ! PeerGroupAdvertisement peerGroupAdv = (PeerGroupAdvertisement) ae.nextElement(); ! peerGroup = parentGroup.newGroup(peerGroupAdv); ! logger.fine("Group " + groupName + " created."); } ! return peerGroup; ! } ! private PeerGroup createPeerGroup(PeerGroup parentGroup, ! String groupName, ! String groupDescription, ! PeerGroupID groupID) ! throws Exception ! { ! logger.entering(classStr, "createPeerGroup"); ! PeerGroupAdvertisement peerGroupAdv = null; ! PeerGroup peerGroup = null; ! logger.info("Creating the " + groupName + " Peer Group."); ! if (groupID == null) { ! // create a group id ! groupID = IDFactory.newPeerGroupID(); // create new random peer group ID ! logger.finer("Generated GroupID " + groupID.toString() + ! " created for Group " + groupName + "."); ! } ! try { ! ! // create a new, all-purpose peergroup ! ModuleImplAdvertisement implAdv = ! parentGroup.getAllPurposePeerGroupImplAdvertisement(); ! ! peerGroup = parentGroup.newGroup(groupID, ! implAdv, ! groupName, ! groupDescription); ! ! // Get the peer group advertisement ! peerGroupAdv = parentGroup.getPeerGroupAdvertisement(); } ! catch (Exception e) { ! String str = "Error in creating peergroup."; logger.severe(str); System.err.println(str); ! throw e; } + logger.info("Peer Group, " + groupName + ", created."); + return peerGroup; } ! private PeerGroupID mkWettGroupID() throws Exception { return (PeerGroupID) IDFactory.fromURL( new URL("urn", "", WETT_GID)); |
From: <rb...@us...> - 2002-12-15 00:27:55
|
Update of /cvsroot/wett-p2p/org/wettp2p/communicationslayer In directory sc8-pr-cvs1:/tmp/cvs-serv29120 Added Files: CommunicationsHandlerDesign.html Log Message: Start of initial draft of a continuing design for the CommunicationHandler class and classes that will work with it. It will document the control messages that are used by the application to control the CommunicationsLayer. --- NEW FILE: CommunicationsHandlerDesign.html --- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <HTML> <HEAD> <TITLE>CommunicationsHandler Design</TITLE> </HEAD> <BODY> <h1>CommunicationsHandler Design</H1> <h2>Introduction</h2> <p>The CommunicationsHandler (CH) provides an interface between the JXTA communications layer and the MessageHandler which handles messaging for the rest of the application. The CH sets up and controls the peer groups, pipes and other JXTA structures and presents a simplified view of the network to the rest of the application. The rest of the appication just sees a module that accepts and produces messages just like any other part of the application. The CH itself is controled via messages sent to it through the MessageHandler.</p> <h2>CommunicationsHandler Controls</h2> <p>The CH only has a very few public methods: a getInstance() method, an initialize() method, and a few others. Almost all interaction with the CH is done via messages that are sent via the MessageHandler.</p> <h3>Control Messages</h3> <ul> <li>Start Communications Processes</li> <li>Stop Communications Processes</li> <li>Change Peer Group</li> <li>Leave Peer Group</li> <li>Retransmit Message or Message Block</li> </ul> </BODY> </HTML> |
From: <zy...@us...> - 2002-12-13 20:39:51
|
Update of /cvsroot/wett-p2p/org/wettp2p/combatmanager/combatagent In directory sc8-pr-cvs1:/tmp/cvs-serv7118 Modified Files: CombatAgentMain.java MeleeAgent.java Log Message: Fixed an infinite loop problem, CombatAgentMain should now run. Currently, it takes 10 orcs and a monk and has them all fight each other. (Just exchange melee blows, it doesn't do anything interesting yet.) Index: CombatAgentMain.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/combatmanager/combatagent/CombatAgentMain.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** CombatAgentMain.java 13 Dec 2002 20:01:49 -0000 1.4 --- CombatAgentMain.java 13 Dec 2002 20:39:44 -0000 1.5 *************** *** 78,82 **** drycon.addWeapon(fists); ! ch.getInitiative().addParticipant(drycon); List orcArmy = new ArrayList(); --- 78,82 ---- drycon.addWeapon(fists); ! ch.getInitiativeObj().addParticipant(drycon); List orcArmy = new ArrayList(); *************** *** 85,89 **** newOrc = makeOrc("Orc " + i); orcArmy.add(newOrc); ! ch.getInitiative().addParticipant(newOrc); } ch.fireStartCombat(); --- 85,89 ---- newOrc = makeOrc("Orc " + i); orcArmy.add(newOrc); ! ch.getInitiativeObj().addParticipant(newOrc); } ch.fireStartCombat(); Index: MeleeAgent.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/combatmanager/combatagent/MeleeAgent.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** MeleeAgent.java 13 Dec 2002 20:01:49 -0000 1.1 --- MeleeAgent.java 13 Dec 2002 20:39:44 -0000 1.2 *************** *** 39,42 **** --- 39,44 ---- myMoral -= myBody.getIntMod(); myMoral += myBody.getChaMod(); + + //if(myBody.g ch.registerListener(this); //System.out.println(myName + "'s moral starts at: " + myMoral); *************** *** 76,80 **** public void makeDecision(){ ! List participants = myCH.getInitiative().getParticipantList(); int status = myBody.getHPStatus(); switch (status){ --- 78,82 ---- public void makeDecision(){ ! List participants = myCH.getInitiativeObj().getParticipantList(); int status = myBody.getHPStatus(); switch (status){ |
From: <zy...@us...> - 2002-12-13 20:39:34
|
Update of /cvsroot/wett-p2p/org/wettp2p/combatmanager In directory sc8-pr-cvs1:/tmp/cvs-serv7044 Modified Files: CombatHandler.java Log Message: Fixed an infinite loop problem, CombatAgentMain should now run. Currently, it takes 10 orcs and a monk and has them all fight each other. (Just exchange melee blows, it doesn't do anything interesting yet.) Index: CombatHandler.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/combatmanager/CombatHandler.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** CombatHandler.java 13 Dec 2002 20:00:50 -0000 1.1 --- CombatHandler.java 13 Dec 2002 20:39:29 -0000 1.2 *************** *** 31,40 **** private Iterator callBackItr; private Initiative init; - private List curRoundResults; private Random rnd; private Creature curCritter; /** Creates a new instance of CombatHandler */ public CombatHandler() { registeredObjects = new ArrayList(); curRoundResults = new ArrayList(); --- 31,43 ---- private Iterator callBackItr; private Initiative init; private Random rnd; private Creature curCritter; + private boolean inCombat; + + private List curRoundResults; /** Creates a new instance of CombatHandler */ public CombatHandler() { + inCombat = false; registeredObjects = new ArrayList(); curRoundResults = new ArrayList(); *************** *** 62,65 **** --- 65,70 ---- // ******************************************** public void fireAttackOccured(MeleeAttackEvent e){ + if(!inCombat) return; + if(! e.getInitiator().equals(curCritter)){ e.setWhatHappened(e.getInitiator().getName() + " attempted to attack out of turn."); *************** *** 88,95 **** --- 93,103 ---- public void fireMoralFailure(FlockingEvent e){ + if(!inCombat) return; + callbacks(e, MORAL_FAILURE); } public void fireStartCombat(){ + inCombat = true; callbacks(null, START_COMBAT); fireNewRound(); *************** *** 97,100 **** --- 105,110 ---- public void fireNewRound(){ + if(!inCombat) return; + init.newRound(); callbacks(null, NEW_ROUND); *************** *** 104,107 **** --- 114,119 ---- public void fireParticipantDone(){ + if(!inCombat) return; + if(init.hasMoreParticipants()){ Participant p = init.getNextParticipant(); *************** *** 135,138 **** --- 147,153 ---- public void fireEndCombat(){ + if(!inCombat) return; + + inCombat = false; callbacks(null, END_COMBAT); |
Update of /cvsroot/wett-p2p/org/wettp2p/creature In directory sc8-pr-cvs1:/tmp/cvs-serv26005 Modified Files: .nbattrs Creature.java HitPoints.java Added Files: AbilityScoresTest.java CreatureBase.java CreatureBaseTest.java CreatureList.java SavesTest.java Log Message: Modifications to creature, this shouldn't break anything --- NEW FILE: AbilityScoresTest.java --- /* Copyright (C) 2002 Heather Cousineau This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * AbilityScoresTest.java * NetBeans JUnit based test * * Created on December 9, 2002, 6:37 PM */ package org.wettp2p.creature; import junit.framework.*; import org.netbeans.junit.*; /** Test. * @author Zyrca */ public class AbilityScoresTest extends NbTestCase { /** Test. * @param testName Test. */ public AbilityScoresTest(java.lang.String testName) { super(testName); } /** Test. * @param args Test. */ public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } /** Test of setAll method, of class org.wettp2p.creature.AbilityScores. */ public void testSetAll() { System.out.println("testSetAll"); AbilityScores as = new AbilityScores(); as.setAll(15, 10, 11,9, 8, 8); if(as.getStr().getCurrent() != 15) fail("Str should be 15, it is: " + as.getStr().getCurrent()); if(as.getDex().getCurrent() != 10) fail("Dex should be 10, it is: " + as.getDex().getCurrent()); if(as.getCon().getCurrent() != 11) fail("Con should be 11, it is: " + as.getCon().getCurrent()); if(as.getInt().getCurrent() != 9) fail("Int should be 9, it is: " + as.getInt().getCurrent()); if(as.getWis().getCurrent() != 8) fail("Wis should be 8, it is: " + as.getWis().getCurrent()); if(as.getCha().getCurrent() != 8) fail("Cha should be 8, it is: " + as.getCha().getCurrent()); } public static Test suite() { TestSuite suite = new NbTestSuite(AbilityScoresTest.class); return suite; } } --- NEW FILE: CreatureBase.java --- /* Copyright (C) 2002 Heather Cousineau This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * Creature.java * * Created on October 20, 2002, 12:07 PM */ package org.wettp2p.creature; import org.wettp2p.intelligentagents.*; import java.util.List; import java.util.LinkedList; /** A Creature, such as a Human, Elf or Dragon. * * @author Zyrca */ public class CreatureBase { protected Agent myCombatAgent; // Creature tree nodes /** The creature "above" the this creature, in social structure, command, or just * the creature that this creature tends to follow. */ protected CreatureBase myLeader; /** The list of creatures that follows this creature. */ protected List myFollowers; // Description /** Creature's name. */ protected String myName; /** The name of the player that controls this creature. */ protected String myPlayerName; /** The creature's alignment. */ protected Alignment myAlig; /** Creature's class. */ protected String myCreatureClass; /** Creature's race. */ protected String myRace; /** Other information, such as a biography, that doesn't fit anywhere else. */ protected String myOtherInfo; /** Creature's size. */ protected CreatureSize mySize; // Stats /** Creature's Hit Points. */ protected HitPoints myHitPoints; /** Creature's Ability Scores. */ protected AbilityScores myAbilityScores; /** Creature's Level, or Hit Dice. */ protected Stat myLevel; /** Creature's xp. */ protected Stat myXP; /** Creature's saving throws. */ protected Saves mySaves; /** Creature's armor class. */ protected ArmorClass myAC; /** Creature's speed. */ protected int mySpeed; // In feet // Combat /** Creature's initiative. */ protected DieRollAdj myInitiative; /** Creature's melee modification. */ protected DieRollAdj myMeleeMod; /** Creatures ranged modification. */ protected DieRollAdj myRangedMod; /** All of the weapons that this creature has on it. */ protected List myWeapons; /** Creates a new instance of Creature */ protected CreatureBase() { myAlig = new Alignment(); myAbilityScores = new AbilityScores(); myLevel = new Stat("Level", "LVL"); myXP = new Stat("Experience Points", "XP"); mySaves = new Saves(myAbilityScores); mySize = new CreatureSize(); myAC = new ArmorClass(); mySpeed = 30; myInitiative = new DieRollAdj("Initiative", "INIT", myAbilityScores.getDex()); myMeleeMod = new DieRollAdj("Melee Attack Mod", "Melee", myAbilityScores.getStr()); myRangedMod = new DieRollAdj("Ranged Attack Mod", "Ranged", myAbilityScores.getDex()); myHitPoints = new HitPoints(myLevel, myAbilityScores.getCon()); myWeapons = new LinkedList(); myCombatAgent = null; } /** Sets the name of the player in control of the creature * @param PlayerName Name of the player. */ //protected final void setPlayerName(String PlayerName){ myPlayerName = PlayerName; } /** Sets the name of the creature * @param Name Name of Creature. */ //protected final void setName( String Name ) { myName = Name; } /** Sets the class of the creature * @param CreatureClass Creature Class. */ //protected final void setCreatureClass( String CreatureClass ) { myCreatureClass = CreatureClass; } /** Sets the race of the creature * @param Race Creature race, such as "Elf" or "Owl Bear". */ //protected final void setRace( String Race ) { myRace = Race; } /** Sets the string of other details about the creature * @param OtherInfo Other information about the creature that doesn't fit anywhere else. */ //protected final void setOtherInfo( String OtherInfo ) { myOtherInfo = OtherInfo; } /** Sets the creature's size. * Use the constants in Creature Size for the size value. * @param critterSize CreatureSize constant. */ //protected final void setCreatureSize( int critterSize ) { mySize.setSize( critterSize ); } /** Sets the creature's size object * @param critterSize CreatureSize object. */ //protected final void setCreatureSize( CreatureSize critterSize ) { mySize = critterSize; } /** Set the creature's speed in feet. (Per round) * @param speed Speed, in feet. */ //protected final void setSpeed( int speed ) { mySpeed = speed; } /** Player in control. * @return Returns the name of the player in control of the creature */ //protected final String getPlayerName(){ return myPlayerName; } /** <CODE>AbilityScores</CODE>. * @return Returns a <CODE>AbilityScores</CODE> object with the creature's ability scores */ protected final AbilityScores getAbilityScores() { return myAbilityScores; } /** Name of Creature. * @return Returns the name of the creature. */ //protected final String getName() { return myName; } /** Creature's Class, such as "Sorcerer" or "Beast". * @return Returns the class of the creature. */ //protected final String getCreatureClass() { return myCreatureClass; } /** Race of a creature, such as "Elf" or "Dragon". * @return Returns the race of the creature. */ //protected final String getRace() { return myRace; } /** Misc details. * @return Returns the string of other details about the creature. */ //protected final String getOtherInfo() { return myOtherInfo; } /** Creature's level. * @return Returns the creature's level. */ protected final Stat getLevel() { return myLevel; } /** Creature's Armor Class. * @return Returns the creature's Armor Class. */ protected final ArmorClass getAC() { return myAC; } /** Get the speed that the creature can move in a round. (In Feet) * @return The creature's speed in feet. */ //protected final int getSpeed() { return mySpeed; } /** Experience Points. * @return Returns the creature's Experience Points. */ protected final Stat getXP() { return myXP; } /** Creature Size. * @return Returns the creature's Size Object */ protected final CreatureSize getSize() { return mySize; } /** Initiative Modifier. * @return The initiative modifier Stat for the creature. */ protected final DieRollAdj getInitiative() { return myInitiative; } /** Hit Points. * @return The HitPoints object for this creature. */ protected final HitPoints getHitPoints() { return myHitPoints; } /** Get the creature's saves object. * @return Saves object. */ protected final Saves getSaves() { return mySaves; } protected final Agent getMyCombatAgent() { return myCombatAgent; } protected final void setMyCombatAgent(Agent combatAgent){ myCombatAgent = combatAgent; } } --- NEW FILE: CreatureBaseTest.java --- /* Copyright (C) 2002 Heather Cousineau This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * CreatureTest.java * NetBeans JUnit based test * * Created on October 20, 2002, 12:14 PM */ package org.wettp2p.creature; import java.util.List; import java.util.LinkedList; import junit.framework.*; import org.netbeans.junit.*; /** Test <CODE>Creature</CODE> class. * @author Zyrca */ public class CreatureBaseTest extends NbTestCase { /** Test <CODE>Creature</CODE> class. * @param testName The name of the test. */ public CreatureBaseTest(java.lang.String testName) { super(testName); } /** Test <CODE>Creature</CODE> class. * @param args No args required. */ public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } /** Test of PlayerName method, of class org.wettp2p.creature.Creature. */ public void testPlayerName() { System.out.println("org.wettp2p.creature.Creature.testPlayerName"); Creature critter = new Creature(); critter.setPlayerName("Heather"); // Make sure the player name works correctly if(((String)critter.getPlayerName()).compareTo("Heather") != 0) fail("Player name was not saved correctly"); } /** Test of DescriptionObject, of class org.wettp2p.creature.Creature. */ public void testDescriptionObject() { System.out.println("org.wettp2p.creature.Creature.testDescriptionObject"); Creature critter = new Creature(); // Make sure the description object is referenced correctly critter.setName("Zyrca"); if(critter.getName().compareTo("Zyrca") != 0) fail("The description object's name value is not saved correctly."); } /** Test of AbilityScoresObject, of class org.wettp2p.creature.Creature. */ public void testAbilityScoresObject() { System.out.println("org.wettp2p.creature.Creature.testAbilityScoresObject"); Creature critter = new Creature(); // Make sure the AbilitieScores object is referenced correctly critter.getAbilityScores().getStr().setBaseStat(10); if(critter.getAbilityScores().getStr().getBaseStat() != 10) fail("The AbilityScores object's name value is not saved correctly."); } /** Test of getName method, of class org.wettp2p.creature.Description. */ public void testDescription() { System.out.println("org.wettp2p.creature.Creature.testDescription"); Creature critter = new Creature(); critter.setName("Zyrca"); critter.setCreatureClass("Bard"); critter.setRace("Elf"); critter.setOtherInfo("Singing forest humanoid"); if((critter.getName()).compareTo("Zyrca") != 0) fail("Creature name was changed"); if((critter.getCreatureClass()).compareTo("Bard") != 0) fail("Creature class was changed"); if((critter.getRace()).compareTo("Elf") != 0) fail("Creature race was changed"); if((critter.getOtherInfo()).compareTo("Singing forest humanoid") != 0) fail("Creature information was changed"); } /** Test the weapon interaction with CreatureBase */ public void testWeapon(){ System.out.println("org.wettp2p.creature.Creature.testWeapon"); Creature critter = new Creature(); Weapon greatAxe = new Weapon(); StatAdjuster sa = new HitPointAdjuster(); greatAxe.setDamage(sa); greatAxe.setDescription("Great Axe"); greatAxe.setDamageDice("1d12+3"); int greatAxeIDX = critter.addWeapon(greatAxe); if(critter.getWeapon(greatAxeIDX).getDescription().compareTo("Great Axe") != 0) fail("Weapon was not added or retreived properly"); } public static Test suite() { TestSuite suite = new NbTestSuite(CreatureBaseTest.class); return suite; } } --- NEW FILE: CreatureList.java --- /* * CreatureList.java * * Created on December 12, 2002, 10:52 AM */ package org.wettp2p.creature; import java.util.ArrayList; /** CreatureList is simply a convience class so you don't have to cast the creature * objects every time you access them. * @author Zyrca */ public class CreatureList extends ArrayList{ /** Creates a new instance of CreatureList */ public CreatureList() { super(); } /** Get the creature as index idx. * @param idx The index of the Creature. * @return The Creature object at the index idx. */ public Creature getCreature(int idx) { return (Creature)super.get(idx); } /** Set the Creature object at an existing index idx. * @param idx The index of the Creature you are setting. * @param critter The Creature object that you are setting. * @return The resulting Creature Object. */ public Creature setCreature(int idx, Creature critter) { return (Creature)super.set(idx, critter); } } --- NEW FILE: SavesTest.java --- /* Copyright (C) 2002 Heather Cousineau This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * SavesTest.java * NetBeans JUnit based test * * Created on December 9, 2002, 6:20 PM */ package org.wettp2p.creature; import junit.framework.*; import org.netbeans.junit.*; /** Test. * @author Zyrca */ public class SavesTest extends NbTestCase { /** Test. * @param testName Test. */ public SavesTest(java.lang.String testName) { super(testName); } /** Test. * @param args Test. */ public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } /** Test of getFort method, of class org.wettp2p.creature.Saves. */ public void testGetFort() { System.out.println("org.wettp2p.creature.Saves.testGetFort"); Saves s = new Saves(); AbilityScore con = new AbilityScore(); con.setBaseStat(15); s.getFort().setDependentScore(con); if(s.getFort().getCurrent() != 2) fail("Current Fortitude Save should be 2, is: " + s.getFort().getCurrent()); } /** Test of getWill method, of class org.wettp2p.creature.Saves. */ public void testGetWill() { System.out.println("org.wettp2p.creature.Saves.testGetWill"); Saves s = new Saves(); AbilityScore wis = new AbilityScore(); wis.setBaseStat(8); s.getWill().setDependentScore(wis); if(s.getWill().getCurrent() != -1) fail("Current Will Save should be -1, is: " + s.getWill().getCurrent()); } /** Test of getRef method, of class org.wettp2p.creature.Saves. */ public void testGetRef() { System.out.println("org.wettp2p.creature.Saves.testGetRef"); Saves s = new Saves(); AbilityScore dex = new AbilityScore(); dex.setBaseStat(10); s.getRef().setDependentScore(dex); if(s.getRef().getCurrent() != 0) fail("Current Reflex Save should be 0, is: " + s.getRef().getCurrent()); } /** Test of constructor method, of class org.wettp2p.creature.Saves. */ public void testInit() { System.out.println("org.wettp2p.creature.Saves.testInit"); AbilityScores as = new AbilityScores(); Saves s = new Saves(as); as.setAll(15, 10, 11, 9, 8, 8); if(s.getFort().getCurrent() != 0) fail("Current Fortitude Save should be 0, is: " + s.getFort().getCurrent()); if(s.getWill().getCurrent() != -1) fail("Current Will Save should be -1, is: " + s.getWill().getCurrent()); if(s.getRef().getCurrent() != 0) fail("Current Reflex Save should be -1, is: " + s.getRef().getCurrent()); } public static Test suite() { TestSuite suite = new NbTestSuite(SavesTest.class); return suite; } } Index: .nbattrs =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/creature/.nbattrs,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** .nbattrs 11 Dec 2002 20:05:54 -0000 1.13 --- .nbattrs 13 Dec 2002 20:03:50 -0000 1.14 *************** *** 14,17 **** --- 14,20 ---- <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="AbilityScoresTest"/> </fileobject> + <fileobject name="HitPoints.java"> + <attr name="class_dependency_org.wettp2p.creature.Stat" stringvalue="HitPoints"/> + </fileobject> <fileobject name="AbilityScoreTest.java"> <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="AbilityScoreTest"/> *************** *** 21,25 **** </fileobject> <fileobject name="Stat.java"> ! <attr name="EA-OpenIDE-Connection" serialvalue="aced0005737200146a6176612e7574696c2e4c696e6b65644c6973740c29535d4a60882203000078707704000000047372002a6f72672e6f70656e6964652e6c6f61646572732e436f6e6e656374696f6e537570706f72742450616972055f8af6f04a3bd80200024c00047479706574002b4c6f72672f6f70656e6964652f636f6f6b6965732f436f6e6e656374696f6e436f6f6b696524547970653b4c000576616c75657400124c6a6176612f6c616e672f4f626a6563743b78707372002e6f72672e6e65746265616e732e6d6f64756c65732e6a6176612e4a617661436f6e6e656374696f6e732454797065a83dd01001306d7402000149000666696c746572787000000050737200436f72672e6e65746265616e732e6d6f64756c65732e6a6176612e4a617661446174614f626a6563742450657273697374656e74436f6e6e656374696f6e48616e646c65ba16f1d2dd4c1cb60200014c000e646174614e6f646548616e646c6574001f4c6f72672f6f70656e6964652f6e6f6465732f4e6f64652448616e646c653b7870737200296f72672e6f70656e6964652e6c6f61646572732e446174614e6f6465244f626a65637448616e646c655bd0f82e01811d2e0200025a0005636c6f6e654c00036f626a7400244c6f72672f6f70656e6964652f66696c6573797374656d732f46696c654f626a6563743b787000737200326f72672e6f70656e6964652e66696c6573797374656d732e416273747261637446696c654f626a656374245265706c616365896fa1bce4b5219f0200024c000866696c654e616d657400124c6a6176612f6c616e672f537472696e673b4c000666734e616d6571007e000f78707400266f72672f776574747032702f63726561747572652f4162696c69747953636f72652e6a61766174004c433a2f446f63756d656e747320616e642053657474696e67732f486561746865722f4d7920446f63756d656e74732f50726f6772616d732f736f75726365666f7267652f776574742d7032707371007e00027371007e0006000000507371007e00087371007e000b007371007e000e7400246f72672f776574747032702f63726561747572652f446965526f6c6c41646a2e6a61766171007e00127371007e00027371007e0006000000507371007e00087371007e000b007371007e000e7400236f72672f776574747032702f63726561747572652f486974506f696e74732e6a61766171007e00127371007e00027371007e0006000000507371007e00087371007e000b007371007e000e7400246f72672f776574747032702f63726561747572652f41726d6f72436c6173732e6a61766171007e001278"/> </fileobject> <fileobject name="HitPointsTest.java"> --- 24,28 ---- </fileobject> <fileobject name="Stat.java"> ! <attr name="EA-OpenIDE-Connection" serialvalue="aced0005737200146a6176612e7574696c2e4c696e6b65644c6973740c29535d4a60882203000078707704000000047372002a6f72672e6f70656e6964652e6c6f61646572732e436f6e6e656374696f6e537570706f72742450616972055f8af6f04a3bd80200024c00047479706574002b4c6f72672f6f70656e6964652f636f6f6b6965732f436f6e6e656374696f6e436f6f6b696524547970653b4c000576616c75657400124c6a6176612f6c616e672f4f626a6563743b78707372002e6f72672e6e65746265616e732e6d6f64756c65732e6a6176612e4a617661436f6e6e656374696f6e732454797065a83dd01001306d7402000149000666696c746572787000000050737200436f72672e6e65746265616e732e6d6f64756c65732e6a6176612e4a617661446174614f626a6563742450657273697374656e74436f6e6e656374696f6e48616e646c65ba16f1d2dd4c1cb60200014c000e646174614e6f646548616e646c6574001f4c6f72672f6f70656e6964652f6e6f6465732f4e6f64652448616e646c653b7870737200296f72672e6f70656e6964652e6c6f61646572732e446174614e6f6465244f626a65637448616e646c655bd0f82e01811d2e0200025a0005636c6f6e654c00036f626a7400244c6f72672f6f70656e6964652f66696c6573797374656d732f46696c654f626a6563743b787000737200326f72672e6f70656e6964652e66696c6573797374656d732e416273747261637446696c654f626a656374245265706c616365896fa1bce4b5219f0200024c000866696c654e616d657400124c6a6176612f6c616e672f537472696e673b4c000666734e616d6571007e000f78707400266f72672f776574747032702f63726561747572652f4162696c69747953636f72652e6a61766174004c433a2f446f63756d656e747320616e642053657474696e67732f486561746865722f4d7920446f63756d656e74732f50726f6772616d732f736f75726365666f7267652f776574742d7032707371007e00027371007e0006000000507371007e00087371007e000b007371007e000e7400246f72672f776574747032702f63726561747572652f446965526f6c6c41646a2e6a61766171007e00127371007e00027371007e0006000000507371007e00087371007e000b007371007e000e7400246f72672f776574747032702f63726561747572652f41726d6f72436c6173732e6a61766171007e00127371007e00027371007e0006000000507371007e00087371007e000b007371007e000e7400236f72672f776574747032702f63726561747572652f486974506f696e74732e6a61766171007e001278"/> </fileobject> <fileobject name="HitPointsTest.java"> *************** *** 32,35 **** --- 35,41 ---- <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="StatTest"/> </fileobject> + <fileobject name="CreatureList.java"> + <attr name="class_dependency_java.util.ArrayList" stringvalue="CreatureList"/> + </fileobject> <fileobject name="HitPointAdjusterTest.java"> <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="HitPointAdjusterTest"/> *************** *** 47,61 **** <attr name="EA-OpenIDE-Connection" serialvalue="aced0005737200146a6176612e7574696c2e4c696e6b65644c6973740c29535d4a608822030000787077040000000078"/> </fileobject> - <fileobject name="SavesTestTest.java"> - <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="SimpleNbJUnitTest"/> - </fileobject> <fileobject name="CreatureSizeTest.java"> <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="CreatureSizeTest"/> </fileobject> ! <fileobject name="SavesTest.java"> ! <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="SavesTest"/> </fileobject> <fileobject name="Creature.java"> <attr name="class_dependency_org.wettp2p.creature.CreatureBase" stringvalue="Creature"/> </fileobject> <fileobject name="AlignmentTest.java"> --- 53,67 ---- <attr name="EA-OpenIDE-Connection" serialvalue="aced0005737200146a6176612e7574696c2e4c696e6b65644c6973740c29535d4a608822030000787077040000000078"/> </fileobject> <fileobject name="CreatureSizeTest.java"> <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="CreatureSizeTest"/> </fileobject> ! <fileobject name="SavesTestTest.java"> ! <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="SimpleNbJUnitTest"/> </fileobject> <fileobject name="Creature.java"> <attr name="class_dependency_org.wettp2p.creature.CreatureBase" stringvalue="Creature"/> + </fileobject> + <fileobject name="SavesTest.java"> + <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="SavesTest"/> </fileobject> <fileobject name="AlignmentTest.java"> Index: Creature.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/creature/Creature.java,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** Creature.java 11 Dec 2002 20:05:55 -0000 1.11 --- Creature.java 13 Dec 2002 20:03:51 -0000 1.12 *************** *** 25,28 **** --- 25,29 ---- package org.wettp2p.creature; import java.util.List; + import org.wettp2p.intelligentagents.*; /** Container class for all creature information, such as stats, ability scores, *************** *** 69,72 **** --- 70,77 ---- } + public int getStrMod(){ + return super.getAbilityScores().getStr().getModifier(); + } + /** Set the dexterity base. * @param dex Current adjusted dexterity *************** *** 82,85 **** --- 87,94 ---- } + public int getDexMod(){ + return super.getAbilityScores().getDex().getModifier(); + } + /** Set the constitution base. * @param Con Current adjusted constituion *************** *** 95,98 **** --- 104,111 ---- } + public int getConMod(){ + return super.getAbilityScores().getCon().getModifier(); + } + /** Set the inteligence base. * @param intl Current adjusted inteligence *************** *** 108,111 **** --- 121,128 ---- } + public int getIntMod(){ + return super.getAbilityScores().getInt().getModifier(); + } + /** Set the wisdom base. * @param wis Current adjusted wisdom *************** *** 119,122 **** --- 136,143 ---- public int getWis(){ return super.getAbilityScores().getWis().getCurrent(); + } + + public int getWisMod(){ + return super.getAbilityScores().getWis().getModifier(); } *************** *** 134,137 **** --- 155,162 ---- } + public int getChaMod(){ + return super.getAbilityScores().getCha().getModifier(); + } + /** Set the name of the creature. * @param cName The creature's name. *************** *** 315,318 **** --- 340,354 ---- } + public boolean isStable(){ + return super.getHitPoints().isStable(); + } + + public void setIsStable(boolean stable){ + super.getHitPoints().setIsStable(stable); + } + + public void adjHP(int adj){ + super.getHitPoints().adjAdj(adj); + } /** If a particular weapon has been marked as the favored one, then return that * weapon. If none have been marked, looks for the first melee weapon starting at *************** *** 326,330 **** } else { List weapons = getWeapons(); ! for(int i = weapons.size(); i >= 0; i--){ if(((Weapon)weapons.get(i)).IsMelee()) return (Weapon)weapons.get(i); --- 362,366 ---- } else { List weapons = getWeapons(); ! for(int i = (weapons.size()-1); i >= 0; i--){ if(((Weapon)weapons.get(i)).IsMelee()) return (Weapon)weapons.get(i); *************** *** 486,488 **** --- 522,532 ---- } + + public Agent getCombatAgent(){ return super.myCombatAgent; } + public void setCombatAgent(Agent combatAgent){ + super.myCombatAgent = combatAgent; + } + + public int getMeleeMod() { return super.myMeleeMod.getCurrent(); } + public int getRangedMod(){ return super.myRangedMod.getCurrent(); } } Index: HitPoints.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/creature/HitPoints.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** HitPoints.java 9 Dec 2002 20:13:33 -0000 1.6 --- HitPoints.java 13 Dec 2002 20:03:51 -0000 1.7 *************** *** 37,40 **** --- 37,41 ---- private AbilityScore myCon; private Stat myLevel; + private boolean isStable; /** Tha character is alive and kicking. */ *************** *** 91,95 **** myStatName = "Hit Points"; myStatAbbrev = "HP"; ! myCon = Constitution; } --- 92,110 ---- myStatName = "Hit Points"; myStatAbbrev = "HP"; ! myCon = Constitution; ! // This only matters if the character is dying. So we set it ! // to false by default. ! isStable = false; ! } ! ! public boolean isStable(){ ! if(this.health() == DYING) ! return isStable; ! else ! return true; ! } ! ! public void setIsStable(boolean stable){ ! isStable = stable; } |
From: <zy...@us...> - 2002-12-13 20:02:17
|
Update of /cvsroot/wett-p2p/org/wettp2p/combatmanager/combatagent In directory sc8-pr-cvs1:/tmp/cvs-serv25111 Modified Files: CombatAgentMain.java Added Files: Agent.java MeleeAgent.java Log Message: Wrote some of the melee agent and the Agent interface --- NEW FILE: Agent.java --- /* * Agent.java * * Created on December 11, 2002, 6:47 PM */ package org.wettp2p.intelligentagents; /** * * @author Zyrca */ public interface Agent { } --- NEW FILE: MeleeAgent.java --- /* * MeleeAgent.java * * Created on December 11, 2002, 6:55 PM */ package org.wettp2p.intelligentagents; import java.util.Random; import java.util.List; import java.util.ArrayList; import org.wettp2p.creature.*; import org.wettp2p.combatmanager.*; /** * * @author Zyrca */ public class MeleeAgent implements Agent, CombatListener { private Random rnd = null; private int myMoral; private String myName; private CombatHandler myCH; private Creature myBody; private Creature myFoe; /** Creates a new instance of MeleeAgent */ public MeleeAgent(Creature body, Random random, CombatHandler ch) { myCH = ch; myFoe = null; myBody = body; rnd = random; myName = myBody.getCreatureName(); myMoral = 0; myMoral += myBody.getStrMod(); myMoral += myBody.getDexMod(); myMoral += myBody.getConMod(); myMoral -= myBody.getWisMod(); myMoral -= myBody.getIntMod(); myMoral += myBody.getChaMod(); ch.registerListener(this); //System.out.println(myName + "'s moral starts at: " + myMoral); } public void hitTaken(int hp){ myMoral--; //System.out.println(myName + " was hit for " + hp + " hit points. " + // "New moral: " + myMoral); } public void hitDealt(int hp){ myMoral++; //System.out.println(myName + " dealt a hit of " + hp + " hit points. " + // "New moral: " + myMoral); } public void attackMissed(){ myMoral--; //System.out.println(myName + " missed. New moral: " + myMoral); } public void sucessfulEvade(){ myMoral++; //System.out.println(myName + " evaded. New moral: " + myMoral); } public boolean moralCheck(){ int moral = rollDie(20) + myMoral; return (moral > 3); } public int getMoral(){ return myMoral; } public void makeDecision(){ List participants = myCH.getInitiative().getParticipantList(); int status = myBody.getHPStatus(); switch (status){ case HitPoints.NORMAL: if(moralCheck()){ // The creature choose not to run //System.out.println(myName + " chooses to attack."); if((myFoe == null) || (myFoe.getHPStatus() == HitPoints.DEAD)){ // Choose a foe myFoe = pickRandFoe(participants); // If there are no other foe's return false if(myFoe == null) return; } // Attack current foe MeleeAttackEvent mae = new MeleeAttackEvent(this, myBody, myFoe, myBody.getFavoredMeleeWeapon()); myCH.fireAttackOccured(mae); return; }else{ // Attack current foe FlockingEvent ce = new FlockingEvent(this, myBody); myCH.fireMoralFailure(ce); return; } case HitPoints.UNCONSCIOUS: case HitPoints.STAGGERED: case HitPoints.DISABLED: case HitPoints.DYING: System.out.println(" AGENT: " + myName + " IS " + myBody.getHPStatusStr() + " and will be unable to act this round."); return; case HitPoints.DEAD: System.out.println(" AGENT: " + myName + " IS DEAD."); return; } System.out.print(" AGENT: " + myName + " was unable to make a decision. And died from Shame - "); System.out.println(myBody.getHPStatusStr()); myBody.setCurHP(-100); return; } private Creature pickRandFoe(List participants){ if(participants.size() > 1){ Creature critter; int idx = rnd.nextInt(participants.size()); critter = ((Participant)participants.get(idx)).getCreature(); if(critter.equals(myBody)) return pickRandFoe(participants); else return critter; } else { // No one to pick from, unless you wish to attack yourself! return null; } } private int rollDie(int sides){ return rnd.nextInt(sides) + 1; } public void meleeAttack(MeleeAttackEvent e) { Creature initiator = e.getInitiator(); Creature affected = e.getAffected(); if(initiator.equals(myBody)){ //System.out.println("AGENT: I, " + myName + ", initiated a melee attack."); if(e.IsMiss()){ ((MeleeAgent)affected.getCombatAgent()).hitTaken(e.getDamageDone()); ((MeleeAgent)initiator.getCombatAgent()).hitDealt(e.getDamageDone()); } else { ((MeleeAgent)initiator.getCombatAgent()).attackMissed(); ((MeleeAgent)affected.getCombatAgent()).sucessfulEvade(); } } if(affected.equals(myBody)){ //System.out.println("AGENT: I, " + myName + ", was affected by " + // initiator.getCreatureName() + "'s attack."); } } public void moralFailure(FlockingEvent e) { Creature initiator = e.getInitiator(); CreatureList affected = e.getAllAffected(); if(initiator.equals(myBody)){ System.out.println(" AGENT: I, " + myName + ", failed my moral check."); } if(affected.contains(e)){ System.out.println(" AGENT: I, " + myName + ", was affected by " + initiator.getCreatureName() + "'s moral check failure."); } } public void endCombat() { } public void newRound() { if(myCH.getInitiativeObj().getParticipantList().size() <= 1) myCH.fireEndCombat(); } public void startCombat() { } public void nextParticipant(CombatEvent e) { if(e.getInitiator().equals(myBody)){ this.makeDecision(); myCH.fireParticipantDone(); } } } Index: CombatAgentMain.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/combatmanager/combatagent/CombatAgentMain.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** CombatAgentMain.java 11 Dec 2002 20:07:49 -0000 1.3 --- CombatAgentMain.java 13 Dec 2002 20:01:49 -0000 1.4 *************** *** 23,27 **** */ ! package org.wettp2p.combatmanager.combatagent; import java.io.*; --- 23,27 ---- */ ! package org.wettp2p.intelligentagents; import java.io.*; *************** *** 29,32 **** --- 29,35 ---- import org.wettp2p.combatmanager.*; import java.util.Random; + import java.util.List; + import java.util.ArrayList; + import java.util.Iterator; *************** *** 35,73 **** * @author Zyrca */ ! public class CombatAgentMain { ! /** * @param args the command line arguments */ public static void main(String[] args) { ! Creature orc = new Creature(); ! orc.setName("Orgmr"); ! orc.setAbilityScores(15, 10, 11, 9, 8, 8); ! orc.setBaseAC(10); ! orc.setArmorAC(4); ! orc.setDexCap(3); ! orc.setSaveBasesFromTotal(2, 0, -1); ! orc.setSpeed(20); ! orc.setHitDice(1); ! orc.setCurHP(4); ! Weapon greatAxe = new Weapon(); ! StatAdjuster sa = new HitPointAdjuster(); ! greatAxe.setDamage(sa); ! greatAxe.setDescription("Great Axe"); ! greatAxe.setDamageDice("1d12+3"); ! int greatAxeIDX = orc.addWeapon(greatAxe); ! ! Creature orc2 = new Creature(); ! orc2.setName("Grutmn"); ! orc2.setAbilityScores(15, 10, 11, 9, 8, 8); ! orc2.setBaseAC(10); ! orc2.setArmorAC(4); ! orc2.setDexCap(3); ! orc2.setSaveBasesFromTotal(2, 0, -1); ! orc2.setSpeed(20); ! orc2.setHitDice(1); ! orc2.setCurHP(4); ! orc2.addWeapon(greatAxe); Creature drycon = new Creature(); drycon.setName("Drycon"); --- 38,60 ---- * @author Zyrca */ ! public class CombatAgentMain implements CombatListener { ! private static Random rnd; ! ! private CombatHandler ch; ! public CombatAgentMain(){ ! } /** * @param args the command line arguments */ public static void main(String[] args) { ! CombatAgentMain me = new CombatAgentMain(); ! me.runSim(); ! } ! ! public void runSim(){ ! ch = new CombatHandler(); ! ch.registerListener(this); + rnd = new Random(System.currentTimeMillis()); Creature drycon = new Creature(); drycon.setName("Drycon"); *************** *** 77,83 **** drycon.setSaveBases(3, 3, 3); drycon.setSpeed(40); drycon.setHPfromTotal(24); drycon.setInitBaseModifier(0); - drycon.setLevel(3); drycon.setOtherInfo("Monk"); drycon.setPlayerName("Heather"); --- 64,70 ---- drycon.setSaveBases(3, 3, 3); drycon.setSpeed(40); + drycon.setLevel(3); drycon.setHPfromTotal(24); drycon.setInitBaseModifier(0); drycon.setOtherInfo("Monk"); drycon.setPlayerName("Heather"); *************** *** 87,123 **** fists.setDescription("Drycon's fists"); fists.setIsRanged(false); drycon.addWeapon(fists); ! Initiative init = new Initiative(); ! init.addParticipant(orc); ! init.addParticipant(orc2); ! init.addParticipant(drycon); ! ! for(int i = 0; i < 5; i++){ ! System.out.println("*** NEW INITIATIVE ROUND ***"); ! ! Participant partic; ! init.newRound(); ! while (init.hasMoreParticipants()){ ! partic = init.getNextParticipant(); ! System.out.println(partic.getCreature().getName() + ! " (" + partic.getInitiative() + ")"); ! } } ! ! } private static String askQuestion(String q){ System.out.print(q + " "); ! BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String a = null; ! try { a = br.readLine(); --- 74,158 ---- fists.setDescription("Drycon's fists"); fists.setIsRanged(false); + drycon.setCombatAgent(new MeleeAgent(drycon, rnd, ch)); drycon.addWeapon(fists); ! ch.getInitiative().addParticipant(drycon); ! List orcArmy = new ArrayList(); ! Creature newOrc; ! for(int i = 0; i < 10; i++){ ! newOrc = makeOrc("Orc " + i); ! orcArmy.add(newOrc); ! ch.getInitiative().addParticipant(newOrc); } + ch.fireStartCombat(); + + //while(init.getParticipantList().size() > 1){ + + + //Participant partic; + //Creature critter; + + //init.newRound(); + //while (init.hasMoreParticipants()){ + //partic = init.getNextParticipant(); + + //critter = partic.getCreature(); + //System.out.print("*** " + critter.getName() + " (" + partic.getInitiative() + ")"); + //System.out.print(" <" + critter.getHP() + " hp>"); + //System.out.print(" [" + ((MeleeAgent)critter.getCombatAgent()).getMoral() + " moral] -- "); + //MeleeAgent creatureAgent = (MeleeAgent)critter.getCombatAgent(); + //List particList = init.getParticipantList(); + + //if(!creatureAgent.makeDecision(particList)){ + // init.removeParticipant(); + //} + //} + //} + //init.newRound(); + //System.out.println(); + //if(init.hasMoreParticipants()) + // System.out.println(((Participant)init.getParticipantList().get(0)).getName() + " is vicortious!"); + //else + // System.out.println("Everyone Died"); + } + + private Creature makeOrc(String name){ + Creature orc = new Creature(); + orc.setName(name); + orc.setAbilityScores(15, 10, 11, 9, 8, 8); + orc.setBaseAC(10); + orc.setArmorAC(4); + orc.setDexCap(3); + orc.setSaveBasesFromTotal(2, 0, -1); + orc.setSpeed(20); + orc.setHitDice(1); + orc.setCurHP(4); + Weapon greatAxe = new Weapon(); + StatAdjuster sa = new HitPointAdjuster(); + greatAxe.setDamage(sa); + greatAxe.setDescription("Great Axe"); + greatAxe.setDamageDice("1d12+3"); + int greatAxeIDX = orc.addWeapon(greatAxe); + orc.setCombatAgent(new MeleeAgent(orc, rnd, ch)); ! orc.addWeapon(greatAxe); ! ! return orc; ! } ! ! private static int rollDie(int sides){ ! return rnd.nextInt(sides) + 1; } private static String askQuestion(String q){ System.out.print(q + " "); ! BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String a = null; ! try { a = br.readLine(); *************** *** 128,131 **** --- 163,191 ---- return a; + + } + + public void endCombat() { + System.out.println(" *********** End Combat ***********"); + } + + public void meleeAttack(MeleeAttackEvent e) { + System.out.println(" meleeAttack: " + e.getWhatHappened()); + } + + public void moralFailure(FlockingEvent e) { + System.out.println(" moralFailure: " + e.getWhatHappened()); + } + + public void newRound() { + System.out.println(" ***** NEW INITIATIVE ROUND *****"); + } + + public void nextParticipant(CombatEvent e) { + System.out.println(" ** " + e.getWhatHappened() + " ** "); + } + + public void startCombat() { + System.out.println("*********** Start Combat ***********"); } |
Update of /cvsroot/wett-p2p/org/wettp2p/combatmanager In directory sc8-pr-cvs1:/tmp/cvs-serv24541 Added Files: CombatEvent.java CombatHandler.java CombatListener.java CombatManagerPanel.java CombatmanagerSuite.java Event.java FlockingEvent.java Initiative.java InitiativeTest.java MeleeAttackEvent.java Participant.java ParticipantList.java ParticipantListCellRenderer.java ParticipantListPanel.java TextDisplayPanel.java Log Message: Created combat handler --- NEW FILE: CombatEvent.java --- /* * CombatEvent.java * * Created on December 12, 2002, 8:23 AM */ package org.wettp2p.combatmanager; import java.awt.*; import java.awt.event.*; import org.wettp2p.creature.*; /** * * @author Zyrca */ public class CombatEvent implements Event { private String myWhatHappened; private Object mySource; private Creature myInitiator; public CombatEvent(Object source) { mySource = source; } public CombatEvent(Object source, Creature initiator) { mySource = source; myInitiator = initiator; } public void setInitiator(Creature initiator){ myInitiator = initiator; } public Creature getInitiator(){ return myInitiator; } public String getWhatHappened() { return myWhatHappened; } public void setWhatHappened(String whatHappened){ myWhatHappened = whatHappened; } } --- NEW FILE: CombatHandler.java --- /* * CombatHandler.java * * Created on December 12, 2002, 11:29 AM */ package org.wettp2p.combatmanager; import org.wettp2p.creature.*; import org.wettp2p.combatmanager.Participant; import java.util.List; import java.util.Iterator; import java.util.ArrayList; import java.util.Random; /** * * @author Zyrca */ public class CombatHandler { private static final int MELEE_ATTACK = 1; private static final int MORAL_FAILURE = 2; private static final int NEW_ROUND = 3; private static final int END_COMBAT = 4; private static final int START_COMBAT = 5; private static final int NEXT_PARTIC = 6; private List registeredObjects; private Iterator callBackItr; private Initiative init; private List curRoundResults; private Random rnd; private Creature curCritter; /** Creates a new instance of CombatHandler */ public CombatHandler() { registeredObjects = new ArrayList(); curRoundResults = new ArrayList(); init = new Initiative(); rnd = new Random(System.currentTimeMillis()); } public Initiative getInitiativeObj(){ return init; } // ******************************************** // *************** REGISTRATION *************** // ******************************************** public void registerListener(CombatListener obj){ registeredObjects.add(obj); } public void unregisterListener(CombatListener obj){ registeredObjects.remove(obj); } // ******************************************** // ****************** EVENTS ****************** // ******************************************** public void fireAttackOccured(MeleeAttackEvent e){ if(! e.getInitiator().equals(curCritter)){ e.setWhatHappened(e.getInitiator().getName() + " attempted to attack out of turn."); } else { Creature initiator = e.getInitiator(); String myName = initiator.getName(); Creature affected = e.getAffected(); int toHit = rollDie(20); toHit += initiator.getMeleeMod(); if(toHit >= affected.getCurAC()){ int dam = rollDie(12) + 3; initiator.getFavoredMeleeWeapon().getDamage().damage(affected, dam); e.setWhatHappened(myName + " HIT " + affected.getCreatureName() + " FOR " + dam + " HP. "); } else { e.setWhatHappened(myName + " MISSED " + affected.getCreatureName()); } } callbacks(e, MELEE_ATTACK); } public void fireMoralFailure(FlockingEvent e){ callbacks(e, MORAL_FAILURE); } public void fireStartCombat(){ callbacks(null, START_COMBAT); fireNewRound(); } public void fireNewRound(){ init.newRound(); callbacks(null, NEW_ROUND); fireParticipantDone(); } public void fireParticipantDone(){ if(init.hasMoreParticipants()){ Participant p = init.getNextParticipant(); curCritter = p.getCreature(); int hpStatus = curCritter.getHPStatus(); switch(hpStatus){ case HitPoints.NORMAL: this.handleNormal(p); break; case HitPoints.STAGGERED: this.handleStaggered(p); break; case HitPoints.DISABLED: this.handleDisabled(p); break; case HitPoints.UNCONSCIOUS: this.handleUnconscious(p); break; case HitPoints.DYING: this.handleDying(p); break; case HitPoints.DEAD: this.handleDead(p); break; } } else{ fireNewRound(); } } public void fireEndCombat(){ callbacks(null, END_COMBAT); } // ******************************************** // ******* fireParticipantDone METHODS ******** // ******************************************** private void handleNormal(Participant p){ CombatEvent e = new CombatEvent(this, curCritter); e.setWhatHappened(curCritter.getCreatureName() + "'s turn"); callbacks(e, NEXT_PARTIC); } private void handleStaggered(Participant p){ // TODO: implement code to handle a character in staggered state this.handleNormal(p); } private void handleDisabled(Participant p){ // TODO: implement code to handle a character in disabled state this.handleNormal(p); } private void handleUnconscious(Participant p){ this.handleNormal(p); } private void handleDying(Participant p){ CombatEvent e = new CombatEvent(this, curCritter); if(!curCritter.isStable()){ int stableCheck = this.rollDie(10); if(stableCheck == 1){ p.getCreature().setIsStable(true); e.setWhatHappened(curCritter.getCreatureName() + " became stable."); } else { p.getCreature().adjHP(-1); e.setWhatHappened(curCritter.getCreatureName() + " lost a hit point."); } } callbacks(e, NEXT_PARTIC); } private void handleDead(Participant p){ CombatEvent e = new CombatEvent(this, curCritter); e.setWhatHappened(curCritter.getCreatureName() + " is DEAD"); init.removeParticipant(); callbacks(e, NEXT_PARTIC); } // ******************************************** // **************** CALLBACKS ***************** // ******************************************** private void callbacks(Event e, int eventID){ CombatListener obj = null; callBackItr = registeredObjects.iterator(); while(callBackItr.hasNext()){ obj = (CombatListener)callBackItr.next(); switch(eventID){ case MELEE_ATTACK: obj.meleeAttack((MeleeAttackEvent)e); break; case MORAL_FAILURE: obj.moralFailure((FlockingEvent)e); break; case NEW_ROUND: obj.newRound(); break; case START_COMBAT: obj.startCombat(); break; case END_COMBAT: obj.endCombat(); break; case NEXT_PARTIC: obj.nextParticipant((CombatEvent)e); break; } } } private int rollDie(int sides){ return rnd.nextInt(sides) + 1; } } --- NEW FILE: CombatListener.java --- /* * CombatListener.java * * Created on December 12, 2002, 8:10 AM */ package org.wettp2p.combatmanager; /** * * @author Zyrca */ public interface CombatListener { void meleeAttack( MeleeAttackEvent e ); void moralFailure( FlockingEvent e ); void newRound(); void nextParticipant( CombatEvent e ); void startCombat(); void endCombat(); } --- NEW FILE: CombatManagerPanel.java --- /* * CombatManagerPanel.java * * Copyright (C) 2002, Ray Benjamin * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * Created on November 23, 2002, 2:22 PM */ package org.wettp2p.combatmanager; import org.wettp2p.creature.*; import javax.swing.*; import java.util.*; /** * The CombatManager panel presents an interface that the user can use to * run a d20 Game System-style combat. * * @author Ray Benjamin */ public class CombatManagerPanel extends javax.swing.JPanel { /** Creates new form CombatManagerPanel */ public CombatManagerPanel() { initComponents(); initMyComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ private void initComponents() {//GEN-BEGIN:initComponents controlPanel = new javax.swing.JPanel(); rollInitiativeButton = new javax.swing.JButton(); setLayout(new java.awt.BorderLayout()); setMinimumSize(new java.awt.Dimension(640, 480)); setPreferredSize(new java.awt.Dimension(640, 480)); rollInitiativeButton.setText("Initiative"); controlPanel.add(rollInitiativeButton); add(controlPanel, java.awt.BorderLayout.SOUTH); }//GEN-END:initComponents // Adding components that don't neatly fit in the netbeans gui builder /** * This routine adds additional pieces to the interface that were not * built using the NetBeans GUI builder. */ private void initMyComponents() { participantList = new ParticipantList(); // add Participant List Panel participantListPanel = new ParticipantListPanel(); add(participantListPanel, java.awt.BorderLayout.EAST); // add Text Display Panel textDisplayPanel = new TextDisplayPanel(); add(textDisplayPanel, java.awt.BorderLayout.CENTER); } // Work Routines public void setParticipants(Vector participants) { participantListPanel.setParticipantList(participants); } // Main Routine, primarily for testing public static void main(String args[]) { JFrame gui = new JFrame("CombatManagerPanel"); gui.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { System.exit(0); } }); CombatManagerPanel combatManagerPanel = new CombatManagerPanel(); gui.getContentPane().add(combatManagerPanel); // Add a couple of participants Creature fighterBob = new Creature(); fighterBob.setName("Uncle Bob"); Creature orcGronk = new Creature(); orcGronk.setName("Gronk"); Vector participantList = new Vector(); participantList.add(new Participant(fighterBob)); participantList.add(new Participant(orcGronk)); combatManagerPanel.setParticipants(participantList); gui.pack(); gui.show(); } // Helper Classes /** Initiative Action */ /** Next Creature */ /** Next Round */ /** Check Surprise */ /** Listen Check */ /** Spot Check */ // Combat Actions /** Standard Action */ /** Full Round Action */ /** Attack Action */ /** Move Equivalent Action */ /** Free Action */ /** Not an Action */ /** Partial Action */ /** Move Action */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton rollInitiativeButton; private javax.swing.JPanel controlPanel; // End of variables declaration//GEN-END:variables // Additional variables private ParticipantList participantList; private ParticipantListPanel participantListPanel; private TextDisplayPanel textDisplayPanel; } --- NEW FILE: CombatmanagerSuite.java --- /* * CombatmanagerSuite.java * NetBeans JUnit based test * * Created on December 11, 2002, 12:48 PM */ package org.wettp2p.combatmanager; import junit.framework.*; import org.netbeans.junit.*; /** * * @author Heather */ public class CombatmanagerSuite extends NbTestCase { public CombatmanagerSuite(java.lang.String testName) { super(testName); } public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { //--JUNIT: //This block was automatically generated and can be regenerated again. //Do NOT change lines enclosed by the --JUNIT: and :JUNIT-- tags. TestSuite suite = new NbTestSuite("CombatmanagerSuite"); suite.addTest(org.wettp2p.combatmanager.InitiativeTest.suite()); //:JUNIT-- //This value MUST ALWAYS be returned from this function. return suite; } // Add test methods here, they have to start with 'test' name. // for example: // public void testHello() {} } --- NEW FILE: Event.java --- /* * Event.java * * Created on December 12, 2002, 2:09 PM */ package org.wettp2p.combatmanager; /** * * @author Zyrca */ public interface Event { public String getWhatHappened(); } --- NEW FILE: FlockingEvent.java --- /* * MoralFailureEvent.java * * Created on December 12, 2002, 4:31 PM */ package org.wettp2p.combatmanager; import org.wettp2p.creature.Creature; import org.wettp2p.creature.CreatureList; /** * * @author Heather */ public class FlockingEvent extends CombatEvent implements Event { private CreatureList myAffected; public FlockingEvent(Object source) { super(source); myAffected = new CreatureList(); } public FlockingEvent(Object source, Creature initiator) { super(source, initiator); myAffected = new CreatureList(); } public CreatureList getAllAffected(){ return myAffected; } public Creature getAffected(int idx){ return myAffected.getCreature(idx); } public boolean addAffected(Creature affected){ return myAffected.add(affected); } } --- NEW FILE: Initiative.java --- /* Copyright (C) 2002 Heather Cousineau This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * initiative.java * * Created on December 11, 2002, 8:34 AM */ package org.wettp2p.combatmanager; import org.wettp2p.creature.*; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Random; /** * * @author Zyrca */ public class Initiative { private List myParticipants = null; private Iterator roundItr = null; private Random rnd = null; /** Creates a new instance of initiative */ public Initiative() { myParticipants = new ArrayList(); rnd = new Random(System.currentTimeMillis()); } public Participant addParticipant(Creature critter){ Participant partic = new Participant(critter); myParticipants.add(partic); return partic; } public Participant getParticipant(Creature critter){ Iterator itr = myParticipants.iterator(); Participant participant; while(itr.hasNext()){ participant = (Participant)itr.next(); if(participant.getCreature().equals(critter)) return participant; } return null; } public List getParticipantList(){ return myParticipants; } public void newRound(){ Iterator itr = myParticipants.iterator(); Participant participant; int init; while(itr.hasNext()){ participant = (Participant)itr.next(); init = participant.getCreature().getInitModifier(); participant.setInitiative(rollInit(init)); } java.util.Collections.sort(myParticipants); roundItr = myParticipants.iterator(); } public boolean hasMoreParticipants(){ return roundItr.hasNext(); } public void removeParticipant(){ roundItr.remove(); } public Participant getNextParticipant() throws NoSuchElementException { return (Participant)roundItr.next(); } private int rollInit(int modifier){ return (rnd.nextInt(10)+1) + modifier; } } --- NEW FILE: InitiativeTest.java --- /* Copyright (C) 2002 Heather Cousineau This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * InitiativeTest.java * NetBeans JUnit based test * * Created on December 11, 2002, 11:49 AM */ package org.wettp2p.combatmanager; import junit.framework.*; import org.netbeans.junit.*; import org.wettp2p.creature.*; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Random; import java.lang.Boolean; /** * * @author Zyrca */ public class InitiativeTest extends NbTestCase { private Creature orc; private Creature orc2; private Creature drycon; public InitiativeTest(java.lang.String testName) { super(testName); // Create 3 creatures (2 orcs and a monk) // to be used in these tests. orc = new Creature(); orc.setName("Orgmr"); orc.setAbilityScores(15, 10, 11, 9, 8, 8); orc.setBaseAC(10); orc.setArmorAC(4); orc.setDexCap(3); orc.setSaveBasesFromTotal(2, 0, -1); orc.setSpeed(20); orc.setHitDice(1); orc.setCurHP(4); Weapon greatAxe = new Weapon(); StatAdjuster sa = new HitPointAdjuster(); greatAxe.setDamage(sa); greatAxe.setDescription("Great Axe"); greatAxe.setDamageDice("1d12+3"); int greatAxeIDX = orc.addWeapon(greatAxe); orc2 = new Creature(); orc2.setName("Grutmn"); orc2.setAbilityScores(15, 10, 11, 9, 8, 8); orc2.setBaseAC(10); orc2.setArmorAC(4); orc2.setDexCap(3); orc2.setSaveBasesFromTotal(2, 0, -1); orc2.setSpeed(20); orc2.setHitDice(1); orc2.setCurHP(4); orc2.addWeapon(greatAxe); drycon = new Creature(); drycon.setName("Drycon"); drycon.setAbilityScores(17, 18, 13, 13, 15, 12); drycon.setWisAsBonusToAC(); drycon.setBaseAC(10); drycon.setSaveBases(3, 3, 3); drycon.setSpeed(40); drycon.setHPfromTotal(24); drycon.setInitBaseModifier(0); drycon.setLevel(3); drycon.setOtherInfo("Monk"); drycon.setPlayerName("Heather"); Weapon fists = new Weapon(); fists.setCritical(2); fists.setDamage(new HitPointAdjuster()); fists.setDescription("Drycon's fists"); fists.setIsRanged(false); drycon.addWeapon(fists); } public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } /** Test of adding and retreiving participants, of class org.wettp2p.combatmanager.Initiative. */ public void testAddAndGetParticipant() { System.out.println("org.wettp2p.combatmanager.Initiative.testAddAndGetParticipant"); Initiative init = new Initiative(); init.addParticipant(orc); init.newRound(); if(init.hasMoreParticipants() && (! init.getNextParticipant().getCreature().equals(orc))) fail("Orc was not successfully added to the participant list"); } /** Test of newRound method, of class org.wettp2p.combatmanager.Initiative. */ public void testNewRound() { System.out.println("org.wettp2p.combatmanager.Initiative.testNewRound"); System.out.println("Initiative modifier: " + drycon.getInitModifier()); Initiative init = new Initiative(); init.addParticipant(drycon); boolean done = false; List keepNums = new ArrayList(20); for(int i = 0; i < 20; i++) keepNums.add(i, new Boolean(false)); // Drycon has a +4 modifier to initiative // so make sure she can get all of them! Participant dry; int iterations = 0; while(! done){ iterations++; if(iterations > 100000) fail("Initiative did not roll all numbers in 100000 tries"); // Roll Drycon's initiative init.newRound(); dry = init.getNextParticipant(); keepNums.set(dry.getInitiative(), new Boolean(true)); for(int i = 0; i < 4; i++){ if(((Boolean)keepNums.get(i)).booleanValue()){ fail("Initiative should never be below 4"); } } for(int i = 15; i < 20; i++){ if(((Boolean)keepNums.get(i)).booleanValue()){ fail("Initiative should never be above 15"); } } for(int i = 5; i < 14; i++){ done = true; if(!((Boolean)keepNums.get(i)).booleanValue()){ done = false; break; } } } } /** Test of hasMoreParticipants method, of class org.wettp2p.combatmanager.Initiative. */ public void testHasMoreParticipants() { System.out.println("org.wettp2p.combatmanager.Initiative.testHasMoreParticipants"); Initiative init = new Initiative(); init.addParticipant(orc2); init.newRound(); if(!init.hasMoreParticipants()) fail("There should be a participant."); init.getNextParticipant(); if(init.hasMoreParticipants()) fail("There should not be another participant."); } /** Test of getNextParticipant method, of class org.wettp2p.combatmanager.Initiative. */ public void testGetNextParticipant() { System.out.println("org.wettp2p.combatmanager.Initiative.testGetNextParticipant"); Initiative init = new Initiative(); init.addParticipant(orc2); init.newRound(); init.getNextParticipant(); try{ init.getNextParticipant(); fail("getNextParticipant should throw NoSuchElementException if "+ "it does not have any more elements"); } catch (NoSuchElementException e){} } public static Test suite() { TestSuite suite = new NbTestSuite(InitiativeTest.class); return suite; } } --- NEW FILE: MeleeAttackEvent.java --- /* * MeleeAttackEvent.java * * Created on December 12, 2002, 1:59 PM */ package org.wettp2p.combatmanager; import org.wettp2p.creature.Weapon; import org.wettp2p.creature.Creature; import org.wettp2p.creature.CreatureList; /** * * @author Zyrca */ public class MeleeAttackEvent extends CombatEvent implements Event { private Weapon myWeaponUsed; private Creature myAffected; private int myDamageDone; private boolean myMiss; /** Creates a new instance of MeleeAttackEvent */ public MeleeAttackEvent( Object source, Creature initiator, Creature affected, Weapon weaponUsed) { super(source, initiator); myAffected = affected; myWeaponUsed = weaponUsed; myDamageDone = 0; myMiss = true; } public Creature getAffected(){ return myAffected; } public Weapon getWeaponUsed(){ return myWeaponUsed; } public void setDamageDone(int damage){ myDamageDone = damage; } public int getDamageDone(){ return myDamageDone; } public void setIsMiss(boolean missed){ myMiss = missed; } public boolean IsMiss(){ return myMiss; } } --- NEW FILE: Participant.java --- /* * Participant.java * * Copyright (C) 2002, Ray Benjamin * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Created on November 24, 2002, 5:20 PM */ package org.wettp2p.combatmanager; import org.wettp2p.creature.*; import org.wettp2p.intelligentagents.*; /** * This class carries information about a given participant in Combat Manager. * * @author Ray Benjamin */ public class Participant implements Comparable { /** Creates a new instance of Participant */ public Participant() { } /** Creates a new instance of Paricipant using the * supplied creature object. * * @param critter A Creature object. * */ public Participant(Creature critter) { creature = critter; } /** Get a reference to the creature object. * @return A reference to the creature object. */ public Creature getCreature() { return creature; } /** Indicates if the participant is involved in the current melee or not. * * @return true if the participant is in combat. */ public boolean isInCombat() { return inCombat; } /** Sets the inCombat flag to the specified value. * * @param value The new value for the inCombat flag. */ public void setInCombat(boolean value) { inCombat = value; } /** Is the creature flatfooted? A creature is flatfooted if they are suprirsed. They * loose thier dexterity bonus to AC. * @return A boolean indicating whether or not a creature is flatfooted. */ public boolean isFlatfooted() { return flatfooted; } /** Set if the creature is flat footed. * @param value A boolean indicating whether or not a creature is flatfooted */ public void setFlatfooted(boolean value) { flatfooted = value; } /** Is the creature surprised? If they are, they are also flatfooted. * @return A boolean indicating whether or not a creature is */ public boolean isSurprised() { return surprised; } /** Set if the creature is surprised or not. * @param value A boolean indicating whether or not a creature is surprised. */ public void setSurprised(boolean value) { surprised = value; } /** The creature's acctual initiative for the current round. * @return The initiative value. */ public int getInitiative() { return initiative; } /** Sets the initiative value for this round. * @param value The initiative value. */ public void setInitiative(int value) { initiative = value; } /** Get the name of the creature. * @return The name of the creature. */ public String getName() { return creature.getCreatureName(); } /** Get the name of the person controling the creature. * @return Player name. */ public String getPlayerName() { return creature.getPlayerName(); } /** Get the creature's current armor class modified by flattfootedness and * surprise. * @return The creature's current armor class. */ public int getCurrentAC() { if(this.isFlatfooted()) return creature.getFlatFootedAC(); else return creature.getCurAC(); } /** Get the creature's current hit points. * @return The creature's current hit points. */ public int getCurrentHitPoints() { return creature.getCurHP(); } public int getHitPointStatus() { return creature.getHPStatus(); } public String getHitPointStatusStr(){ return creature.getHPStatusStr(); } /** Compares this object with the specified object for order. Returns a * negative integer, zero, or a positive integer as this object is less * than, equal to, or greater than the specified object.<p> * * In the foregoing description, the notation * <tt>sgn(</tt><i>expression</i><tt>)</tt> designates the mathematical * <i>signum</i> function, which is defined to return one of <tt>-1</tt>, * <tt>0</tt>, or <tt>1</tt> according to whether the value of <i>expression</i> * is negative, zero or positive. * * The implementor must ensure <tt>sgn(x.compareTo(y)) == * -sgn(y.compareTo(x))</tt> for all <tt>x</tt> and <tt>y</tt>. (This * implies that <tt>x.compareTo(y)</tt> must throw an exception iff * <tt>y.compareTo(x)</tt> throws an exception.)<p> * * The implementor must also ensure that the relation is transitive: * <tt>(x.compareTo(y)>0 && y.compareTo(z)>0)</tt> implies * <tt>x.compareTo(z)>0</tt>.<p> * * Finally, the implementer must ensure that <tt>x.compareTo(y)==0</tt> * implies that <tt>sgn(x.compareTo(z)) == sgn(y.compareTo(z))</tt>, for * all <tt>z</tt>.<p> * * It is strongly recommended, but <i>not</i> strictly required that * <tt>(x.compareTo(y)==0) == (x.equals(y))</tt>. Generally speaking, any * class that implements the <tt>Comparable</tt> interface and violates * this condition should clearly indicate this fact. The recommended * language is "Note: this class has a natural ordering that is * inconsistent with equals." * * In this particular case, compareTo is based on the modified initiative * for each participant. * * @return a negative integer, zero, or a positive integer as this object * is less than, equal to, or greater than the specified object. * @param o the Object to be compared. */ public int compareTo(Object o) { Participant otherParticipant = (Participant) o; //return (initiative - otherParticipant.initiative); return (otherParticipant.initiative - initiative); } public MeleeAgent getCombatAgent(){ return ((MeleeAgent)creature.getCombatAgent()); } // Variables private boolean inCombat = false; private boolean flatfooted = false; private boolean surprised = false; private int initiative = 0; private Creature creature = null; } --- NEW FILE: ParticipantList.java --- /* * ParticipantList.java * * Copyright (C) 2002, Ray Benjamin * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Created on December 1, 2002, 9:09 PM */ package org.wettp2p.combatmanager; import java.util.*; /** * * @author Ray Benjamin */ public class ParticipantList extends javax.swing.AbstractListModel implements List { /** Creates a new instance of ParticipantList */ public ParticipantList() { list = new ArrayList(); } /** Returns the value at the specified index. * @param index the requested index * @return the value at <code>index</code> * */ public final Object getElementAt(int index) { return list.get(index); } /** * Returns the length of the list. * @return the length of the list * */ public final int getSize() { return list.size(); } /** Ensures that this collection contains the specified element (optional * operation). Returns <tt>true</tt> if this collection changed as a * result of the call. (Returns <tt>false</tt> if this collection does * not permit duplicates and already contains the specified element.)<p> * * Collections that support this operation may place limitations on what * elements may be added to this collection. In particular, some * collections will refuse to add <tt>null</tt> elements, and others will * impose restrictions on the type of elements that may be added. * Collection classes should clearly specify in their documentation any * restrictions on what elements may be added.<p> * * If a collection refuses to add a particular element for any reason * other than that it already contains the element, it <i>must</i> throw * an exception (rather than returning <tt>false</tt>). This preserves * the invariant that a collection always contains the specified element * after this call returns. * * @param o element whose presence in this collection is to be ensured. * @return <tt>true</tt> if this collection changed as a result of the * call * * @throws UnsupportedOperationException <tt>add</tt> is not supported by * this collection. * @throws ClassCastException class of the specified element prevents it * from being added to this collection. * @throws NullPointerException if the specified element is null and this * collection does not support null elements. * @throws IllegalArgumentException some aspect of this element prevents * it from being added to this collection. * */ public final boolean add(Object o) { return list.add(o); } /** Inserts the specified element at the specified position in this list * (optional operation). Shifts the element currently at that position * (if any) and any subsequent elements to the right (adds one to their * indices). * * @param index index at which the specified element is to be inserted. * @param element element to be inserted. * * @throws UnsupportedOperationException if the <tt>add</tt> method is not * supported by this list. * @throws ClassCastException if the class of the specified element * prevents it from being added to this list. * @throws NullPointerException if the specified element is null and * this list does not support null elements. * @throws IllegalArgumentException if some aspect of the specified * element prevents it from being added to this list. * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index > size()). * */ public final void add(int index, Object element) { list.add(index, element); } /** Adds all of the elements in the specified collection to this collection * (optional operation). The behavior of this operation is undefined if * the specified collection is modified while the operation is in progress. * (This implies that the behavior of this call is undefined if the * specified collection is this collection, and this collection is * nonempty.) * * @param c elements to be inserted into this collection. * @return <tt>true</tt> if this collection changed as a result of the * call * * @throws UnsupportedOperationException if this collection does not * support the <tt>addAll</tt> method. * @throws ClassCastException if the class of an element of the specified * collection prevents it from being added to this collection. * @throws NullPointerException if the specified collection contains one * or more null elements and this collection does not support null * elements, or if the specified collection is <tt>null</tt>. * @throws IllegalArgumentException some aspect of an element of the * specified collection prevents it from being added to this * collection. * @see #add(Object) * */ public final boolean addAll(Collection c) { return list.addAll(c); } /** Inserts all of the elements in the specified collection into this * list at the specified position (optional operation). Shifts the * element currently at that position (if any) and any subsequent * elements to the right (increases their indices). The new elements * will appear in this list in the order that they are returned by the * specified collection's iterator. The behavior of this operation is * unspecified if the specified collection is modified while the * operation is in progress. (Note that this will occur if the specified * collection is this list, and it's nonempty.) * * @param index index at which to insert first element from the specified * collection. * @param c elements to be inserted into this list. * @return <tt>true</tt> if this list changed as a result of the call. * * @throws UnsupportedOperationException if the <tt>addAll</tt> method is * not supported by this list. * @throws ClassCastException if the class of one of elements of the * specified collection prevents it from being added to this * list. * @throws NullPointerException if the specified collection contains one * or more null elements and this list does not support null * elements, or if the specified collection is <tt>null</tt>. * @throws IllegalArgumentException if some aspect of one of elements of * the specified collection prevents it from being added to * this list. * @throws IndexOutOfBoundsException if the index is out of range (index * < 0 || index > size()). * */ public final boolean addAll(int index, Collection c) { return list.addAll(index,c); } /** Removes all of the elements from this collection (optional operation). * This collection will be empty after this method returns unless it * throws an exception. * * @throws UnsupportedOperationException if the <tt>clear</tt> method is * not supported by this collection. * */ public final void clear() { list.clear(); } /** Returns <tt>true</tt> if this collection contains the specified * element. More formally, returns <tt>true</tt> if and only if this * collection contains at least one element <tt>e</tt> such that * <tt>(o==null ? e==null : o.equals(e))</tt>. * * @param o element whose presence in this collection is to be tested. * @return <tt>true</tt> if this collection contains the specified * element * @throws ClassCastException if the type of the specified element * is incompatible with this collection (optional). * @throws NullPointerException if the specified element is null and this * collection does not support null elements (optional). * */ public final boolean contains(Object o) { return list.contains(o); } /** Returns <tt>true</tt> if this collection contains all of the elements * in the specified collection. * * @param c collection to be checked for containment in this collection. * @return <tt>true</tt> if this collection contains all of the elements * in the specified collection * @throws ClassCastException if the types of one or more elements * in the specified collection are incompatible with this * collection (optional). * @throws NullPointerException if the specified collection contains one * or more null elements and this collection does not support null * elements (optional). * @throws NullPointerException if the specified collection is * <tt>null</tt>. * @see #contains(Object) * */ public final boolean containsAll(Collection c) { return list.containsAll(c); } /** Returns the element at the specified position in this list. * * @param index index of element to return. * @return the element at the specified position in this list. * * @throws IndexOutOfBoundsException if the index is out of range (index * < 0 || index >= size()). * */ public final Object get(int index) { return list.get(index); } /** Returns the index in this list of the first occurrence of the specified * element, or -1 if this list does not contain this element. * More formally, returns the lowest index <tt>i</tt> such that * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, * or -1 if there is no such index. * * @param o element to search for. * @return the index in this list of the first occurrence of the specified * element, or -1 if this list does not contain this element. * @throws ClassCastException if the type of the specified element * is incompatible with this list (optional). * @throws NullPointerException if the specified element is null and this * list does not support null elements (optional). * */ public final int indexOf(Object o) { return list.indexOf(o); } /** Returns <tt>true</tt> if this collection contains no elements. * * @return <tt>true</tt> if this collection contains no elements * */ public final boolean isEmpty() { return list.isEmpty(); } /** Returns an iterator over the elements in this collection. There are no * guarantees concerning the order in which the elements are returned * (unless this collection is an instance of some class that provides a * guarantee). * * @return an <tt>Iterator</tt> over the elements in this collection * */ public final Iterator iterator() { return list.iterator(); } /** Returns the index in this list of the last occurrence of the specified * element, or -1 if this list does not contain this element. * More formally, returns the highest index <tt>i</tt> such that * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, * or -1 if there is no such index. * * @param o element to search for. * @return the index in this list of the last occurrence of the specified * element, or -1 if this list does not contain this element. * @throws ClassCastException if the type of the specified element * is incompatible with this list (optional). * @throws NullPointerException if the specified element is null and this * list does not support null elements (optional). * */ public final int lastIndexOf(Object o) { return list.lastIndexOf(o); } /** Returns a list iterator of the elements in this list (in proper * sequence). * * @return a list iterator of the elements in this list (in proper * sequence). * */ public final ListIterator listIterator() { return list.listIterator(); } /** Returns a list iterator of the elements in this list (in proper * sequence), starting at the specified position in this list. The * specified index indicates the first element that would be returned by * an initial call to the <tt>next</tt> method. An initial call to * the <tt>previous</tt> method would return the element with the * specified index minus one. * * @param index index of first element to be returned from the * list iterator (by a call to the <tt>next</tt> method). * @return a list iterator of the elements in this list (in proper * sequence), starting at the specified position in this list. * @throws IndexOutOfBoundsException if the index is out of range (index * < 0 || index > size()). * */ public final ListIterator listIterator(int index) { return list.listIterator(index); } /** Removes a single instance of the specified element from this * collection, if it is present (optional operation). More formally, * removes an element <tt>e</tt> such that <tt>(o==null ? e==null : * o.equals(e))</tt>, if this collection contains one or more such * elements. Returns true if this collection contained the specified * element (or equivalently, if this collection changed as a result of the * call). * * @param o element to be removed from this collection, if present. * @return <tt>true</tt> if this collection changed as a result of the * call * * @throws ClassCastException if the type of the specified element * is incompatible with this collection (optional). * @throws NullPointerException if the specified element is null and this * collection does not support null elements (optional). * @throws UnsupportedOperationException remove is not supported by this * collection. * */ public final boolean remove(Object o) { return list.remove(o); } /** Removes the element at the specified position in this list (optional * operation). Shifts any subsequent elements to the left (subtracts one * from their indices). Returns the element that was removed from the * list. * * @param index the index of the element to removed. * @return the element previously at the specified position. * * @throws UnsupportedOperationException if the <tt>remove</tt> method is * not supported by this list. * @throws IndexOutOfBoundsException if the index is out of range (index * < 0 || index >= size()). * */ public final Object remove(int index) { return list.remove(index); } /** * Removes all this collection's elements that are also contained in the * specified collection (optional operation). After this call returns, * this collection will contain no elements in common with the specified * collection. * * @param c elements to be removed from this collection. * @return <tt>true</tt> if this collection changed as a result of the * call * * @throws UnsupportedOperationException if the <tt>removeAll</tt> method * is not supported by this collection. * @throws ClassCastException if the types of one or more elements * in this collection are incompatible with the specified * collection (optional). * @throws NullPointerException if this collection contains one or more * null elements and the specified collection does not support * null elements (optional). * @throws NullPointerException if the specified collection is * <tt>null</tt>. * @see #remove(Object) * @see #contains(Object) * */ public final boolean removeAll(Collection c) { return list.removeAll(c); } /** Retains only the elements in this collection that are contained in the * specified collection (optional operation). In other words, removes from * this collection all of its elements that are not contained in the * specified collection. * * @param c elements to be retained in this collection. * @return <tt>true</tt> if this collection changed as a result of the * call * * @throws UnsupportedOperationException if the <tt>retainAll</tt> method * is not supported by this Collection. * @throws ClassCastException if the types of one or more elements * in this collection are incompatible with the specified * collection (optional). * @throws NullPointerException if this collection contains one or more * null elements and the specified collection does not support null * elements (optional). * @throws NullPointerException if the specified collection is * <tt>null</tt>. * @see #remove(Object) * @see #contains(Object) * */ public final boolean retainAll(Collection c) { return list.retainAll(c); } /** Replaces the element at the specified position in this list with the * specified element (optional operation). * * @param index index of element to replace. * @param element element to be stored at the specified position. * @return the element previously at the specified position. * * @throws UnsupportedOperationException if the <tt>set</tt> method is not * supported by this list. * @throws ClassCastException if the class of the specified element * prevents it from being added to this list. * @throws NullPointerException if the specified element is null and * this list does not support null elements. * @throws IllegalArgumentException if some aspect of the specified * element prevents it from being added to this list. * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index >= size()). * */ public final Object set(int index, Object element) { return list.set(index, element); } /** Returns the number of elements in this collection. If this collection * contains more than <tt>Integer.MAX_VALUE</tt> elements, returns * <tt>Integer.MAX_VALUE</tt>. * * @return the number of elements in this collection * */ public final int size() { return list.size(); } /** Returns a view of the portion of this list between the specified * <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive. (If * <tt>fromIndex</tt> and <tt>toIndex</tt> are equal, the returned list is * empty.) The returned list is backed by this list, so non-structural * changes in the returned list are reflected in this list, and vice-versa. * The returned list supports all of the optional list operations supported * by this list.<p> * * This method eliminates the need for explicit range operations (of * the sort that commonly exist for arrays). Any operation that expects * a list can be used as a range operation by passing a subList view * instead of a whole list. For example, the following idiom * removes a range of elements from a list: * <pre> * list.subList(from, to).clear(); * </pre> * Similar idioms may be constructed for <tt>indexOf</tt> and * <tt>lastIndexOf</tt>, and all of the algorithms in the * <tt>Collections</tt> class can be applied to a subList.<p> * * The semantics of the list returned by this method become undefined if * the backing list (i.e., this list) is <i>structurally modified</i> in * any way other than via the returned list. (Structural modifications are * those that change the size of this list, or otherwise perturb it in such * a fashion that iterations in progress may yield incorrect results.) * * @param fromIndex low endpoint (inclusive) of the subList. * @param toIndex high endpoint (exclusive) of the subList. * @return a view of the specified range within this list. * * @throws IndexOutOfBoundsException for an illegal endpoint index value * (fromIndex < 0 || toIndex > size || fromIndex > toIndex). * */ public final List subList(int fromIndex, int toIndex) { return list.subList(fromIndex, toIndex); } /** Returns an array containing all of the elements in this collection. If * the collection makes any guarantees as to what order its elements are * returned by its iterator, this method must return the elements in the * same order.<p> * * The returned array will be "safe" in that no references to it are * maintained by this collection. (In other words, this method must * allocate a new array even if this collection is backed by an array). * The caller is thus free to modify the returned array.<p> * * This method acts as bridge between array-based and collection-based * APIs. * * @return an array containing all of the elements in this collection * */ public final Object[] toArray() { return list.toArray(); } /** Returns an array containing all of the elements in this collection; * the runtime type of the returned array is that of the specified array. * If the collection fits in the specified array, it is returned therein. * Otherwise, a new array is allocated with the runtime type of the * specified array and the size of this collection.<p> * * If this collection fits in the specified array with room to spare * (i.e., the array has more elements than this collection), the element * in the array immediately following the end of the collection is set to * <tt>null</tt>. This is useful in determining the length of this * collection <i>only</i> if the caller knows that this collection does * not contain any <tt>null</tt> elements.)<p> * * If this collection makes any guarantees as to what order its elements * are returned by its iterator, this method must return the elements in * the same order.<p> * * Like the <tt>toArray</tt> method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs<p> * * Suppose <tt>l</tt> is a <tt>List</tt> known to contain only strings. * The following code can be used to dump the list into a newly allocated * array of <tt>String</tt>: * * <pre> * String[] x = (String[]) v.toArray(new String[0]); * </pre><p> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * * @param a the array into which the elements of this collection are to be * stored, if it is big enough; otherwise, a new array of the same * runtime type is allocated for this purpose. * @return an array containing the elements of this collection * * @throws ArrayStoreException the runtime type of the specified array is * not a supertype of the runtime type of every element in this * collection. * @throws NullPointerException if the specified array is <tt>null</tt>. * */ public final Object[] toArray(Object[] a) { return list.toArray(a); } // Data elements private ArrayList list; } --- NEW FILE: ParticipantListCellRenderer.java --- /* * ParticipantListCellRenderer.java * * Copyright (C) 2002, Ray Benjamin * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Created on November 24, 2002, 4:58 PM */ package org.wettp2p.combatmanager; import java.awt.*; import javax.swing.*; import org.wettp2p.creature.*; /** * This class prepares a panel that is used to display an entry in the * ParticipantList in the Combat Manager. * * This display component consists of an icon which displays general status * information about the combatent, a check box used to indicate if the * particular participant is involved in the current melee, and the name of * the participant. * * @author Ray Benjamin */ public class ParticipantListCellRenderer extends DefaultListCellRenderer implements ListCellRenderer { /** Creates a new instance of ParticipantListCellRenderer */ public ParticipantListCellRenderer() { //setLayout(new BorderLayout()); initComponents(); } /** * This method initializes the graphical components that display the * participant information. */ private void initComponents() { icon = new ImageIcon("sample.gif"); this.setIcon(icon); } /** Return a component that has been configured to display the specified * value. That component's <code>paint</code> method is then called to * "render" the cell. If it is necessary to compute the dimensions * of a list because the list cells do not h... [truncated message content] |
From: <zy...@us...> - 2002-12-11 20:07:53
|
Update of /cvsroot/wett-p2p/org/wettp2p/combatmanager/combatagent In directory sc8-pr-cvs1:/tmp/cvs-serv2850/combatagent Modified Files: CombatAgentMain.java Log Message: * Commiting Ray's current combat manager code * The initiative class can be used to keep initiative but is not yet added to the combat manager panal. (GUI) Index: CombatAgentMain.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/combatmanager/combatagent/CombatAgentMain.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** CombatAgentMain.java 10 Dec 2002 15:11:01 -0000 1.2 --- CombatAgentMain.java 11 Dec 2002 20:07:49 -0000 1.3 *************** *** 27,30 **** --- 27,33 ---- import java.io.*; import org.wettp2p.creature.*; + import org.wettp2p.combatmanager.*; + import java.util.Random; + /** *************** *** 39,42 **** --- 42,46 ---- public static void main(String[] args) { Creature orc = new Creature(); + orc.setName("Orgmr"); orc.setAbilityScores(15, 10, 11, 9, 8, 8); orc.setBaseAC(10); *************** *** 55,58 **** --- 59,63 ---- Creature orc2 = new Creature(); + orc2.setName("Grutmn"); orc2.setAbilityScores(15, 10, 11, 9, 8, 8); orc2.setBaseAC(10); *************** *** 65,76 **** orc2.addWeapon(greatAxe); ! orc.getWeapon(greatAxeIDX).getDamage().damage(orc2, 20); ! System.out.println("Orc hit Orc2 for 5 damage, Orc2 now has " + ! orc2.getCurHP() + " hp and is " + orc2.getHitPoints().healthStr()); } --- 70,113 ---- orc2.addWeapon(greatAxe); ! Creature drycon = new Creature(); ! drycon.setName("Drycon"); ! drycon.setAbilityScores(17, 18, 13, 13, 15, 12); ! drycon.setWisAsBonusToAC(); ! drycon.setBaseAC(10); ! drycon.setSaveBases(3, 3, 3); ! drycon.setSpeed(40); ! drycon.setHPfromTotal(24); ! drycon.setInitBaseModifier(0); ! drycon.setLevel(3); ! drycon.setOtherInfo("Monk"); ! drycon.setPlayerName("Heather"); ! Weapon fists = new Weapon(); ! fists.setCritical(2); ! fists.setDamage(new HitPointAdjuster()); ! fists.setDescription("Drycon's fists"); ! fists.setIsRanged(false); ! drycon.addWeapon(fists); + Initiative init = new Initiative(); + init.addParticipant(orc); + init.addParticipant(orc2); + init.addParticipant(drycon); + for(int i = 0; i < 5; i++){ + System.out.println("*** NEW INITIATIVE ROUND ***"); + + Participant partic; + init.newRound(); + while (init.hasMoreParticipants()){ + partic = init.getNextParticipant(); + System.out.println(partic.getCreature().getName() + + " (" + partic.getInitiative() + ")"); + } + } + + } |
From: <zy...@us...> - 2002-12-11 20:06:07
|
Update of /cvsroot/wett-p2p/org/wettp2p/creature In directory sc8-pr-cvs1:/tmp/cvs-serv2091 Modified Files: .nbattrs AbilityScoreTest.java AlignmentTest.java ArmorClassTest.java Creature.java CreatureSizeTest.java DieRollAdjTest.java HitPointAdjusterTest.java HitPointsTest.java StatTest.java Log Message: Moved more stuff around in Creature and CreatureBase. Index: .nbattrs =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/creature/.nbattrs,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** .nbattrs 10 Dec 2002 04:49:37 -0000 1.12 --- .nbattrs 11 Dec 2002 20:05:54 -0000 1.13 *************** *** 8,29 **** <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="SubdualAdjusterTest"/> </fileobject> ! <fileobject name="AbilityScore.java"> ! <attr name="class_dependency_org.wettp2p.creature.Stat" stringvalue="AbilityScore"/> </fileobject> <fileobject name="AbilityScoresTest.java"> <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="AbilityScoresTest"/> </fileobject> - <fileobject name="CreatureSuite.java"> - <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="CreatureSuite"/> - </fileobject> - <fileobject name="ArmorClass.java"> - <attr name="class_dependency_org.wettp2p.creature.Stat" stringvalue="ArmorClass"/> - </fileobject> - <fileobject name="HitPoints.java"> - <attr name="class_dependency_org.wettp2p.creature.Stat" stringvalue="HitPoints"/> - </fileobject> - <fileobject name="TemporaryHitPointAdjusterTest.java"> - <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="TemporaryHitPointAdjusterTest"/> - </fileobject> <fileobject name="AbilityScoreTest.java"> <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="AbilityScoreTest"/> --- 8,17 ---- <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="SubdualAdjusterTest"/> </fileobject> ! <fileobject name="AbilityScoresTestTest.java"> ! <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="SimpleNbJUnitTest"/> </fileobject> <fileobject name="AbilityScoresTest.java"> <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="AbilityScoresTest"/> </fileobject> <fileobject name="AbilityScoreTest.java"> <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="AbilityScoreTest"/> *************** *** 38,47 **** <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="HitPointsTest"/> </fileobject> <fileobject name="StatTest.java"> <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="StatTest"/> </fileobject> - <fileobject name="SubdualAdjuster.java"> - <attr name="class_dependency_org.wettp2p.creature.StatAdjuster" stringvalue="SubdualAdjuster"/> - </fileobject> <fileobject name="HitPointAdjusterTest.java"> <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="HitPointAdjusterTest"/> --- 26,35 ---- <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="HitPointsTest"/> </fileobject> + <fileobject name="AbilityScoreTestTest.java"> + <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="SimpleNbJUnitTest"/> + </fileobject> <fileobject name="StatTest.java"> <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="StatTest"/> </fileobject> <fileobject name="HitPointAdjusterTest.java"> <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="HitPointAdjusterTest"/> *************** *** 56,75 **** <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="SimpleNbJUnitTest"/> </fileobject> - <fileobject name="WeaponTest.java"> - <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="WeaponTest"/> - </fileobject> - <fileobject name="Alignment.java"> - <attr name="class_dependency_java.lang.Comparable" stringvalue="Alignment"/> - </fileobject> <fileobject name="DieRollAdj.java"> <attr name="EA-OpenIDE-Connection" serialvalue="aced0005737200146a6176612e7574696c2e4c696e6b65644c6973740c29535d4a608822030000787077040000000078"/> ! <attr name="class_dependency_org.wettp2p.creature.Stat" stringvalue="DieRollAdj"/> </fileobject> <fileobject name="CreatureSizeTest.java"> <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="CreatureSizeTest"/> </fileobject> - <fileobject name="HitPointAdjuster.java"> - <attr name="class_dependency_org.wettp2p.creature.StatAdjuster" stringvalue="HitPointAdjuster"/> - </fileobject> <fileobject name="SavesTest.java"> <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="SavesTest"/> --- 44,56 ---- <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="SimpleNbJUnitTest"/> </fileobject> <fileobject name="DieRollAdj.java"> <attr name="EA-OpenIDE-Connection" serialvalue="aced0005737200146a6176612e7574696c2e4c696e6b65644c6973740c29535d4a608822030000787077040000000078"/> ! </fileobject> ! <fileobject name="SavesTestTest.java"> ! <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="SimpleNbJUnitTest"/> </fileobject> <fileobject name="CreatureSizeTest.java"> <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="CreatureSizeTest"/> </fileobject> <fileobject name="SavesTest.java"> <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="SavesTest"/> *************** *** 83,92 **** <fileobject name="DieRollAdjTest.java"> <attr name="class_dependency_org.netbeans.junit.NbTestCase" stringvalue="DieRollAdjTest"/> - </fileobject> - <fileobject name="TemporaryHitPointAdjuster.java"> - <attr name="class_dependency_org.wettp2p.creature.StatAdjuster" stringvalue="TemporaryHitPointAdjuster"/> - </fileobject> - <fileobject name="CreatureSize.java"> - <attr name="class_dependency_java.lang.Comparable" stringvalue="CreatureSize"/> </fileobject> </attributes> --- 64,67 ---- Index: AbilityScoreTest.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/creature/AbilityScoreTest.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** AbilityScoreTest.java 10 Dec 2002 04:49:37 -0000 1.6 --- AbilityScoreTest.java 11 Dec 2002 20:05:55 -0000 1.7 *************** *** 48,60 **** } - /** The Suite. - * @return Returns the Test Suite. - */ - public static Test suite() { - TestSuite suite = new NbTestSuite(AbilityScoreTest.class); - - return suite; - } - /** Test of getModifier method, of class org.wettp2p.creature.AbilityScore. */ --- 48,51 ---- *************** *** 107,109 **** --- 98,107 ---- fail("Ability Score Mod: " + as.getModifier() + " but should be 5"); } + + public static Test suite() { + TestSuite suite = new NbTestSuite(AbilityScoreTest.class); + + return suite; + } + } Index: AlignmentTest.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/creature/AlignmentTest.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** AlignmentTest.java 9 Dec 2002 20:13:33 -0000 1.4 --- AlignmentTest.java 11 Dec 2002 20:05:55 -0000 1.5 *************** *** 212,222 **** } - /** Test suite for class <CODE>Alignment</CODE>. - * @return Returns the test suite. - */ public static Test suite() { TestSuite suite = new NbTestSuite(AlignmentTest.class); return suite; ! } } --- 212,222 ---- } public static Test suite() { TestSuite suite = new NbTestSuite(AlignmentTest.class); return suite; ! } ! ! ! } Index: ArmorClassTest.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/creature/ArmorClassTest.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** ArmorClassTest.java 10 Dec 2002 04:49:37 -0000 1.4 --- ArmorClassTest.java 11 Dec 2002 20:05:55 -0000 1.5 *************** *** 48,60 **** } - /** Test - * @return Test - */ - public static Test suite() { - TestSuite suite = new NbTestSuite(ArmorClassTest.class); - - return suite; - } - /** Test the default values of the class org.wettp2p.creature.ArmorClass. */ public void testDefaults() { --- 48,51 ---- *************** *** 125,128 **** --- 116,125 ---- } + public static Test suite() { + TestSuite suite = new NbTestSuite(ArmorClassTest.class); + + return suite; + } + } Index: Creature.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/creature/Creature.java,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** Creature.java 10 Dec 2002 04:49:37 -0000 1.10 --- Creature.java 11 Dec 2002 20:05:55 -0000 1.11 *************** *** 134,137 **** --- 134,163 ---- } + /** Set the name of the creature. + * @param cName The creature's name. + */ + public void setCreatureName(String cName){ + super.myName = cName; + } + /** Get the creature's name. + * @return The creature's name. + */ + public String getCreatureName(){ + return super.myName; + } + + /** Set the player's name. + * @param pName The player's name. + */ + public void setPlayerName(String pName){ + super.myPlayerName = pName; + } + /** Get the player's name. + * @return The player's name. + */ + public String getPlayerName(){ + return super.myPlayerName; + } + /** Set the creature's total hit points. * @param HP Total hit points. *************** *** 146,149 **** --- 172,191 ---- return super.getHitPoints().getCurrent(); } + /** Get the HP status. + * + * The constats are found in the class org.wettp2p.HitPoints. + * The values are: NORMAL, STAGGERED, DIABLED, UNCONSCIOUS, DYING and DEAD. + * @return Hit point status. + */ + public int getHPStatus(){ + return super.getHitPoints().health(); + } + /** The string representing the creature's hit point status, such as "Dead" or + * "Dying". + * @return The creature's hit point status in a string. + */ + public String getHPStatusStr(){ + return super.getHitPoints().healthStr(); + } /** Set the creature's bonus to armor class from armor. *************** *** 171,174 **** --- 213,219 ---- super.getAC().setBaseStat(baseAC); } + public void setWisAsBonusToAC(){ + super.getAC().setAltDep(super.getAbilityScores().getWis()); + } /** Get the current adjusted armor class for the creature. * @return Current adjusted Armor Class. *************** *** 177,180 **** --- 222,232 ---- return super.getAC().getAC(); } + /** Get the creature's flatfooted AC, which is the creature's AC without the + * dexterity modifier. + * @return Flatfooted AC. + */ + public int getFlatFootedAC(){ + return super.getAC().getFlatFootedAC(); + } /** Set the base saving throws of all three saving throws. *************** *** 271,277 **** public Weapon getFavoredMeleeWeapon(){ if(myFavoredMeleeIdx != -1){ ! return super.getWeapon( myFavoredMeleeIdx ); } else { ! List weapons = super.getWeapons(); for(int i = weapons.size(); i >= 0; i--){ if(((Weapon)weapons.get(i)).IsMelee()) --- 323,329 ---- public Weapon getFavoredMeleeWeapon(){ if(myFavoredMeleeIdx != -1){ ! return getWeapon( myFavoredMeleeIdx ); } else { ! List weapons = getWeapons(); for(int i = weapons.size(); i >= 0; i--){ if(((Weapon)weapons.get(i)).IsMelee()) *************** *** 289,295 **** public Weapon getFavoredRangedWeapon(){ if(myFavoredMeleeIdx != -1){ ! return super.getWeapon( myFavoredRangedIdx ); } else { ! List weapons = super.getWeapons(); for(int i = weapons.size(); i >= 0; i--){ if(((Weapon)weapons.get(i)).IsRanged()) --- 341,347 ---- public Weapon getFavoredRangedWeapon(){ if(myFavoredMeleeIdx != -1){ ! return getWeapon( myFavoredRangedIdx ); } else { ! List weapons = getWeapons(); for(int i = weapons.size(); i >= 0; i--){ if(((Weapon)weapons.get(i)).IsRanged()) *************** *** 329,331 **** --- 381,488 ---- } + /** Sets the name of the creature + * @param Name Name of Creature. + */ + public void setName( String Name ) { + super.myName = Name; + } + /** Sets the class of the creature + * @param CreatureClass Creature Class. + */ + public void setCreatureClass( String CreatureClass ) { + super.myCreatureClass = CreatureClass; + } + /** Sets the race of the creature + * @param Race Creature race, such as "Elf" or "Owl Bear". + */ + public void setRace( String Race ) { + super.myRace = Race; + } + /** Sets the string of other details about the creature + * @param OtherInfo Other information about the creature that doesn't fit anywhere else. + */ + public void setOtherInfo( String OtherInfo ) { + super.myOtherInfo = OtherInfo; + } + /** Sets the creature's size. + * Use the constants in Creature Size for the size value. + * @param critterSize CreatureSize constant. + */ + public void setCreatureSize( int critterSize ) { + super.mySize.setSize( critterSize ); + } + /** Sets the creature's size object + * @param critterSize CreatureSize object. + */ + public void setCreatureSize( CreatureSize critterSize ) { + super.mySize = critterSize; + } + /** Set the creature's speed in feet. (Per round) + * @param speed Speed, in feet. + */ + public void setSpeed( int speed ) { + super.mySpeed = speed; + } + + /** Name of Creature. + * @return Returns the name of the creature. + */ + public String getName() { + return super.myName; + } + /** Creature's Class, such as "Sorcerer" or "Beast". + * @return Returns the class of the creature. + */ + public String getCreatureClass() { + return super.myCreatureClass; + } + /** Race of a creature, such as "Elf" or "Dragon". + * @return Returns the race of the creature. + */ + public String getRace() { + return super.myRace; + } + /** Misc details. + * @return Returns the string of other details about the creature. + */ + public String getOtherInfo() { + return super.myOtherInfo; + } + /** Get the speed that the creature can move in a round. (In Feet) + * @return The creature's speed in feet. + */ + public int getSpeed() { + return super.mySpeed; + } + + /** Get all of the weapons that the creature is carrying. + * @return A List of Weapon objects. + */ + public List getWeapons() { + return super.myWeapons; + } + /** Get a particular weapon. + * @param idx The weapon's index in the List. + * @return A Weapon object. + */ + public Weapon getWeapon(int idx) { + return (Weapon)super.myWeapons.get(idx); + } + /** Add a Weapon object to the List of weapons this creature is carrying. + * @param weap A Weapon object. + * @return The index of the weapon you just added. + */ + public int addWeapon(Weapon weap) { + super.myWeapons.add(weap); + return super.myWeapons.indexOf(weap); + } + + public int getInitModifier(){ + return super.getInitiative().getCurrent(); + } + + public void setInitBaseModifier(int baseInitiative){ + super.getInitiative().setBaseStat(baseInitiative); + } + } Index: CreatureSizeTest.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/creature/CreatureSizeTest.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** CreatureSizeTest.java 9 Dec 2002 20:13:33 -0000 1.4 --- CreatureSizeTest.java 11 Dec 2002 20:05:55 -0000 1.5 *************** *** 49,61 **** } - /** Test <CODE>CreatureSize</CODE>. - * @return Test suite. - */ - public static Test suite() { - TestSuite suite = new NbTestSuite(CreatureSizeTest.class); - - return suite; - } - /** Test default values of class org.wettp2p.creature.CreatureSize. */ public void testDefaults(){ --- 49,52 ---- *************** *** 160,162 **** --- 151,160 ---- fail("Set Size did not set the creature's size properly."); } + + public static Test suite() { + TestSuite suite = new NbTestSuite(CreatureSizeTest.class); + + return suite; + } + } Index: DieRollAdjTest.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/creature/DieRollAdjTest.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** DieRollAdjTest.java 9 Dec 2002 20:13:33 -0000 1.3 --- DieRollAdjTest.java 11 Dec 2002 20:05:55 -0000 1.4 *************** *** 48,60 **** } - /** Test <CODE>DieRollAdj</CODE>. - * @return The test suite. - */ - public static Test suite() { - TestSuite suite = new NbTestSuite(DieRollAdjTest.class); - - return suite; - } - /** Test default values of class org.wettp2p.creature.DieRollAdj. */ public void testDefaults(){ --- 48,51 ---- *************** *** 110,113 **** --- 101,111 ---- } + + public static Test suite() { + TestSuite suite = new NbTestSuite(DieRollAdjTest.class); + + return suite; + } + } Index: HitPointAdjusterTest.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/creature/HitPointAdjusterTest.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** HitPointAdjusterTest.java 9 Dec 2002 20:13:33 -0000 1.3 --- HitPointAdjusterTest.java 11 Dec 2002 20:05:55 -0000 1.4 *************** *** 48,60 **** } - /** Test. - * @return Test. - */ - public static Test suite() { - TestSuite suite = new NbTestSuite(HitPointAdjusterTest.class); - - return suite; - } - /** Test of inflict method, of class org.wettp2p.creature.HitPointAdjuster. */ public void testDamage() { --- 48,51 ---- *************** *** 126,129 **** --- 117,125 ---- } + public static Test suite() { + TestSuite suite = new NbTestSuite(HitPointAdjusterTest.class); + + return suite; + } } Index: HitPointsTest.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/creature/HitPointsTest.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** HitPointsTest.java 9 Dec 2002 20:13:33 -0000 1.5 --- HitPointsTest.java 11 Dec 2002 20:05:55 -0000 1.6 *************** *** 48,60 **** } - /** Test - * @return Test - */ - public static Test suite() { - TestSuite suite = new NbTestSuite(HitPointsTest.class); - - return suite; - } - /** Test default values of class org.wettp2p.creature.HitPoints. */ public void testDefaultBaseHP(){ --- 48,51 ---- *************** *** 226,229 **** --- 217,227 ---- } + public static Test suite() { + TestSuite suite = new NbTestSuite(HitPointsTest.class); + + return suite; + } + + } Index: StatTest.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/creature/StatTest.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** StatTest.java 9 Dec 2002 20:13:33 -0000 1.5 --- StatTest.java 11 Dec 2002 20:05:55 -0000 1.6 *************** *** 48,60 **** } - /** Test the <CODE>Stat</CODE> class. - * @return Test suite. - */ - public static Test suite() { - TestSuite suite = new NbTestSuite(StatTest.class); - - return suite; - } - /** Test the default values of the class org.wettp2p.creature.Stat. */ public void testDefaults() { --- 48,51 ---- *************** *** 113,116 **** } ! } --- 104,112 ---- } ! public static Test suite() { ! TestSuite suite = new NbTestSuite(StatTest.class); ! ! return suite; ! } ! } |
From: <rb...@us...> - 2002-12-11 04:29:32
|
Update of /cvsroot/wett-p2p/org/wettp2p/communicationslayer In directory sc8-pr-cvs1:/tmp/cvs-serv25492 Modified Files: CommunicationsHandler.java Log Message: Changed the logic used to join the WETT peer group so that the application will join the group if it already exists or create the group if it doesn't. Index: CommunicationsHandler.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/communicationslayer/CommunicationsHandler.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** CommunicationsHandler.java 10 Dec 2002 21:21:16 -0000 1.2 --- CommunicationsHandler.java 11 Dec 2002 04:28:59 -0000 1.3 *************** *** 53,56 **** --- 53,59 ---- import net.jxta.id.IDFactory; + import java.io.IOException; + import java.net.*; + import java.util.*; import org.wettp2p.peer.*; import java.util.logging.*; *************** *** 77,80 **** --- 80,91 ---- * @author Robert Wei * @version 0.3, 2002/11/21 + * + * $Author$ + * $Date$ + * $Name$ + * $Locker$ + * $Revision$ + * $State$ + * */ public class CommunicationsHandler implements MessageConsumer, MessageProducer { *************** *** 83,93 **** --- 94,111 ---- static Logger logger = Logger.getLogger(Peer.TOP_LOG_NAME + ".communicationshandler"); + private static final int DEFAULT_RETRY_COUNT = 3; + private static String classStr = "CommunicationsHandler"; // The globally unique ID for the WETT peergroup (generated on 11/21/2002 by Robert Wei) private final String WETT_GID = "urn:jxta:uuid-ECFFFA4E82E348AF9043A8A0844FE5CB02"; + private static final String WETT_GROUP_NAME = "WETT"; + private static final String WETT_GROUP_DESCRIPTION = "Web Enabled Table Top - Peer-to-Peer"; + private static final int TIMEOUT = 3000; private PeerGroup netPeerGroup; private PeerGroup wettPeerGroup; + private DiscoveryService wettDiscoveryService; + private PipeService wettPipeService; public static void main(String args[]) { *************** *** 104,108 **** logger.entering(classStr, "initialize"); startJXTA(); ! createWettGroup(); } --- 122,137 ---- logger.entering(classStr, "initialize"); startJXTA(); ! // try to find the WettGroup ! // if it can't be found, create it ! try { ! joinWettGroup(); ! } ! catch (Exception e) { ! String str = "ERROR: Unable to join or create Wett peergroup."; ! logger.severe(str); ! System.err.println(str); ! System.exit(1); // fail ! } ! // Join the Wett group. } *************** *** 113,126 **** logger.entering(classStr, "startJXTA"); try { ! System.out.println("Attempting to initialize JXTA"); netPeerGroup = PeerGroupFactory.newNetPeerGroup(); ! System.out.println("JXTA started"); ! System.out.println("Joined Peergroup: " + netPeerGroup.getPeerGroupName()); } catch (Exception e) { // Failed to initialize JXTA, print error message and quit. ! System.out.print("JXTA initialization failed due to exception: "); ! System.out.println(e); e.printStackTrace(); System.exit(1); } --- 142,160 ---- logger.entering(classStr, "startJXTA"); try { ! logger.fine("Attempting to initialize JXTA"); netPeerGroup = PeerGroupFactory.newNetPeerGroup(); ! logger.fine("JXTA started"); ! logger.fine("Joined Peergroup: " + netPeerGroup.getPeerGroupName()); } catch (Exception e) { // Failed to initialize JXTA, print error message and quit. ! String str = "Error: JXTA initialization failed due to exception: "; ! logger.severe(str); ! System.err.println(str); ! logger.severe(e.toString()); ! System.err.println(e.toString()); e.printStackTrace(); + // NOTE: should find someway to insure that stacktrace is written into + // log... System.exit(1); } *************** *** 128,131 **** --- 162,273 ---- /** + * Joins the WettGroup if it exists and creates and joins the group if it + * does not exist. + */ + private void joinWettGroup() throws Exception { + logger.entering(classStr, "joinWettGroup"); + int count = DEFAULT_RETRY_COUNT; + logger.info("Attempting to Discover the WettGroup."); + + // get the discovery service. + DiscoveryService discoveryService = netPeerGroup.getDiscoveryService(); + Enumeration ae = null; // holds discovered peers + + // Loop until we discover WettGroup or until we've exhausted the + // desired number of attempts + while(count-- > 0) { + try { + // Search first in the peer's local cache to find + // the Wett peergroup advertisement + ae = discoveryService.getLocalAdvertisements( + DiscoveryService.GROUP, "Name", WETT_GROUP_NAME); + + // If we found the advetisement, we are done + if ((ae != null) && ae.hasMoreElements()) + break; + + // If we did not find it, we send a discovery request + discoveryService.getRemoteAdvertisements(null, + DiscoveryService.GROUP, "Name", WETT_GROUP_NAME, 1, null); + + // Sleep to allow time for peers to respond to the discovery + // request. + try { + Thread.sleep(TIMEOUT); + } + catch (InterruptedException ie) { + // do nothing + } + } + catch (IOException e) { + // found nothing + } + } // end while + + PeerGroupAdvertisement wettGroupAdv = null; + + // See if we found the Wett Group advertisement. If we didn't, + // then either we are the first peer to join or no other peers are up. + // In either case, we must create the group. + + if (ae == null || !ae.hasMoreElements()) { + logger.info("Could not find the Wett peergroup; creating one"); + + try { + + // create a new, all-purpose peergroup + ModuleImplAdvertisement implAdv = + netPeerGroup.getAllPurposePeerGroupImplAdvertisement(); + + wettPeerGroup = netPeerGroup.newGroup(mkGroupID(), + implAdv, + WETT_GROUP_NAME, + WETT_GROUP_DESCRIPTION); + + // Get the peer group advertisement + wettGroupAdv = netPeerGroup.getPeerGroupAdvertisement(); + } + catch (Exception e) { + String str = "Error in creating WETT peergroup."; + logger.severe(str); + System.err.println(str); + throw e; + } + } + else { + // we found the advertisement in the cache; + // We can join the existing wettPeerGroup. + + try { + wettGroupAdv = (PeerGroupAdvertisement) ae.nextElement(); + wettPeerGroup = netPeerGroup.newGroup(wettGroupAdv); + logger.info("Found the WETT Peer Group advertisement; " + + "joined the existing group."); + } + catch (Exception e) { + String str = "Error in creating Wett peergroup " + + "from existing advertisement."; + logger.severe(str); + System.err.println(str); + throw e; + } + } // end if (wett group adv found) + + try { + // get the diescvoer and pipe services for the Wett peergroup + wettDiscoveryService = wettPeerGroup.getDiscoveryService(); + wettPipeService = wettPeerGroup.getPipeService(); + } + catch (Exception e) { + String str = "Error getting services from Wett peergroup"; + logger.severe(str); + System.err.println(str); + throw e; + } + + logger.info("Web Enabled Table Top - Peer-to-Peer is on-line!"); + } // end joinWettGroup() + + /** * Creates and joins the WettPeerGroup. */ *************** *** 135,139 **** PeerGroupAdvertisement adv = null; ! System.out.println("Attempting to create the WETT peergroup"); try { --- 277,281 ---- PeerGroupAdvertisement adv = null; ! logger.info("Attempting to create the WETT peergroup"); try { *************** *** 147,154 **** adv = wettPeerGroup.getPeerGroupAdvertisement(); ! System.out.println("WETT peergroup successfully created"); } catch (Exception e) { ! System.out.println("Failed to create the WETT group: " + e); e.printStackTrace(); System.exit(1); --- 289,298 ---- adv = wettPeerGroup.getPeerGroupAdvertisement(); ! logger.info("WETT peergroup successfully created"); } catch (Exception e) { ! String str = "Failed to create the WETT group: " + e; ! logger.severe(str); ! System.err.println(str); e.printStackTrace(); System.exit(1); *************** *** 160,167 **** disco.remotePublish(adv, DiscoveryService.GROUP); ! System.out.println("WETT peergroup successfully published"); } catch (Exception ee) { ! System.out.println("Failed to publish the WETT group: " + ee); ee.printStackTrace(); System.exit(1); --- 304,313 ---- disco.remotePublish(adv, DiscoveryService.GROUP); ! logger.info("WETT peergroup successfully published"); } catch (Exception ee) { ! String str = "Failed to publish the WETT group: " + ee; ! logger.severe(str); ! System.err.println(str); ee.printStackTrace(); System.exit(1); *************** *** 169,172 **** --- 315,323 ---- } + private PeerGroupID mkGroupID() throws Exception { + return (PeerGroupID) IDFactory.fromURL( + new URL("urn", "", WETT_GID)); + } + public void subscribe(Class type) { logger.entering(classStr,"subscribe", type); *************** *** 236,238 **** --- 387,390 ---- { } + } |
From: <rb...@us...> - 2002-12-10 21:21:19
|
Update of /cvsroot/wett-p2p/org/wettp2p/communicationslayer In directory sc8-pr-cvs1:/tmp/cvs-serv16607 Modified Files: CommunicationsHandler.java Log Message: I added some logging code to CommunicationsHandler and an initialize method which is called by Peer to initialize the module. Index: CommunicationsHandler.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/communicationslayer/CommunicationsHandler.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** CommunicationsHandler.java 21 Nov 2002 19:27:20 -0000 1.1 --- CommunicationsHandler.java 10 Dec 2002 21:21:16 -0000 1.2 *************** *** 2,5 **** --- 2,8 ---- * CommunicationsHandler.java * + * This module handles communications between the MessageHandler and the JXTA + * network and all other peers. + * * Phase 1 goals: * 1 (Done) - Initialize JXTA / join peergroup: netpeer *************** *** 9,12 **** --- 12,17 ---- * 5 - Send messages to every member of the peergroup * 6 - Expose an input pipe to recieve messages from the peergroup + * 8 - (Done - rben) Add Initialization method to be used in initializing + * communications. */ *************** *** 48,55 **** import net.jxta.id.IDFactory; /** * CommunicationsHandler class. Manages and controls network traffic. * ! * Copyright (C) 2002, Paulo Mouat * * This program is free software; you can redistribute it and/or --- 53,63 ---- import net.jxta.id.IDFactory; + import org.wettp2p.peer.*; + import java.util.logging.*; + /** * CommunicationsHandler class. Manages and controls network traffic. * ! * Copyright (C) 2002, Robert Wei, Ray Benjamin * * This program is free software; you can redistribute it and/or *************** *** 72,75 **** --- 80,88 ---- public class CommunicationsHandler implements MessageConsumer, MessageProducer { + /* Logger */ + static Logger logger = Logger.getLogger(Peer.TOP_LOG_NAME + ".communicationshandler"); + + private static String classStr = "CommunicationsHandler"; + // The globally unique ID for the WETT peergroup (generated on 11/21/2002 by Robert Wei) private final String WETT_GID = "urn:jxta:uuid-ECFFFA4E82E348AF9043A8A0844FE5CB02"; *************** *** 85,91 **** --- 98,115 ---- /** + * This routine performs initialization of the communications interface. + * + */ + public void initialize() { + logger.entering(classStr, "initialize"); + startJXTA(); + createWettGroup(); + } + + /** * Initializes the JXTA platform and joins the default netPeer group. **/ private void startJXTA() { + logger.entering(classStr, "startJXTA"); try { System.out.println("Attempting to initialize JXTA"); *************** *** 107,110 **** --- 131,135 ---- */ private void createWettGroup() { + logger.entering(classStr,"createWettGroup"); PeerGroupAdvertisement adv = null; *************** *** 145,171 **** public void subscribe(Class type) { } public void subscribe(String producerName) { } private void createTransmitter(OutputPipe pipe, Message message) { } private void createReceiver(InputPipe pipe) { } ! /** Receives the passed <code>Message</code>. * @param message the <code>Message</code> to be received. * */ public void receive(Message message) { } ! /** Sends the passed <code>Message</code>. * @param message the <code>Message</code> to be sent. * */ public void send(Message message) { } --- 170,214 ---- public void subscribe(Class type) { + logger.entering(classStr,"subscribe", type); } public void subscribe(String producerName) { + logger.entering(classStr,"subscribe", producerName); } private void createTransmitter(OutputPipe pipe, Message message) { + logger.entering(classStr,"createTransmitter"); } private void createReceiver(InputPipe pipe) { + logger.entering(classStr,"createReceiver", pipe); } ! /** ! * Receives the passed <code>Message</code> from the MessageHandler, ! * the module that handles communications within the Wett-p2p ! * application. ! * ! * There should be two types of messages we are concerned with: messages ! * bound for other peers and messages that are commands to the ! * CommunicationsHander. ! * * @param message the <code>Message</code> to be received. * */ public void receive(Message message) { + logger.entering(classStr,"receive", message); } ! /** ! * Sends the passed <code>Message</code> to the MessageHandler which ! * sends the message to it's appropriate destination based on the class ! * of the message. ! * * @param message the <code>Message</code> to be sent. * */ public void send(Message message) { + logger.entering(classStr,"send", message); } |
From: <rb...@us...> - 2002-12-10 21:19:58
|
Update of /cvsroot/wett-p2p/org/wettp2p/peer In directory sc8-pr-cvs1:/tmp/cvs-serv16032 Modified Files: Peer.java Log Message: Integrated the current version of the Communications Layer into Peer so that the peer now instantiates and initializes the CommunicationsHandler. Index: Peer.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/peer/Peer.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Peer.java 12 Nov 2002 19:04:39 -0000 1.3 --- Peer.java 10 Dec 2002 21:19:55 -0000 1.4 *************** *** 40,43 **** --- 40,44 ---- import org.wettp2p.messagehandler.*; + import org.wettp2p.communicationslayer.*; /** Peer - This class is the class that will start the Wett-p2p application. *************** *** 48,52 **** /* Constants */ ! private static final String releaseNumber = "0.1.0"; private static final String releaseName = "Hatchling"; --- 49,53 ---- /* Constants */ ! private static final String releaseNumber = "0.1.1"; private static final String releaseName = "Hatchling"; *************** *** 80,83 **** --- 81,86 ---- // logger.fine("Starting CommunicationsLayer"); + communicationsHandler = CommunicationsHandler.getInstance(); + communicationsHandler.initialize(); // // Start DataManager *************** *** 359,362 **** --- 362,366 ---- private static String logFileName = null; private MessageHandler messageHandler = null; + private CommunicationsHandler communicationsHandler = null; /* private CommunicationsLayer communicationsLayer = null; |
From: <zy...@us...> - 2002-12-10 15:11:06
|
Update of /cvsroot/wett-p2p/org/wettp2p/combatmanager/combatagent In directory sc8-pr-cvs1:/tmp/cvs-serv24506 Modified Files: CombatAgentMain.java Log Message: Test to see if stuff is working Index: CombatAgentMain.java =================================================================== RCS file: /cvsroot/wett-p2p/org/wettp2p/combatmanager/combatagent/CombatAgentMain.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** CombatAgentMain.java 10 Dec 2002 04:51:42 -0000 1.1 --- CombatAgentMain.java 10 Dec 2002 15:11:01 -0000 1.2 *************** *** 47,63 **** orc.setHitDice(1); orc.setCurHP(4); ! System.out.println("Str: " + orc.getStr()); ! System.out.println("Dex: " + orc.getDex()); ! System.out.println("Con: " + orc.getCon()); ! System.out.println("Int: " + orc.getInt()); ! System.out.println("Wis: " + orc.getWis()); ! System.out.println("Cha: " + orc.getCha()); ! System.out.println("AC: " + orc.getCurAC()); ! System.out.println("Fort Save: " + orc.getFort()); ! System.out.println(" Ref Save: " + orc.getRef()); ! System.out.println("Will Save: " + orc.getWill()); ! System.out.println("Speed: " + orc.getSpeed()); ! System.out.println("Hit Points: " + orc.getCurHP()); --- 47,75 ---- orc.setHitDice(1); orc.setCurHP(4); + Weapon greatAxe = new Weapon(); + StatAdjuster sa = new HitPointAdjuster(); + greatAxe.setDamage(sa); + greatAxe.setDescription("Great Axe"); + greatAxe.setDamageDice("1d12+3"); + int greatAxeIDX = orc.addWeapon(greatAxe); ! Creature orc2 = new Creature(); ! orc2.setAbilityScores(15, 10, 11, 9, 8, 8); ! orc2.setBaseAC(10); ! orc2.setArmorAC(4); ! orc2.setDexCap(3); ! orc2.setSaveBasesFromTotal(2, 0, -1); ! orc2.setSpeed(20); ! orc2.setHitDice(1); ! orc2.setCurHP(4); ! orc2.addWeapon(greatAxe); ! ! orc.getWeapon(greatAxeIDX).getDamage().damage(orc2, 20); ! ! System.out.println("Orc hit Orc2 for 5 damage, Orc2 now has " + ! orc2.getCurHP() + " hp and is " + orc2.getHitPoints().healthStr()); ! ! ! |
From: <zy...@us...> - 2002-12-10 04:51:46
|
Update of /cvsroot/wett-p2p/org/wettp2p/combatmanager/combatagent In directory sc8-pr-cvs1:/tmp/cvs-serv14074 Added Files: CombatAgentMain.java Log Message: * Added the folder where the inteligent agent will live. * Added the main class which will be used for testing / playing with the agent once it is acctually written enough to test / play with. --- NEW FILE: CombatAgentMain.java --- /* Copyright (C) 2002 Heather Cousineau This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * CombatAgentMain.java * * Created on December 9, 2002, 5:01 PM */ package org.wettp2p.combatmanager.combatagent; import java.io.*; import org.wettp2p.creature.*; /** * * @author Zyrca */ public class CombatAgentMain { /** * @param args the command line arguments */ public static void main(String[] args) { Creature orc = new Creature(); orc.setAbilityScores(15, 10, 11, 9, 8, 8); orc.setBaseAC(10); orc.setArmorAC(4); orc.setDexCap(3); orc.setSaveBasesFromTotal(2, 0, -1); orc.setSpeed(20); orc.setHitDice(1); orc.setCurHP(4); System.out.println("Str: " + orc.getStr()); System.out.println("Dex: " + orc.getDex()); System.out.println("Con: " + orc.getCon()); System.out.println("Int: " + orc.getInt()); System.out.println("Wis: " + orc.getWis()); System.out.println("Cha: " + orc.getCha()); System.out.println("AC: " + orc.getCurAC()); System.out.println("Fort Save: " + orc.getFort()); System.out.println(" Ref Save: " + orc.getRef()); System.out.println("Will Save: " + orc.getWill()); System.out.println("Speed: " + orc.getSpeed()); System.out.println("Hit Points: " + orc.getCurHP()); } private static String askQuestion(String q){ System.out.print(q + " "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String a = null; try { a = br.readLine(); } catch (IOException ioe) { System.out.println("IO error: " + ioe.getMessage()); System.exit(1); } return a; } } |