Robotwar
By Alex Kallend

Note, this document also exists in Microsoft Word format, in the file,
robot.doc  It is probably easier to read that version.


Robotwar is a game where rather than playing as a robot, you program a robot, and see it battle against 
other programmed robots. The idea is simple: You have a robot, equipped with a radar device, a means of 
transportation, and a gun. Your robot is put into an arena with between 1 and 4 other robots, where they all 
try to outlive each other.
Your robot needs a goal. Will you try to outlive the other robots by not getting hurt, or will you try to 
destroy them before they can destroy you?  Your job is to program your robots brain. 
Robotwar comes with a menu based driver. It allows you to edit, compile and schedule matches between 
robots. 
The Editor: 
The editor allows you to edit robot code.
The Compiler:
The compiler presents you with a choice of robots with code in the directory. It attempts to compile 
that robots code, and prints any error messages to the screen. After editing any robot, you need to 
compile it for the changes to take effect.
The Match Scheduler:
The match scheduler presents you with a selection screen. You can add any robot  that is currently 
compiled to the match. When youve finished selecting robots, you need to choose how many matches 
you want to run, by using the n option. Hit d and the matches begin. When the matches are over, the 
robots scores are returned. Each robot is given 1 point for each other robot it outlives. For multiple 
scheduled matches, the total score is returned. You can set the matches to be run in fast mode, where 
no graphics are displayed, by hitting f.
You can stop a match at any time by pressing s. You can terminate all remaining matches by pressing 
t. You can toggle the sound on and off by pressing m. Any other key will pause the game until 
another key is pressed.
The Tournament Driver:
The tournament driver takes all the robots on the disk and runs a number of matches between them. It 
randomly sets up matches with n robots each (n is chosen at the beginning of the tournament), keeping 
each robots total score. When done, it reports which robot has accumulated the most points overall.





The Arena:
The arena is where the robots battle it out. The arena screen is comprised of the arena and the display. 
The display shows the current damage done to each robot. It is color coded, so you can tell which robot 
is which in the arena. The arena has dimensions of 250x190, although, since the robots have a size of 
10, and are represented by their center coordinates, the actual working dimensions of the arena are (6-
244 x, 6-184 y).
The Robots:
Each robot has a representation on the screen. Each robot is a different color, so they can be 
distinguished from each other.  Each robot looks like a little tank. The direction the robot is aiming can 
be determined by looking at the robots turret.
			          225     270   315
				    \    |   /
				      \  | /
			         180 -- robot -- 0
				      /  |   \
				    /    |    \
			          135     90     45

Notice, the robots targetting angles increase clockwise, while angles usually increase counter-clockwise. 
This is because on a monitor, Y coordinates grow down, not up.

The robots use a doppler type radar, that can return whether or not another robot was found at any 
given angle, and also the speed of the found robot, if any.
Damaging a robot:
A robot can be damaged in one of two ways. The first, more common way of being damaged is by being 
shot by another robot. Whenever a robot is shot it takes damage between 3 and 14% of its total. Robots 
can be damaged when explosions go off near them, although it does less damage than a direct hit. 
Robots can also be damaged by running into things. Whenever two robots collide, they each take 
damage equal to the speed of the moving robot. If a robot runs into a wall, it takes a few points of 
damage. Collisions are often fatal when robots dont detect damage while moving, because they will 
continue to try and move, even though there is an obstacle in the way.
Robot Death:  
A robot dies when it has taken 100% or more damage. The dead robot is removed from the game, so as 
not to obstruct the remaining robots.  A robot also dies if it ever runs out of code to execute. A robot 
who runs out of code has essentially become a sitting duck.  Certain illegal instructions can cause robot 
termination. (Things like overflowing the robots stack, writing over the ends of arrays, etc.)
When only 2 robots are left (or if only 2 robots were chosen) a countdown begins. The countdown is in 
robot clock cycles, so should be machine independent. Each time a robot damages another robot, 200 
more cycles are added to the countdown.  This countdown is displayed at the bottom of the screen, and 
helps to prevent stalemates between robots.

How to Program a Robot

