ERROR ON PREV
Tanks!
  1. "Hello, World!"
  2. Variables and Types
  3. Arrays
  4. While, If, For
  5. ...Problem Set 0
  6. Static Methods
  7. Static Fields
  8. String Conversion
  9. Objects
  10. Threading
  11. Strings
  12. ...Problem Set 1.5
  13. Packages
  14. Complex Numbers
  15. Abstract classes
  16. Interfaces
  17. Autoboxing
  18. ...Problem Set 1
  19. enum
  20. Inner Classes
  21. Polymorphism
  22. Tanks!
  23. Callbacks
  24. Exceptions
  25. File I/O
  26. ...Problem Set 2
  27. Regular Expressions

Tanks!

Implement a Tank for a Tank Battle. The Tank should subclass tanks.Tank. You only need to implement one method, action. Here is a sample:

SimpleTank.java
1import tanks.*;
2import java.util.*;
3 
4public class SimpleTank extends Tank {
5    public void action() {
6        Direction dir = randomDir(); // choose a random direction
7        ScanResult[] results = scanArray(9); // long range scan
8        for(int i=0;i<results.length;i++) {
9            Pos pos = getPos();
10            ScanResult sr = results[i];
11            if(sr.pos.x == pos.x && sr.pos.y == pos.y)
12                throw new Error("same pos!");
13            dir = pos.toward(sr.pos); // direction to target
14            aimTurret(dir); 
15            fire();
16            break;
17        }   
18        Pos p = getPos();
19        Pos np = new Pos(p.x+dir.dx,p.y+dir.dy);
20        boolean collision = false;
21        for(int i=0;i<results.length;i++) {
22            if(equals(np,results[i].pos))
23                collision = true;
24        }
25        if(!collision) { // avoid collision!
26            setDrivingDirection(dir);
27            drive();
28        }
29    }
30}
You can download the program here.
  • You can extract the contents of the file using the command: jar xf tanks-src.jar
  • Compile your code like this: javac SimpleTank.java tanks/*.java
  • Running the code:
    • Edit the file tanks.in. This file should have the name of a java class file for a tank, one per line. It might look like this:
                                      SimpleTank
                                      tanks.Tank
                                      tanks.Tank
                                  
      Make sure your tank is in the list.
    • Run the command: java tanks.Game -- this will cause the battle to occur, and save the output in a file called game1.log (or game2.log if game1.log exits, or game3.log if game1.log and game2.log exsists, etc.).
    • Visualize the battle by typing: java tanks.Viewer game1.log
    • Visualize all battles by typing: java tanks.Viewer