Writing a battlefield simulation; except I'm the one fighting here ;-)

Hi, all:
I'm having a problem getting my Soldier class to find instances of each other (NPEs) and change aspects of each other. This is an agent-based model in which I generate multiple Soldier objects. The soldiers win or lose based on their strength as compared to the other soldier they are fighting in any given step (round of the battle). Their strength is increased if they have other soldiers of their own team (meaning their own color, green, blue, whatever) as their neighbor. If they see a neighbor of the opposing color team in their Moore neighborhood (like a tic-tac-toe board where the soldier is in the middle square and "sees" the eight squares around him), they fight him, and kill him if their strength is greater, and die if their strength is lesser.
Here's the problem: have I screwed up the communication between soldiers? Why is there an NPE when I'm asking about the other soldier's color? The NPE error is, obviously, because one is pointing at a null object. However, I included that debug message about the other soldier's color and ID to see if it was finding a color and ID, and it does (see the stack trace below), so where am I going wrong?
public Soldier () {
          ID = nextID++;
          x = 0;
          y = 0;
          myColor = Color.magenta;
          myBorder = Color.black;
          strength = Normal.staticNextDouble(50.00, 23.75);
          if (strength >= 100 ){
               strength = 100;
          if (strength <= 0 ) {
               strength = 0;
     public void step () {
          getMyNeighbor();
          move();
     public void getMyNeighbor () {
          neighborList = new Vector();
          soldierNeighbors = new Vector();
          neighborList = world.getMooreNeighbors(x, y, false);
          int random = Random.uniform.nextIntFromTo(0, 99);
          for (int i = 0; i < neighborList.size(); i++){
               Object o = neighborList.get (i);
               if (o instanceof Soldier) {
                    Soldier otherSoldier = (Soldier)o;
                    otherSoldier.getID();
                    otherSoldier.getMyColor();
                    System.out.println ("The other soldier's color is " +
                              otherSoldier.getMyColor() + " and his ID is " + otherSoldier.getID() );
                    otherSoldier.getStrength();
               if (otherSoldier.getMyColor() == this.getMyColor()){//NPE here
                    strength = strength + 1;
               if (otherSoldier.getMyColor()!= this.getMyColor()){
                    fight();
     public void fight () {
          if (strength > otherSoldierStrength){
               otherSoldier.setMyColor(Color.red);//another problem here
          if (strength < otherSoldierStrength){
                        Model.soldierList.remove(this);
     public void draw (SimGraphics g) {
          g.drawFastRoundRect(myColor);
          g.drawRectBorder(new BasicStroke(2), myBorder);
     public double getStrength() { return strength; }
     public void setStrength( double i ) { strength = i; }
     public Color getMyColor() { return myColor; }
     public void setMyColor( Color i ) { myColor = i; }
     public Color getMyBorder() { return myBorder; }
     public void setMyBorder( Color i ) { myBorder = i; }
     public static void setModel( Model m ) { model = m; }
     public static void setWorld( Object2DGrid world ) {     Soldier.world = world;}Here's the stack trace:
Model.main() beginning...
Model.setup() beginning...
Model.setup() finished.
Model.main() finished...
Model.begin() beginning...
Model.buildModel() beginning.
creating people now
Model.buildModel() finished.
Model.buildDisplay() beginning.
Model.buildDisplay() finished.
Model.buildSchedule() beginning
Model.buildSchedule() finished
Model.begin() finished...
Exception in thread "Thread-4" java.lang.NullPointerException
     at tyranny.Soldier.getMyNeighbor(Soldier.java:71)
     at tyranny.Soldier.step(Soldier.java:52)
     at tyranny.Model.step(Model.java:145)
     at BAB_SYNTH_1.execute(Unknown Source)
     at uchicago.src.sim.engine.ScheduleGroup.execute(Unknown Source)
     at uchicago.src.sim.engine.RandomScheduleGroup.execute(Unknown Source)
     at uchicago.src.sim.engine.Schedule.execute(Unknown Source)
     at uchicago.src.sim.engine.BaseController$1.run(Unknown Source)
     at java.lang.Thread.run(Unknown Source)
==> Model step 1.0
The other soldier's color is java.awt.Color[r=0,g=255,b=0] and his ID is 924

CeciNEstPasUnProgrammeur wrote:
if (o instanceof Soldier) {
Soldier otherSoldier = (Soldier)o;
if (otherSoldier.getMyColor() == this.getMyColor()){//NPE hereThis really surprises you? Where do you set "otherSoldier"? You're assigning something to some local variable earlier, but that's out of scope, and that variable just coincidentally has the same name as your attribute.
Just use
this.otherSoldier = (Soldier)o;
Set otherSoldier? I'm not setting it anywhere, I'm retrieving otherSoldier from a list of previously generated instances of Soldier from within a given instance of Soldier. This soldier is fighting the otherSoldier, so I'm confused as to how telling this soldier that it is also the otherSoldier by saying this.otherSoldier (if I'm understanding you correctly), isn't conflating two different objects. The otherSoldier is not this soldier. It's distinctly possible that I'm misunderstanding you, but I dont' want THIS instance of Soldier to think that it is ALSO otherSoldier, which I believe it would do if I told it this.otherSoldier. I'm sure I'm wrong, please tell me how.

Similar Messages

  • I want to build a drop down menu like the one featured here

    Hi there, I am wanting to build a drop down menu exactly like the one on this site (see college information button, top right)
    http://www.barnsley.ac.uk/index.php
    I have a lot of content, and really like the idea of hiding behind a button at the top, and when the user clicks on it it opens up and pushes the rest of the page down!
    Anyone know how?

    jQuery isn't a program as much as a collection of tools and effects built in JavaScript, a "framework".
    Here's a tutorial that will help you build what you're looking for:
    http://web-kreation.com/index.php/tutorials/nice-clean-sliding-login-panel-built-with-jque ry/

  • If i send a message to my daughter from the computer at home to her e-mail address (which is the one on her i-phone) does the message go to her phone?

    help!!!!   so so new at all of this and my 12 yr old is not the best teacher.   I need to contact her and she uses a e-mail address on her I-phone , so I got on the computer and sent her an e-mail. my question is will it go to her I phone?

    > In sxmb_moni, I get the error: "No receiver could be determined". If I remove one of the conditions, then the output is sent on both receiver adapters, instead of only the one that fulfills the condition.
    Hi,
    I think the problem in Receive Determination. As you mentioned when you remove one of the condition then it works..
    What I concluded is, I think while creating your Receiver Determination for multiple receivers you added the receivers by pressing the plus sign and that means you are using mulitiple receivers with "AND" condition, so in this condition when both the condition will be true then only you will get success.
    What you can do is, Just remove one of the receivers and then add it by pressing the "OR" symbol i.e. by pressing this ( [ ] ) symbol and put your conditions as you like.
    I hope what I have concluded is correct.. 
    Regards,
    Sarvesh

  • How to create a button like the one pictured here

    How would I create a button like the print button below?
    I was thinking actually make it two separate buttons placed next to each other. The print button obviously would just be a modified boolean, that's easy. But the drop down is a bit harder. I figure I could customize a drop down but because I haven't been able to play around with it in LabVIEW (don't have it at home) I'm not sure if you can modify the alignment of the box that actually drops down etc. Is the drop down box location and look something you can modify within the control editor?
    I'm guessing I could also use .net correct? But I am trying to keep it all with just control modification in LabVIEW if possible. Thanks.
    CLA, LabVIEW Versions 2010-2013
    Solved!
    Go to Solution.
    Attachments:
    buttonexample.PNG ‏6 KB

    for(imstuck),
    I'd use a multicolumn listbox and toggle it's visibility when the user clicks on the button.  I've attached an example:
    ~Simon
    Attachments:
    8-2-2010 2-04-25 PM.png ‏24 KB
    Print Drop Down Snippet.png ‏55 KB
    Print Drop Down.vi ‏29 KB

  • Need a more compact BPM flow than the one over here.

    This is the BPM i have encountered with.
    The parameters for the steps are :
    1. Start: One Queue
    1. Loop: Condition: CO_endloop value: not = true
    2. Parallel: End condition; necessary branches : value: 1
    3. Fork Start.
    4. Receive: message: Collect message; use correlation: Correlation
    5. Append : target: Collectmessagelist; operation: Append
    6. loop parameter1: target:Co_endloop;expression:False
    7. Wait:duration: 2mins;
    8. loop parameter2: target:co_endloop;expression:True
    9. Applymapping: source and target messages defined.
    10. Send New message: mode:asynchcronous.
    11. Stop: One queue.
    The graphical definition looks like this:
    .................................-> wait(15 minutes) > loop2>
    Start--> loop --> Parallel(Fork).....................Parallel Fork END --> loop END --> append >send>Stop
    .................................--> receive -->append --> loop1 --->
    Kindly show me how this works.
    Is it a good flow;Please inform if u can come up with a more reduced BPM for the said requirement.
    If we have a similar kind of bpm for another interface,with another branch to add in the parallel node specifying the number or cardinality function(specifying number of idocs to be collected along with the wait condition). how can we do it ?
    Please explain.
    If there are any  reference materials in any blogs for the same then please post in reply.

    This is the BPM i have encountered with.
    The parameters for the steps are :
    1. Start: One Queue
    1. Loop: Condition: CO_endloop value: not = true
    2. Parallel: End condition; necessary branches : value: 1
    3. Fork Start.
    4. Receive: message: Collect message; use correlation: Correlation
    5. Append : target: Collectmessagelist; operation: Append
    6. loop parameter1: target:Co_endloop;expression:False
    7. Wait:duration: 2mins;
    8. loop parameter2: target:co_endloop;expression:True
    9. Applymapping: source and target messages defined.
    10. Send New message: mode:asynchcronous.
    11. Stop: One queue.
    The graphical definition looks like this:
    .................................-> wait(15 minutes) > loop2>
    Start--> loop --> Parallel(Fork).....................Parallel Fork END --> loop END --> append >send>Stop
    .................................--> receive -->append --> loop1 --->
    Kindly show me how this works.
    Is it a good flow;Please inform if u can come up with a more reduced BPM for the said requirement.
    If we have a similar kind of bpm for another interface,with another branch to add in the parallel node specifying the number or cardinality function(specifying number of idocs to be collected along with the wait condition). how can we do it ?
    Please explain.
    If there are any  reference materials in any blogs for the same then please post in reply.

  • Is there a good fix for iTunes crashing on start up on the itunes store for Windows 8.1 tried the ones on here bust still get display driver problems

    I recently purchased a new PC and it came with Windows 8.1 and tried to install itunes as i had it installed on windows Vista and XP but for some reason now on windows 8.1 every time I open itunes is takes me to the take a tour page of the new itunes and when i try to go to the itunes store it allows me to brows for like 30 seconds before i get the Error Display Driver.

    What is your exact brand/model graphics adapter (ATI or nVidia or ???)
    What is your exact graphics adapter driver version?
    Have you gone to the vendor web site to check for a newer driver?
    For Windows, do NOT rely on Windows Update to have current driver information
    -you need to go direct to the vendor web site and check updates for yourself
    ATI Driver Autodetect http://support.amd.com/en-us/download/auto-detect-tool
    nVidia Driver Downloads http://www.nvidia.com/Download/index.aspx?lang=en-us
    Do you have dual graphics adapters?
    Go to the Windows Control Panel and select Hardware and Sound and then select Device Manager... In Device manager you click the + sign to the left of Display Adapters... and see if 2 are listed
    IF YES, read below
    -http://helpx.adobe.com/premiere-pro/kb/error---preludevideo-play-modules.html
    -http://forums.adobe.com/thread/1001579
    -Use BIOS http://forums.adobe.com/thread/1019004?tstart=0
    -link to why http://forums.adobe.com/message/4685328
    -http://www.anandtech.com/show/4839/mobile-gpu-faceoff-amd-dynamic-switchable-graphics-vs-n vidia-optimus-technology/2

  • When i run a sequence with ivi step types in simulation mode i get the error code number BFFA0015 - Types do not match.

    When i run the sequence with ivi step types in simulation mode i get the error Types do not mathc. The step that generates this error is an IviScope step type and is configured as a measurement. Th weird thing is that in real mode is working perfectly. I have three measure steps and i get the error in all of them. The exact error message is:
    UUT Result: Error, Error executing substep 'Post'. An exception occurred calling 'RunStep' in 'ISubstep' of 'TestStand Ivi Step Types 1.0 Type Library' An error occurred while executing the step. Component Works IVI Control Error: The IVI Read operation failed on channel '1' for logical name 'SampleScope'. Details: (1
    ) Types do not match. [IVI Error Code: BFFA0015] Source: TSIviStepTypes [Error Code: -30721, User-defined error code.]
    Can someone tell me how to fix this problem?. It seems to me that the simulation generates a diferent type of measurement of that generated in real mode.

    Update:
    The simulation driver appears to be raising the error. By switching to specific driver simulation the error does not occur. This may be a problem in either the class simulation driver or the specific driver.
    Scott Richardson
    National Instruments

  • IOS Simulator failed to install the application

    I just installed OS X Mavericks then downloaded XCODE. Just to test it, I created a Single View Controller application. I went to the storyboard and added a label just so I could see something come up when I would run the app. I did not add any code. I ran the app which builds fine, but I then get a IOS Simulator failed to install the application. Rememer, this is a clean install of Mavericks, a clean install of XCODE and the first app created. I repeated this for a Master-Detail application and get the same result. I did not change any settings in XCODE from that which is installed by default. Just wanted to go through a build and run to verify things before I start writing a real app.
    I checked the forums which talk about telling the IOS Simulator to Reset Content and Settings. This does not resolve it. I get a black simulator screen. There was other talk about removing a file: ~/Library/Application Support/iPhone Simulator
    but that file does not exist. The forums also talk about building IOS 6 apps and then having a problem after building for IOS 7. But again, no default parameters were changed and it is building an IOS 7 app for the first time and has only been generating IOS 7 apps.
    Any ideas why the simulator won't load any of the simple apps?

    Since everything else I tried had failed, I uninstalled XCODE, reset the Mac then re-installed XCODE and the apps all started loading properly into the simulator. After I installed OS X Mavericks the first thing I did was install XCODE and made no configuration changes to it. Yet I had the issue reported. But now with reloading XCODE all seems fine.

  • Animated gif icon for an exception instead of the standard icon?

    Hello,
    is there a possibillity to use an animated gif icon for an exception instead of the red standard icon in a web template?
    I tried  to change the standard icon s_s_ledr.gif against an animated gif icon in the mime repository, but it does not work. In the IE the icon is still shown without animation.
    Maybe I´ve changed the wrong icon?
    Can you please help me?
    Greetings
    Andreas
    Edited by: Andreas Zenner on Feb 25, 2009 1:22 PM

    Hi Andreas,
    it is possible to integrate own symbols for exceptions. If you can use animated gif I don't know. However there is a post over here explaining the usage of the modification for symbols:
    Re: BI 7 Web Design API - Parameter modification - Exception symbol
    If you have questions just let us know.
    Brgds,
    Marcel

  • Coded UI -Unit Test Adapter threw exception: Unable to load one or more of the requested types

    I am working on silver light bases share point application using visual studio 2012 with C#
    While debugging  coded ui tests with ui maps  i am getting this error.
    I have taken the solution developed by team member containing test methods and trying to debug/run the test methods which contain ui maps I am getting 
    Unit Test Adapter threw exception: Unable to load one or more of the requested types.Retrieve the loader exceptions property for more information.
    When i exclude the tests that depend on ui maps and debug/run remaining test methods I am not getting this error and able to run/debug test methods successfully
    But when I include the test methods related to ui maps and tried to debug i am getting this error.
    Please help me in this.

    Thanks for Fouad's help.
    Hi usha.talasila,
    >>Unit Test Adapter threw exception: Unable to load one or more of the requested types.Retrieve the loader exceptions property for more information.
    Generally this error would be related to the references. Like Fouad's suggestion, you would check whether there are specific references in your test project, and then right click the reference->property, and then set the Copy Local =true.
    Best Regards,
    Jack
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • An XSD Exception occurred. The kind 'Note' does not exist in the CMS. (FWM

    Hi,
    I am trying to get the Know Rights for a report object without any success. Everytime my code hits this method it throws an exception
    An XSD Exception occurred. The kind 'Note' does not exist in the CMS. (FWM 04030) (WBP 42029)
    I am stuck with this problem for past two days and am not able to figure out any solution
    Can anyone please help me in this issue?
    Public Function GetObjectRights(ByVal CUID As String) As RightInfo()
            Try
                Dim m_BiPlatform As BusinessObjects.DSWS.BIPlatform.BIPlatform
                Dim urls() As String = _Session.GetAssociatedServicesURL("BIPlatform")
                m_BiPlatform = BusinessObjects.DSWS.BIPlatform.BIPlatform.GetInstance(_Session, urls(0))
                Dim _RightInfo() As RightInfo = m_BiPlatform.GetKnownRights(CUID)
                Return _RightInfo
            Catch ex As DSWSException
            End Try
        End Function
    Thanks,

    Hmm... I can't think of anything else that could be causing the problem.
    I don't know of any way to exclude the 'note' right since GetKnownRights() returns all known rights (RightInfo) for the type of object passed into the method.
    A suggestion might be to try getting the knownRights using the BOE .NET SDK (not web services) to see if the same error occurs.  There is some simple sample code that you can use as a test in the [BOE .NET SDK developers guide|http://help.sap.com/businessobject/product_guides/boexir31/en/boesdk_net_dg_12_en.chm].
    If this fails as well, then I can only assume that there is some problem with your install of Enterprise as I have tried many ways to reproduce the error you are getting, but cannot.

  • I just synced my iphone 3gs after downloading the Safari upgrade, now my iphone won;'t open any apps except the ones loaded on my phone when I got it.

    I just synced my iphone 3gs after downloading the safari update.  Now I can't open any apps except the ones that came with the phone.  I have tried rebooting, turning it off and on. 
    When I select the icon, it goes to the page then returns to my screensaver.
    It was working well before the update and sync with my Acer netbook.  Have never had any problems with itunes store or downloads.

    this happened to me with my iPhone 4. I researched the problem and found this :
    "The reason this happens is because every time a downloaded app is opened it checks for your itunes password for validation that you are authorized to open that app (as it may contain personal info). From time to time the iphone 'forgets' your itunes password. You can fix the missing password by syncing the iphone with itunes or downloading an app from the app store and entering your password that way.”
    And to fix it, all I did was download a new app, or delete a current one, I used Facebook, and re-download it.
    Hope this helps

  • Invalid Handle Exception-What is the reason?

    I face with "Invalid Handle exception" (SQLException) while using the following code.
    Could anybody tell me the possible reasons/Situation the error rise?
    stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(SQLStmt);
         if(rs!=null){
    ResultSetMetaData rsm = rs.getMetaData();
         int totalcols = rsm.getColumnCount();
         Vector temp;
         while (rs.next()) {
         Vector temp = new Vector();
         for (int i = 1; i <= totalcols; i++) {
              String value = rs.getString(i);
              if (value == null) {
              value = "";
         temp.addElement(value);
         }//for loop ends here
         valueVector.addElement(temp);
         rs.close();
         stmt.close();     
    Thank you all

    Vector temp;
    while (rs.next()) {
    Vector temp = new Vector();Are you sure that this is the code you are running? The reason I ask is that I'm pretty sure that it won't compile, at least under JDK1.4. You should get a compile error something like "temp is already defined".
    If thats not the problem you need to find out on which line the error actually occurs. You can get this from the exception by calling the printStackTrace() method.
    Col

  • I have all of my music on my dad's apple ID (on my Macbook pro and iphone). I want to start using my own apple ID (the one that my iPhone uses for everything except iTunes store) as my iTunes apple ID - how do I do this without losing my old music?

    I have all of my music on my dad's apple ID (on my Macbook pro and iphone). I want to start using my own apple ID (the one that my iPhone uses for everything except iTunes store) as my iTunes apple ID - how do I do this without losing my old music?

    Authorize your computer with your Dad's AppleID.

  • How can I get a file to copy all of the files in a directory except itself and the source of the copy function will be the directory the final program is in?

    How can I get a file to copy all of the files in a directory except itself and the source of the copy function will be the directory the final program is in? This application must be in Lab View 8.

    you mean something like this (see below)?
    Now you may have to implement code to check if the destination folder exists and to create it, etc.  But if you use the Front Panel Control to select the destination folder, it should be okay.
    Not the best implementation, mind you but you'll get the idea..
    Message Edited by JoeLabView on 04-18-2007 03:43 PM
    Attachments:
    copy folder contents.PNG ‏10 KB

Maybe you are looking for

  • Possible to put iMac G5 HD into PowerMac?

    I recently had my old iMac g5 die (logic board not Hard Drive). I have an old Power Mac G5 with an open harddrive bay. Can I put the imacs HD in there to get my data? is there anything I need to worry about? Is it even possible?

  • Create a Raid to be used in VISTA

    Need some help on this raid. I am running Vista on a MacPro, I want to raid two 500gig external dives. The raid is just to read files off of. So this is not an OS install thread. In disk management, I have deleted the volumes, than created a new stri

  • When i print from internet it only prints a blank document

    when i print from internet it only prints a blank document.....whats up with that?

  • Draw line over Image??.. in Grid Format

    Hello frnds, what i want to do in my project is to draw image on JPanel with grid lines.. ?? May be image in background and lines over image.. I searched forum before but coulnt find appropriate thread.. please help me out?? gervini

  • Inbound Idoc customer number conversion

    I am new to EDI and have a question to ask you both about inbound IDOC's. We have customers sending remittance advices through EDI. The customer numbers in them are their own customer numbers. In SAP, we maintain different customer numbers. Where do