Programming a robot is meant to be both enjoyable and interesting.  The language is simple enough that 
using it isnt a challenge, so the challenge can be designing the algorithm that the robot uses. 
Comments:
Any pound sign (#) indicates that the remainder of the line it was found on is a comment. A comment is 
a line used by the programmer, but ignored by the computer. Its useful to have them so that other 
people looking at your code can tell what you meant to do. 
Variables:
Variables are words that are used to store values as your robots program runs. They must be declared 
before they can be used. Variables are declared by writing the name you want to use before the brackets 
that indicate the beginning of your code.
Functions:
Functions are small sub-programs that are used by the main program to work more efficiently. 
Functions are declared at the beginning of the program. They are called by typing the function name, 
followed by parenthesis.  Functions can be passed parameters when they are called. Putting a value, or 
expression within the functions parenthesis will pass that value to the function. Additional values can be 
passed by adding commas. Some functions return values that are used by the main program. They do 
this by  using the return statement. Functions that do not explicitly return a value return an undefined 
value, so if you want a function to return something, you need to remember to explicitly tell it to. Each 
function can have its own local variables that exist only while the function is being used. There are also 
some predefined functions that are explained later. They behave just like functions you would write.  
Blocks: 
A block is a collection of statements. It follows the form:
	{ 
		statement ; 
		statement; 
		statement; 
	} 
A block can be empty if needed:
	{
	}

Statements:
There are 3 main types of statements in the robot language. Each statement must be ended with a 
semicolon. 
IF : 
An if statement is used for decision making. It follows the 
form
IF (expression) THEN if-statement;
or
IF (expression) THEN if-statement ELSE if-statement;

Examples:
if (a=b) then a := a + 1;
if (a=b) then
	a :=a+1      <<---- note, no semicolon here, as not 
	else     b :=b+1;            the end of the IF statement   
		
       if (a=b) then	
	{
		a:=a+1;
		b:=b+1;
	};

if (a=b) then
	{
		a:=a+1;
		b:=b+1;
	} else             <<---- No semicolon here either. 
       	{
		a:=a-1;
       	};

Notice, there is always a semicolon at the end of the IF statement, but not at the end of the internal 
THEN statements. 


WHILE
While statements are used for looping. A while statement follows the 
form
WHILE ( expression ) DO while-statement;
A while-statement is the same as an if-statement, it can either become a single statement, or a block of 
statements.     
Examples:
while (a<b) do
a:=a+1;
while (a<b) do 
	{
		a:=a+1;
		b:=b-1;
	};

In order to program a counter, you can use a while loop, and a variable. For example, to count from 1 to 20, 
the following code will work. 


i:= 1;
while (i<=20) do
	{
# do stuff;
i:=i+1;
	};


Expressions
An expression is a combination of one or more numbers and variables combined with mathematical 
symbols. Robots supports most standard math. Like with math, parenthesis mean do this first, and 
other operations take place in the order that they would in mathematics. The table below shows the 
order in which operations occur, from the most important, to least important. 

High Precedence
			()       (parenthesis)
			^        (factor)
			*, /, %  (multiplication, integer division, modulus) 
			+,-     (addition, subtraction)
			=,<=,<, <>,>,>= (relationships)
			not (!)  (negation)
			and (&)  (conjunction)
			or  (|)  (disjunction)
Low Precedence

so,  a + b * c ^ d = f or g  evaluates as (((a+(b*(c^d))) = f) or g)
In addition, assignment is considered an expression. An assignment must have a variable on the left hand 
side of the assignment operator ( := )  and an expression on the right hand side. Assignments always 
resolve last in any statement.


Predefined Functions:
Robots use many predefined functions, to control what their actions.  A list of the currently available 
predefined functions is presented here.
	Fire(angle)     	: fires the robots weapon at the selected angle. 
				This will return a TRUE if the gun was fired, or a 
				FALSE if the gun was reloading.
	DistFire(angle,d)	:fires a shot with a distance variable fuse. It takes slightly longer to reload after 	
			firing fused shots. A shot with a distance fuse will explode at a distance d from 	
			the robot, as long as it doesnt hit anything en-route to that location.
			This will return the same as the fire function.
	Radar(angle)   	: sends a radar pulse out at the given angle. Returns a 0 if nothing found, or the 	
			distance to the robot detected, if one is found. Using the radar causes a slight 	
			delay in the robots instruction processing.
	Random(max)  	: returns a random number from 0 to (max -1)
	Locx()		: returns the robots current X location
	Locy()		: returns the robots current Y location
	Damage()        	: returns the robots damage status (a number from 1 to 100 if the robot is still 	
			functioning.)
	Goto(x,y)       	: starts the robot moving to the specified location. The robot stops when it gets 	
			to the specified coordinates.
	There()         	: returns true if the robot has reached its most recent destination, (set with goto)
			or false if the robot is still moving.
	Hit()           	: returns whether or not the robot has been damaged since the last time this 	
			function 	was called. 
			A 0 means that the robot was not damaged.  Any positive value means that the 	
			robot was damaged. A 5 means that the robot was hit by gunfire, while values 	
			between 1 and 4 indicate collisions. The side from which the collision took place 	
			is indicated by the value, as shown on the diagram below. 
				1
			              4      2 
				3
	GetAngle(x,y)   	: returns the angle along which the point x,y can be found using the robots 	
			current x and y location as a center.
	GetX(angle, d)  	: returns the x offset for a point at distance d from the robot, at the angle 	
			specified
	GetY(angle, d)  	: returns the y offset for a point at distance d from the robot, at the angle 	
			specified
	GetNumRobots()  : returns the number of robots currently left in the game including this robot. 
	Left()          	: returns the x coordinate of the left wall of the arena
	Right()         	: returns the x coordinates of the right wall
	Top()           	: returns the y coordinate of the top of the arena
	Bottom()        	: returns the y coordinate of the bottom of the arena

	Repair()        	: This initiates the robots self repair facilities. Repairing clears any existing goto	
			command, and stops the robot moving.
	Trsx()		: This returns the horizontal (X) velocity of the last robot found with the radar.
	Trsy()		: This returns the vertical (Y) velocity of the last robot found with the radar.
	getdist(x,y)	: returns the distance to a given point (x,y)

Putting it together:
Here is a sample robot. Comments on the right of the code should help to explain what it does. 

	aim;                                            			# global variable
function gettarget(inc)                        			# one parameter, inc 
{
while (radar(aim:=aim+inc) = 0 )        			# looks for another robot
do if (aim > 360) then aim := aim - 360;
return aim;                             				# returns when robot found
}
 
function move()                                 			# no parameters
	x; y;                                   			# variables
{
x:=random(230)+10;                      			# assignments
y:=random(170)+10;
goto(x,y);                              				# predefined function call
}

							# main function
begin
d;                                      				# local variable
{
	aim := 0;                               			# initialize aim

	aim := gettarget(7);                    			# call function
	while (getnumrobots() > 1) do                         	# infinite loop for robot body
	{
		while(radar(aim)) do       			# use radar
		{
			d := damage();          		# save damage 
			fire(aim);              		# fire gun
			if (d <> damage()) then 		# if d is not what damage returns, Ive                      
				move();         		# been hit so move.
		};
		aim:= gettarget(7);             		# get a new target
	};
}
end


Appendix:

BNF for robot language

start: <p>
<p>  ::=  <vardecl> <program>
<program> ::= [<fhead>]* BEGIN <vardecl> <block> END
<fhead> ::= FUNCTION ID ( [ ID [,ID]* ] ) <vardecl> <block>
<vardecl> ::= [ ID; | ARRAY ID[NUMBER]; ]*
<block> ::= { <stat> }
<stat> ::= [ <statement> ; ]*
<statement> ::= IF ( <expr> ) THEN <iftail> [ ELSE <iftail> ]
		| WHILE ( <expr> ) DO <whiletail>
		| <expr>
		| RETURN <expr>
<iftail> ::= <statement>
	   | <block>
<whiletail> ::= <statement>
		   | <block>
<expr> ::= <disj>
	    | ID <varend> := <expr>
<primary> ::= ID <primtail>
		 | <prim1>
<primtail> ::= <procend>
	      | <varend>
<varend> ::=  [ [ <expr> ] ]
<procend> ::= ([<expr> [,<expr>]* ] )
<prim1> ::= NUMBER
	     | ( <expr> )
<factor> ::= <primary> [ ^ <primary>]*
<term> ::= <factor> [ { * | / | % } <factor> ]*
<sum> ::= [ + | - ] <term>  [ {+ | -} <term> ]*
<relation> ::= <sum>  [ { = | < | <= | <> | >= | > } <sum>]*
<negation> ::= [{ NOT | !  } ] <relation>
<conj> ::= <negation> [ { AND | &  } <conj> ]
<disj> ::= <conj> [ {OR |  |  } <disj> ]


