if (rc.getTeam().ordinal()+1== mapInfo.getSpawnZoneTeam()) {
// use for teams since they are "enum variables"
}
Assistant
User
how to teach it to class?
Assistant
User
and what about arraylist? why we need in battlecode
Assistant
library and give you a framework for
coding your Bot um so to do that simply
go to this page hit code and then hit
download zip now we'll download the zip
file um into your downloads folder so
I've done this here here it is and then
we can extract that um into its own
folder so on Mac you just double click
on Windows you can extract make sure you
have it extracted into its own folder
when you do that you should see all the
files in here so we have build. Gradle
Gradle all these things in here so I
have that set up already my desktop
so let's see what the next step is so
once everything is ready with the with
the scaffold we can start moving on to
the local setup so depending on your
your development environment or your
text editor this kind of thing it'll be
different um we've even provided some
basic instructions for how to do this in
intellig and Eclipse which are both two
um integrated Java development
environments so it makes makes working
with Java in our build system very easy
so would definitely recommend using
those um if you're having any problems
so let's start with Eclipse very common
editor and see how we can get started
with
Eclipse so let me first open that so
Eclipse so we have links to download on
the page but I already have it
downloaded so let me just open it so
it'll be prompted with this select
directory as a workspace um this is not
that important you can just leave what
it says by
default and here's what we see when we
open the
IDE all right so the first thing you
want to do is go to file and then um
import so you want to import the B code
project so we have to click Gradle
existing Gradle project so our battle
code is Gradle so next and this is very
important so make sure you guys pay
attention to this part um so let's
actually first select our project
directory so
desktop um Clips so I'll select the
scaffold folder as the root folder of
the
project um and then we need to hit next
here not finished because we need to
make sure that our Java is set to the
correct version so what whichever Java
you installed so Java um version 8 um
there are plenty of ways to figure out
depending on your platform where it's
installed to but we have to make sure
that we select override workspace
settings and set the Java home variable
right here specifically to be um our
Java Home Path so basically where the
Java Java is installed um so in this
case on my machine this is the location
if you're on Mac it'll probably be the
same thing um so I'll put that right in
there and this make sure that when we
run the build system it's using the
correct version of java so hit finish
should set up the project for
us perfect so if I drop this down we can
see all of our tasks in here so Gradle
basically is a system that lets you run
various tasks and in here we can see we
have a little ble code folder up here
this is where all the ble code tasks
will be located so we have build check
new version list Maps run
Etc um so let me open the package here
so we can see what what's going on
um is this so
small fix
that
okay here we go so we can see our
package Explorer here here's all our
source files so if I go into Source
example function player robot player
here is the default um bot that we
include with the scaffold so this helps
you with all the boiler play that you
need to get set up we'll run through
this bot a little bit later so you guys
have an idea what's actually going on
but for now we'll just skip we'll just
skip it um so this is just the example
bot uh if we want to run this
bot um we need to go to our task list
which um should be somewhere around
here here's our tasks so we can build
which will build our code um let's
actually run unpack client so this task
will download the client for us so we
can actually run our games um so once I
do that
let me open up the code so here if we
look back in our project folder we can
see it created a client folder right
here with the ble code client in it so
I'm going to run
this um and here is our client so this
is how you'll visualize all your games
so we distribute this with the engine
and allows you to run visualize see all
the stats that way you can actually know
what's going on because the engine just
runs the code it's kind of hard to tell
what's happening so we can either upload
a match file directly which if you run
the engine which um you can do so let's
do that first let's go to our tasks um
Gradle and let's click
run so you can see it running down here
on the bottom right it's running a
match perfect when that's
done um it actually already populated
for us which is kind of convenient so
here it is it's already loaded into the
client um here we can see our game we
can see some stats so as I I start to
play I can hit space and I can start
seeing the game so here are our ducks
moving around these little arrows
indicate that the duck is carrying the
flag so it's kind of easier to see um we
can see on the left side the count of
each of the Ducks so we have the generic
Ducks here these are the attack Ducks
these are the build ducks and these are
the heal ducks and then these are how
many ducks are currently in jail or out
of the game um this little graph down
here indicates how many units are
allocated to each specialization level
so right now they all start at zero and
as they do more actions this bar chart
will change depending on what they
specialize in so let's speed up this
game a little bit so we can hit these
controls down here which will speed up
the game pause the game go to the next
turn Etc um and if we can also click on
h space to pause if you want to see what
a specific bot is doing we can click on
it and it will show us some stats about
it so it's ID it's Health it's location
um some information like it's the amount
by code it's
using um and if there something if this
control bar is in the way and you want
to click on something you can hit this
minus here and that'll minimize it so
you can click on things that are behind
the control bar um one other cool
feature in the client is if we click on
the bot we can see this little path and
this shows us where the bot has been
recently so if I go step back one or two
turns we can see it follows along this
path so this is where you can kind of
see what your bot's been up to um this
whole
time so yeah that's a little bit about
the client we'll talk about that a
little bit more later um let's move on
to our other IDE for right
now um and so we also have some
instructions for how to get it set up
for intellig so in is another IDE for
doing Java it's very good um let's see
how to set that up so let's open up
intellig we have a installation link on
our website but I already have installed
so first thing we want to do we want to
open our project so we'll hit open and
then let me navigate to
TJ and we want to select the
build.gradle file me just just open
this then we want to say open as
project perfect here it is so as you can
see we start out we get a little error
that says andine must be run using Java
8 this is again another issue with our
computer not detecting the correct Java
version so we can fix that um by going
to our preferences in intelligy and then
we go to um
where is
it um build execution and
deployment and
then where is it build tools Gradle and
then we'll see a config for a specific
project here so B 24 scaffold want to
make sure we set our gr jvm to be
whatever version of version a we
downloaded so in this case mine is open
jdk version 1.8 so I'll set this to be
that and then I'll hit
apply so now if I try building this
again
um we can access our tasks from the top
right little elephant icon this is our
gradal task so I click this um so my
tasks why is these not showing up hit
the refresh button here we go perfect
it's configuring for us now if I expand
this here are all our tasks so again we
can see the same structure as we saw
before B code folder has all our tests
in it here we can build check version
run Etc so let me just try building make
sure that
works see down here perfect build
successful let me get the client going
so let me unpack the
client and let me try running a
match so let's open up our bot here it
is robot player same thing we saw
before um let me get into a match here
or into the client so same structure as
the eclipse setup um in your project
directory you'll see the client
folder open that up and hopefully when
you go to the runner so the runner is
how you actually run games through the
client hopefully it will automatically
detect um your folder and all your setup
if not you can click this reconfigure
scaffold button and this will take you
to a folder select so all you have to do
here is select your scaffold directory
hit open and this should automatically
detect all your maps and players so
right now we only have example funks
player but if we in theory had more
bosss wanted to test we could do it in
here so let's actually run a match so
let's pick two teams to run so we'll
just select them both to be this player
and then here we can select one or
multiple maps to run them on so each map
is like a separate game that runs and
they're all independent so for now we'll
just pick one so I'll just pick small
and then this Java instance thing this
is another way that um things can get
messed up if you don't have the right
Java version selected so this tries to
locate the correct installation so here
I can see it detected these for me so
Auto should work if this is not working
for you you can hit custom and input
that same path that we did earlier into
here and that should hopefully fix the
Java problem um but hopefully it should
just work by default so if I hit
run um running the game here we go you
can see my
output so each the Bots are printing
some things each turn and here we go
game has been
loaded hit
play and I can watch this game awesome
and then here's all my stats in
here and then here I can see the que so
this is the games that have been run so
far so here I can see the players who
played I can see what map it was on and
I can see who won and why so this case I
won with more captured Flags after 2,000
rounds um 2,000 rounds is the maximum
let me try running one more game this
time I'll select two maps so I'll select
small and
medium this will
run here we go second map is
running awesome now we can replay these
through these games and here if we look
in the queue we can see there are
actually now two maps on this game so we
click the second one we'll be taken to
the second game and here we can see this
one being played and we go back to the
first one and vice
versa so yeah that's basic setup for um
the clients and the idees does anyone
have any questions so far on anything
that they've seen or
encountered awesome let's move on a
little bit to um some more Java specific
things so kind of like a maybe review
for some of you but if you guys are new
to using Java let's talk about that a
little bit uh Max would like to up here
let me add in the code for
you
um
go this perfect so look code is in
here
go just put that there right your pocket
and then just put that up
here okay great cool can everyone hear
me great okay
so
um uh first we're going
to we're going to look at some Java
stuff
so sorry I'm pulling up the
file
so here is uh like the most basic Java
program uh we have this thing at the top
so this
means so I'm not used to using a
computer but yeah uh this thing at the
top is a package declaration and
uh the package name has to match the
folder that the Java files in so in this
case we have the example fun player
folder and the functions class the
functions file here functions. Java is
contained in it so we put this package
declaration at the
top and then uh the next thing in the
file
is uh we have these Imports these will
import packages that we'll need so
there's the ball code.com package we do
import baloc code.com and. asterisk and
that Imports everything from bod.com
package you'll generally want to use
this for your Bots and
then oh yeah I don't know what this
other one is but uh and then we have
java. random which is for generating
random numbers so uh then we get to the
actual program so every program in Java
is contained inside a class this is
different from languages like python
where you can just like write print
hello world or whatever you have to
actually put like boiler plate code here
for Java so we have the functions class
here and then you have methods inside
the class
so uh the main method which is called
whenever you run the program is this
thing you write public static void main
of string bracket bracket args so uh if
you ever want to just like run a Java
program you have to put the code that
you're running inside this
function and then we have this other
method here the test
method and uh this prints hello world
system. al. printline is the uh Java
version of python print and just prints
it to the console and in ballot code uh
it'll print it to
the the thing that you saw earlier on
the side so you'll be able to see it if
you use system di print
line so if we want to call the test
method inside the main method so that
it'll actually run and we do
that and then we're getting an error
message
here it says non-static method test
cannot be referenced from a static
context and to fix this well notice that
the main me method is a static method it
has a static modifier here and that
means that it's not like connected to an
instance of the functions class it's
just like a thing which is associated
with the class so for main methods and
methods that are called in the main
method uh you might want
to write static and then there's no
error message anymore so it should
work um so if we run this program
hello world you can see right here it
works
so uh the next thing we're going to look
at
is uh right
here so we have another class with the
main meod like normal and the print line
statement here and we're basically
defining a variable that's an integer
that's what in means and it is
100,000 then what we're doing here is
assigning it to its Square multiplying
it by itself and putting it back in the
variable and then we're printing it that
all seems pretty simple
right so we're running this and then
here's a result it's this weird number
it's like 1 14 1 0 0 something so so
this is definitely not the square of
100,000 and the reason that something
bad is happening here is that the number
just got too big the square turns out to
be uh 10 billion and that's bigger than
the integers in Java can handle
so instead of integers you have to
use
Longs uh this is just an injur with like
more storage of it aailable basically uh
it can handle stuff up to I don't
remember the exact number but it's
bigger than 10 billion so this should
work if we run this
now yeah prints the correct
result and there are also other uh
integer data types like there's one for
bytes which you probably won't need uh
you mostly need long for
integers so now we're going to look at
another thing involving numbers let's
say we have a variable called robot
count it's an integer we're setting it
to 50 here and now we want 15% of the
Bots to be Builders so we're making a
new variable which is the number of
Builders and we're multi multiplying it
by 0.15 which is 15% and then we want to
print
this
so oops there's an error message let's
look at what this says required type int
provided double and what's going on here
is 0.15 is the double like a floating
Point double is the type of floating
point in Java and
um if we multiply by an integer then
double time integer is another double
because it's not guaranteed to be an
integer and then it's saying an error
message because we're trying to set an
integer variable to be a
double that is uh not allowed so there
are multiple ways to fix this you can
either make the variable a
double we do this everything should work
and should give the right result hope
y
7.5 sounds about right
yeah another way to fix this if you
really want to be an integer sometimes
necessary is you can cast to integer
which I think rounds
down so if we put in in parenthesis
there and put this in
parenthesis then we can do this again
seven so yes it does round on and this
is approximately
correct so uh that is integer data types
this is important because like in Python
uh it's weekly typed so um like integers
would and floating points will just
convert to each other kind
of uh also one thing to remember in Java
is that if you divide two integers it
will give the rounded down result so uh
you need to convert one of them to a
floating point if you want the accurate
floating Point
result okay so another important thing
in programming is arrays uh Java arrays
are a little bit more complicated than
python arrays because there are multiple
versions of them
uh the most basic type of array is just
this so you do int bracket bracket int
array equals uh curly brace 1 two 3 and
this will define an array of integers
which contains the integers one two and
three and then we can also just Define
an array without initializing it here um
so the computer just not know what the
value of this array is right now because
we haven't given it one but then uh if
we try to initialize this with let's say
456 it gives an error message now what's
it saying array initializer is not
allowed
here now in Java for some reason I don't
really know why they did this but uh you
can't assign things to be uh expressions
like this with the curly braces after uh
after you've already declared the
variable
so what you need to do is in Array 2
equals new int bracket bracket and then
put the
expression and this assigns in Array two
to be the array
456 now if we try to print an array of
integers let's see what happens I'm
going to comment out all the other print
statements
oops
you can see a prince this weird thing
random characters it looks like so I'm
pretty sure it's actually printing uh
some identifier which represents the
location of the array or something like
that so the better way to print arrays
oops is to Loop through them and print
out each
value so we don't want to do
that and here we're accessing uh the
zeroth entry
array uh just like most programming
languages razor zero index so this is
the first element which is four so the
should
four
yep
so uh what about arrays of things which
are not
integers uh what about strings well in
Java strings are represented by the
capital string class so we do Capital
string bracket bracket string array
equals this array of
strings and uh to Loop through an array
there are two options which are both
used a lot uh the first one is uh you
can do just like an integer you can
increment an integer gradually from zero
up to the length minus one and then
access the value at the integer so this
is the Java for Loop and then we print
the value at uh index I for each ey and
you do do length to get the length of an
array then we have this other way of
looping through arrays for string
message colon string
array and then the advantage of this is
It's cleaner to right and the
disadvantage is that you don't get the
variable I so you don't know what Index
this is but of course you can like uh
figure that out if you put like an extra
variable in there but if you need the
variable I this upper one is usually
better to
use so both these Loops should do the
same thing and let's test
this
so the array had these four values and
it looks like yeah they're being printed
twice first those four then those four
again
okay
so there's one major difference between
uh python arrays and Java arrays and
that is you can't really add stuff to
Java arrays without making a whole new
array so like if you wanted to add the
number four to this original in Array
you couldn't just do something like in
array. add that doesn't
exist or a pen like python that doesn't
work either
so um here's what you do in Java you
instead use array lists which are um in
the Java that util package so you have
to import java.util
dostar
uh so we have array list and then these
uh angle brackets they represent the
type parameter like the type of the
element so if we want an array of
strings we do array list angle bracket
string angle bracket and then we save
the variable
name
and then we do new array list bracket
string bracket
parenthesis this called it's like a
Constructor which makes a new empty
array then we can add Elements which is
good that's what we wanted we add hello
world battle code
2024 and then we can remove elements too
remove
world and we can uh remove at an index
so if we give it the index zero it'll
remove the zeroth element which is the
first so that's hello so now the array
should only contain battle code
2024 and then we can also add add an
index like inserting an element so if we
do add of zero comma the element we want
to insert that adds it at the beginning
because zero is the first element and we
can also put like one or two or any
other index in there and adds it before
that element and shifts everything
over and we can check if something's in
an array over an array list by using the
contains method better array. contains
of 2024 in this example would check if
this contains 2024 and it
does
and uh then should print is 2024 so
let's see if it
does it does right
here now uh what if you want to
initialize an array list without just
like adding everything right because it
took four lines to add four elements to
this uh one way you can do that
is uh well in this example we're using
integers so you have this array of
integers here 1 one 2 3
58 and uh we just make it like a normal
array like above we do new integer and
uh because of how Java works you have to
use Capital integer instead of in
whenever you work with array list uh as
like the type parameter and when you're
doing this uh initialization
so uh you do new integer of 112 3 58
like we did above and then you plug it
into arrays.
aslist arrays is also in
java.util so this converts it into a
list but not specifically an array list
so then we have to do new array list
bracket integer bracket and put all of
this inside that so it's a lot longer
than you'd see another language like
python but it's it
works so so that's how we initialize
them
um and then to Loop through array lists
it's very similar to arrays except we
use dot size parentheses instead of
length and uh we use do getet to access
the I
element and
also well actually this other method of
looping through them is exactly the same
so that's
nice so let's see what this little
output so looks like it prints so we
said for it to print the index of the
like the number of times it's Loop
through so far uh pull in the element
and it looks like it did that zero is
the verse one then 1 two 3 58
good
uh and then we're looking through the
string array this time so it should
print all the elements remember we
inserted the smiley face at element zero
so it's there then battle code in 2024
perfect have any questions about this so
far great okay
uh one more
thing sorry I don't know why this isn't
working I'm trying to click
on okay there we
go so um there's
one there's another uh this is another
example of a way where like if you've
worked with python a lot then and then
you come to Java you
might uh mess something up just because
Java Works differently
so let's say we're making a bot so we're
importing all the B packages and stuff
and
um so map location is a class you
probably already know this by now but it
represents the locations on the map it
takes in two integers as the coordinates
so we make two mplications here 1 one
and 1 two and we have a Boolean variable
here and we're comparing them we're
using the equals equals operator which
uh checks if they're
equal and then we print this let's see
what
happens is 1 one equal to one two false
it's correct about that good let's make
them both one one and make sure say
true is 1 equal to 1 one false oh no so
this does not work uh the correct way to
do it for MTH locations and for a lot of
different types is location 1. equals of
location
two good this is two this time and if
you change it back to two it should say
false like normal so uh the reason for
this is equals equals always checks if
the basically the memory locations of
the two uh instances of loc of M
application are equal and it's possible
to have two equal things which both
represent one one in two different
locations in the computer so equals
actually compares the uh coordinates X
and Y which is what we
want
so what about comparing things other
than
applications
well uh if we want to compare let's
say uh the team of a spawn Zone that
you're standing on and um
the uh your robots team
basically
so uh in this example we have
robot controller RC and map info map
info we're just going to assume that
like you have these from whatever code
you've been writing and map info is like
the information for whatever Square you
want to check so map info. getet spaone
team returns uh let's see Zero if it's
not a spons Zone one if it's team a
spons Zone and two if it's a team be
spons
Zone and uh rc. getet Team
returns a value of typee Team then
ordinal converts to an integer and
that's going to be uh zero for team a
and one for Team B so we have to add one
to check if they're equal because these
don't match so for team a this would be
0er plus one and this would be one for
Team B this would be 1 plus one this
would be two so it works this is how we
check if teams are equal and then if we
want to check if a robot is on a certain
location we shouldn't do this we
shouldn't do rc. getet location equals
equals location because of the thing we
saw above
so I don't know why it's not clicking I
might be doing something wrong uh okay
there we go so we have to do
dials
now as I mentioned before uh this isn't
just a problem from
applications uh probably for most uh
like
non non-primitive types that you use
you'll want to use do equals inste of
equals equals and here's an example
where things fail so if we use array
list we're just initializing to exactly
the same way right they're both hello
comma
world and we're checking if they're
equal using both equals equals and do
equals
so if we run the
program
uh so this is from the output thing
above with locations we can ignore that
for now um down here for equals equals
it outputs false which is obviously not
what we want in most
cases uh because the arrays are at two
different locations in the computer but
for do equals outputs true which is
correct
so and even for Strings even though the
strings seem pretty simple uh in Java
sometimes things can fail so you want to
use do equals for
Strings here we go that's um some of the
differences between Java and
python all right awesome so yeah that
was just a basic introduction some of
the Java Concepts you'll probably need
to know um let's get into a little bit
of the actual robot player that you're
provided with so let's talk a little bit
about what it's doing um and how you can
change some things to get yourself
started can I
delete so we'll have another lecture
coming up soon where we actually I think
it's I don't know it's I think it's
tomorrow but um where we do a intro bot
making so we'll actually walk through
making a bot um from scratch and so
little more about that and tomorrow's
lecture but for today we'll just go
through the code that we give you and
see what is going on so here's a robot
player file so this is an example
function player um as Max mentioned we
always put the package as the same name
as the folder we're in and for your Bots
you always need to call them robot
player just because the way we um run
your code we look for the specific class
to be there so you can call the folder
whatever you want but you have to call
the class robot player um so here let's
look at this so here's some variables we
keep track of so we keep track of turn
count which keep track of which turn
turns have surpassed um you'll notice
every um uh variable and Method we have
in this class is a static and that's
because we never actually instantiate an
instance of robot player we just do
everything statically so you'll need to
make sure all your methods um and
variables are static uh the way we do
robots is that each robot is running its
own version of this code so it has its
own robot player running and these VAR
that are in here are not shared between
them so anything that you store in here
will only be able to be seen by that
specific robot we'll talk a little bit
more about at the end how um that works
how to actually communicate with other
Bots we have a whole lecture dedicated
to that um I will briefly mention it at
the end because we do a little bit of it
in in this player but let skip that for
now um here we an instantiate a random
number generator so we need to do random
a lot if we're doing um so for example
um in this bot if we don't know what to
move to we'll pick pick a random
Direction so we'll use random to do this
um and then we also include a fix seed
in here and basically a seed just tells
um the number generator how to pick the
ordering of numbers so if we put a fixed
seed in here it'll always be the same
every time that way if we keep running
the bot over and over again we'll get
the we'll get predictable results we
also instantiate an array of all the
directions and this is so we can pick
from directions with just a number which
is very
convenient um and then here's our actual
method so every bot has to have this run
method so it's public static so we can
access it it's called run and we pass in
this robot controller RC parameter so
robot controller is the class that
contains um every single function you're
going to be allowed to use um through
battle
code um how do
I can I see it okay I guess I can't see
it in here um we can see what's in here
so in our getting started in our
resources tab we release the
specifications and Java Docs for your
bots so if you look at the Java docs
this contains basically documentation
for all of the information or for all
the methods in robot controller anything
else you might need so we can click on
this and see everything we can do so
this is a good place to look when you're
trying to figure out what your Bot is
allowed to do and what methods what
parameters it needs and all this stuff
and then here's a specification that I
was talking about yesterday so when you
want to figure out what your Bot is
allowed to do and what are the specifics
about what it can do um the
specification is your friend will tell
you everything you need to know
um so let's see so here's our run method
we can see that it has this throws game
action exception here this is also
necessary it's because if something goes
wrong during the game it will throw an
exception of this type we'll see some
examples of that in a bit so when the
game starts we print out I'm alive so
every bot will print this when it starts
and then here we have this method called
set indicator string so indicator
strings are useful things that you can
use in your robot so when you set these
here they'll last for one turn and in
the client when you click on your robot
it'll display the string as text so this
is useful for debugging some information
about your robot if you want to see it
without printing it out in the console
um we can look at an example of this in
a second let me open up the client and
show
see so let's see if we have any matches
here so on turn one when I spawn in I
click on this duck we can see this
little indicator variable that says
hello world so that's what this is doing
right here and then next turn it will be
cleared out so useful debugging tool you
can also set indicator dots and lines
which are just little dots and lines
that show up on the map so if you want
to visualize some path finding or map
locations then it makes it very
convenient and in the config you can
turn off whether or not you want to
visualize these at all times so just
some things that you can do ready
debugging um but that's just useful tool
then we get into this wild true Loop so
you might be scared by this statement um
and typically this is something that you
don't want however for battle code it's
very important and the reason is because
we never actually want this run method
to terminate um once the run method
terminates your Bot will explode and not
be run not be able to run anymore so
don't let that happen which is why we
have this while true
Loop um and basically the idea is we
want this this Loop to run for every
turn that the bot has so right here we
can see we iterate the turn count by one
and then we have this big try catch
block so you may be familiar with tri
catch from other from other languages
basically what happens is we run some
code in the tri block and if any
exceptions get thrown we get the code
starts running in the catch block so
here we can see if any game actions
exception exceptions occur um then we'll
print it out uh a game action exception
might be anything like you try to move
into an invalid location or attack a
square that doesn't have a bot on it or
you tried to attack too many times in
one turn anything that relates to the
game is a game action exception so
likely these when you re see these they
will be something that you did wrong
with your Bot and it's very easy to
print them out and see what's going on
um if you see a regular exception this
is more likely a bug in our code so
hopefully you should not see these um
and then finally what happens is either
when we throw an exception or our turn
is done we've completed all our stuff
for a turn we call this clock. yield
function it's not super important to
know what's going on here this is part
of the the boiler plate basically what
that means is your Bot will give up its
turn and go to the next one and this is
related to we don't ever let the Run
function terminate so this just has to
be in here for every Loop of the turn
when we're done we want to call this
function um more importantly let's get
into the actual logic so inside of our
try method first we check for if RC do
is spawned so as I mentioned yesterday
when the game starts out none of the
Bots are spawning in and we'll need to
spawn them in into the SP one of the
spawn zones before we can actually
perform any actions so we check first if
it's spawned if it's not we need to
actually spawn it so what way we do that
is we call rc. getet Ali spawn locations
and that will return us a list of map
locations so if we go look at the docs
we can see what a map location actually
is so it's an object that has two ins X
and Y so it represents position on the
map
and so each of these is this place that
we can spawn at so for our bot what we
do is we just take a random one so we
basically call rng. next in so that's
this random number generator we
instantiated earlier pick a random spawn
location from the array and we make sure
that we first of all we can spawn there
and if we can we spawn RC do spawn now
we'll put our bot on the map otherwise
if we're already spawned we check if we
can pick up the flag so RC that get
location will give us the current
location of our bot and then RC can pick
up flag we'll check if we are allowed to
pick up a flag um where we are standing
that's true we pick we call pick it up
and then we set this indicator strain so
let's see if this works if we look in
the bot our code we can see we start out
not holding the flag and then on turn
three we're carrying the flag and we can
see the indicator says holding a
flag
um then we have the special check for an
enemy flag so if we have a flag and our
RC that get round num is greater than
our setup rounds so as we mentioned in
the spec um you can only carry your own
Flags during the setup phase so if we're
carrying a flag after that we know it's
an enemy flag and so if we do that we
need to rush back to our side to capture
it so basically the way we do that is we
get our spawn locations with the same
function as before get all spawn
locations we pick just the first one and
we want to move towards that direction
so we can actually Capture the Flag so
the way we do that is we call rc. get
location so this is where our bot is
currently standing and then we have this
useful method called Direction two and
it will give us a Direction so north
south east west or diagonals to the
location we want to go to so in this
case the location of our spawn Zone and
then if we're allowed to move in that
direction we move with this can move and
move function um so if we look at map
location again in the docs we can see
method in there so here we have
Direction two distance Square two equals
so these are all very useful things to
use when you're trying to get directions
and compare locations and all this stuff
so again Java docs very helpful you can
access it on our
dashboard um so we do that and
then we also want to move if we can
still move we just want to move in a
random Direction basically so we're
going to utilize that directions array
that we had before and just basically
just move move randomly which is not
really a great strategy but that's what
we're doing um if we have it moved then
we check if we are allowed to attack so
if you want to so we pick a random
Direction and if we can attack in that
direction we will attack and print out
this line take that damage and enemy
opponent that was in our way so again
pretty bad strategy but just a little a
demonstration of how you can do some
basic um functionality with your
robot um finally we test out build so
here we run get location again to get
our current location and then subtract
the direction so that will basically
give us the Direction behind the
position behind where we are from a
direction and we check if we can build a
trap behind us so basically the strategy
is just we're running a we're running
away in a direction we want to build a
trap behind us so here we check if we
can build an explosive trap in this
location and we have some random number
generator that equals one so this is
like one every 37 times will'll run this
run this code if both these conditions
are true then we will build this
explosive trap at that
spot um so pretty simple there we
finally have this this method called up
the enemy robots so that's down here so
here's an example of just another method
we can make as many methods as we want
in our class we kind of just want to
make sure we pass along this robot
controller in each of them so we can run
the bot functions but here um here we
use some enemy sensing functions so this
is um the robot controller has numerous
functions called sense where you can
sense things in the map so if we
actually go look at the docs
um so we have sense location or we have
not these sorry so here's some sense
methods these will basically give you
information about the game about the map
about the robots nearby so we have sense
nearby robots we have sense nearby map
info so like if you're by water or
you're by a crumb pile it'll tell you
what's nearby you um and this will
return anything in a radius of this blue
circle is your vision radius so you'll
get information of things in this radius
um so let's see that so you can
explicitly pass a radius that you want
to to look nearby so in this case we
pass negative one which indicates that
we want the maximum radius which will be
the blue radius but if you wanted to
just see things that are close to you
you could pass in a specific radius note
that it's radius squared we have some
interesting conventions with how we deal
with radi in the code um but radius
squared essentially just means if you
want to look for two tiles away you
would pass in
four
um but so that's this basic stuff um in
here and then we check okay if there any
enemy robots nearby then we set this
indicator string where we say there are
your to be robots so let's see if that's
working let's go to a point in the code
where there are Bots interacting so here
we go we can see this bot the the white
duck is in its Vision radius so we can
see it says there are by enemy robots in
the indicator string this is again
useful debug
information um and if this is true then
we get all the locations of our enemy
robots so we re instantiate a new map
location array um and then for each
enemy robot we set its location to its
location and then finally here's a bit
of an example of how you can communicate
with your other bots so this is the
shared array so um if you look in the
spec essentially the way we do
communication between inter inter
communication between Bots is we have
one giant big array of integers and you
can write values into them so anyone is
allowed to read and write values into
this array so the array is only for your
team so each team has their own array
and you use this to communicate and send
values around so here what we do we
check if we're allowed to write this
value into index zero into our shared
array if we are we write it um and if we
wanted to read it somewhere else we can
call RC Reet array at index zero so if
the first spot that runs writes this
array value and let's say there's five
robots nearby then the next spot runs
they can read this value and they'll see
that five so like I mentioned this is
the only way we can share values between
robots um but yeah so that's our basic
robot player so when that's done um
we'll run this finally code get here and
then the turn will happen again each
turn um yeah that's uh that's robot any
questions about that
yes that's a great question so yes I
should probably talk about that so um in
your Bot you're not allowed to have
infinite computation so it talks a
little bit about about this in the spec
but essentially the way Java works is
you can think of each each line of code
you write has some amount of um it's
called bite code which is like little um
atoms of instructions that run on the
computer so the way we can we calculate
um computation is we track how many of
those have run um and so different
methods have different costs associated
with them and so certain methods are
more expensive and as a result you
cannot run very like um algorithmically
complex or bit large algorithms and
otherwise you'll run out of um
computation for that bot so bot runs out
of computation for their turn their code
will pause and resume next turn so which
is kind of dangerous because you might
be in a state that something has gone
wrong so if you want to see how much uh
how much each bu code sorry how much bu
code each method costs
um here's some information here so you
can see it in the Java doc so I don't
know if it shows it in the IDE mine's
not really seem to be working right now
but in the Java docs it does tell you
how much B code cost each one is so here
one one one one one
155 so this is good information um if
you're worried about that and you can
always check how much B code your Bot is
using by clicking on it it tells you how
much Bode was used for that turn and
it's a little indicator here and so you
can see if you're approaching your limit
I think this year we have 25,000 is the
limit for each turn which seems like a
lot but you can definitely fill it up
very
quickly um but yeah so again Java do is
your friend make sure you're reading
that um any other questions about Java
do or example
bot awesome well if you have any more
questions feel free to
Absolutely, here’s an explained breakdown of what was discussed in this gigantic introductory Battlecode lecture. We'll simplify and organize this into understandable sections:
Introduction to Battlecode and the Environment Setup
Welcome to Battlecode Lecture Series - This is Lecture 2 of the series. It focuses on using Java for the game and setting up a working environment for programming your bot.
What is Battlecode?
Battlecode is a strategy-based programming competition where you build a bot using Java. This bot competes in a virtual game world against bots from other teams.
Setting Up Your Environment:
Step 1: Register at the website (play.code.org) to submit your bot for tournaments and scrimmaging.
Step 2: Download and install Java Development Kit (JDK), specifically version 8. A specific version is necessary for compatibility reasons.
Step 3: Download the Battlecode Scaffold from the GitHub repository. The scaffold is the essential framework (starter code) for your bot.
Extract the scaffold (a zipped folder) into its own location.
Step 4: Set up the integrated development environment (IDE) like Eclipse or IntelliJ to work with the game. Specific configurations (like setting Java 8 paths) need to be done for both IDEs.
Setting up the Client:
The "client" is a visualization tool that shows your bot running in-game.
Configuring the client allows you to test your bot’s matches and interact with their stats, results, or replay matches across different maps.
Key Tools/Technologies Mentioned:
Gradle: A tool used to build Java projects, seamlessly integrated into the IDEs.
JVM Settings: Make sure your bot runs with Java 8 settings across all the tools.
Understanding Java Concepts
Before jumping into the game logic, a brief overview of Java programming was covered. This is critical for people new to Java or transitioning from other languages like Python.
Overview of Java Programming
Key Basics:
Every Java program is defined by a class.
Execution starts in the public static void main(String[] args) method.
Java is strongly typed, meaning all variables should be declared with a specific data type (e.g., int, double, String, etc.).
Important Java syntax, such as System.out.println() for printing, was explained.
Static Context:
A static method (like main()) doesn't require an instance of the class to run.
When defining helper methods for your bot, like test() in the example, it may also have to be static.
Integer Types in Java:
Regular integers (int) have size limits (e.g., can’t store numbers larger than ~2 billion or smaller than ~-2 billion).
Use long if larger numbers have to be stored.
Example problem: Integer overflow could occur when squaring huge numbers (e.g., 100,000 squared is too large for a typical int).
Working with Arrays:
Arrays in Java store items sequentially and require predefined sizes.
To dynamically handle collections (e.g., resizing), use ArrayLists instead.
Java Equality Concepts:
Important distinction between == and .equals():
== compares whether two objects are stored in the same memory location.
.equals() compares object values (e.g., two different instances of the String “hello” will be considered equal using .equals()).
Loops:
Standard for loops, enhanced for loops (for (String item : array)), and dynamic iteration of ArrayLists were demonstrated.
The Provided Battlecode Bot Player
Now comes the real fun! After the environment setup and Java review, the Battlecode bot scaffolding code (RobotPlayer.java) was explained.
How the Bot Works
Your bot's logic lives in the run method inside the RobotPlayer class. Every robot on the map executes the run method independently in a while-loop that acts as the robot's lifecycle.
Key points covered:
Structure of the Bot Code:
Main execution happens in a loop: while (true). This ensures your bot "operates" every turn without shutting down.
A try-catch block handles game-specific errors (e.g., trying to move into a wall). Errors are prevented from crashing your bot.
Important Variables:
Useful variables include turnCount (to track the current turn) and shared data structures (like directions[] for quick navigation).
Game Logic Flow:
Conditional checks are made during every turn:
Is the bot spawned? Spawn it in a random valid location if not.
If the bot picks up a flag, record the action.
Navigation and Movement:
Use the bot's current location (rc.getLocation()) to calculate the direction to move via directionTo(targetLocation).
Random Movement: If no specific logic applies, just move in a random valid direction.
Combat Actions:
Attack any visible enemy robots nearby using rc.attack().
Flag-Orientation Logic:
If carrying an enemy flag, prioritize moving toward the allied spawn zone.
Communication with Shared Arrays:
Robots communicate with teammates via shared integer arrays using rc.writeSharedArray() and rc.readSharedArray().
Debugging Tools:
"Indicator Strings," dots, or drawn lines in the client are helpful for understanding what each bot is doing during gameplay. These visual tools can aid debugging strategies.
Performance and Bot Optimization
A critical part of the game and bot design is optimizing performance within its constraints:
Bytecode Constraints:
Bots have a computation limit for each turn (25,000 bytecode units). If exceeded, the bot will pause and resume in the next turn, which can be risky during critical decision-making.
Examining Bytecode Usage:
Tools in the client help track bytecode usage by each bot. Carefully managing how complex your algorithms are (e.g., avoiding overly heavy calculations like pathfinding on every turn) is key to success.
Efficiency Tips:
Use efficient pathfinding algorithms.
Avoid redundant computation and shared-array abuse.
Closing Notes
Next Lecture Preview:
Future lectures will dive deeper into designing introductory bots and strategies.
A focus will also be placed on advanced techniques like communication between bots.
Resources Available:
JavaDocs and official specifications detail all the game functions and mechanics you’ll need.
The provided scaffold forms a strong base to start building intelligent bots.
To summarize, this lecture introduced participants to setting up the Battlecode environment, reviewing Java essentials, and understanding how the scaffold bot works. It laid the foundation for bot building and optimization in this competitive, technical game world!
It seems you’ve included bits of broken Java code, and I’m here to clean it up, explain it, and provide a corrected and functional version of it. Let's break it down logically:
What Does This Code Aim to Do?
Compare two MapLocation objects to check if they are equal.
Demonstrate proper comparison techniques for objects in the Battlecode universe.
Use rc.getLocation() and mapInfo.getSpawnZoneTeam() appropriately in context.
Corrected and Functional Code
java
import battlecode.common.*;
import battlecode.world.*;
public class Comparison {
public static void main(String[] args) {
// Example coordinates for MapLocation
int x1 = 5, y1 = 5; // Example x, y coordinates
int x2 = 5, y2 = 5; // Example of two locations with same coordinates
// Instantiate two MapLocation objects with specified coordinates
MapLocation loc1 = new MapLocation(x1, y1);
MapLocation loc2 = new MapLocation(x2, y2);
// Proper way to check if two MapLocations are equal
boolean areTheyEqual = loc1.equals(loc2); // Correct use of .equals()
System.out.println("Is " + loc1 + " equal to " + loc2 + "? " + areTheyEqual);
// Example RobotController comparison with MapLocation
RobotController rc = null; // Placeholder, this would be provided by the game engine
if (rc != null) {
if (rc.getLocation().equals(loc1)) {
System.out.println("Robot is at location: " + loc1);
}
}
MapInfo mapInfo = null; // Placeholder: should be obtained from game state in actual usage
if (mapInfo != null) {
// Example: Comparing team spawn zones
if (rc.getTeam().ordinal() + 1 == mapInfo.getSpawnZoneTeam()) {
System.out.println("This mapInfo location's spawn zone belongs to our team!");
}
}
}
}
Explanation of Key Fixes:
1. Correct MapLocation Declaration
The original code written as new Map Location(x1, y1) had incorrect spacing and syntax (Map Location → MapLocation).
Fixed as MapLocation loc1 = new MapLocation(x1, y1);. This properly creates the objects.
2. Fixing boolean areTheyEqual Syntax
The original line boolean areTheyEqual loc1.equals(loc2): was incorrect because:
5. Enum Comparison (rc.getTeam() and mapInfo.getSpawnZoneTeam())
The line rc.getTeam().ordinal()+1 == mapInfo.getSpawnZoneTeam() assumes getSpawnZoneTeam() is integer-based.
Enums like Team should be compared predictably (e.g., ordinal values for numeric comparison or using specific methods if Battlecode provides such).
The fix clarifies its intended purpose: adding +1 to align enum values in some custom game logic.
Key Notes to Keep in Mind While Coding in Battlecode:
Object Comparison Rules:
Use .equals() for object comparison (e.g., MapLocation, String, or ArrayList).
Use == only for primitive data types (e.g., int, double) or Enum references.
Printing Values:
Concatenate strings properly when using System.out.println().
Avoid Null Pointers:
The placeholders rc = null and mapInfo = null are simulation-only.
For actual Battlecode bots, these objects (e.g., RobotController rc) are directly provided by the game engine, and you don’t have to instantiate them manually.
Team Comparison:
Battlecode's Team is an enum type. Use .ordinal() carefully or rely on custom methods provided by the engine (like rc.getTeam()).
Output Example
If loc1 and loc2 have identical coordinates (5, 5), the program would output:
code
Is (5, 5) equal to (5, 5)? true
Robot is at location: (5, 5)
This mapInfo location's spawn zone belongs to our team!
This confirms proper MapLocation equality, robot location identification, and spawn zone checking.
Feel free to run similar Battlecode-specific code based on this template and adjust it for practical gameplay integration!
Teaching this topic effectively to a class involves good preparation, clear communication, and interactive engagement. Here's a step-by-step guide you can follow to teach the concepts in your MapLocation comparison program to students new to these ideas:
1. Preparation
Before entering the classroom, make sure you have:
A clear breakdown of the concepts you're teaching:
Explanation of MapLocation, equals() vs ==, how objects are compared in Java, and enums (Team in this case).
Practical use-case examples to show why these comparisons are essential in the Battlecode game.
A detailed lesson plan, as structured below.
A prepared demonstration setup:
Ensure your IDE and Battlecode scaffold are ready to run.
Create visual aids to explain key points (such as slides/diagrams).
Have example outputs ready to show.
2. Teaching Strategy
a. Start with Context
Begin by giving the students a reason to care about what they’re learning. For instance:
Introduce the Battlecode game scenario: Explain that our goal is to control robots on a game map. To make critical decisions, robots often need to:
Compare locations (e.g., "Am I at the flag location?")
Check team ownership of spawn zones.
Motivate the lesson by stressing the importance of proper object comparison to avoid logic errors in their bot.
b. Use Step-by-Step Explanation
Step 1: Introduce the Problem
Write incorrect code on the board or IDE first (e.g., rc.getLocation() == loc1) and ask:
"What do you think this does?"
Discuss misconceptions about == and .equals() in Java.
Step 2: Discuss Java Object Comparison
Use a simple analogy to explain the difference between == and .equals():
==: "Do these two pieces of paper point to the exact same house?" (memory locations).
.equals(): "Are the houses these two papers point to the same?" (object values).
Write correct and incorrect examples for MapLocation and ask the class to predict outputs:
java
MapLocation loc1 = new MapLocation(5, 5);
MapLocation loc2 = new MapLocation(5, 5);
System.out.println(loc1 == loc2); // What will this print? (False!)
System.out.println(loc1.equals(loc2)); // What will this print? (True!)
Step 3: Relating it to Battlecode
Explain that in Battlecode bots, MapLocation is important when:
Determining where the bot is (rc.getLocation()).
Comparing team territories using methods like mapInfo.getSpawnZoneTeam().
3. Make It Interactive
Interactive learning improves engagement and retention of material. Here's how you can involve your students:
a. Ask Questions and Clarify Misconceptions
Pause after each section and ask questions:
"Why do you think loc1 == loc2 returns false?"
"What happens if we forget to use .equals()?"
"Why do you think Battlecode uses enums like Team?"
Encourage students to discuss these questions with a partner or share their thoughts with the class.
b. Hands-On Coding: Live Demonstration
Walk through the corrected Comparison program step by step in an IDE with clear commentary:
Write code from scratch and explain why you're using .equals() instead of ==.
Use print statements or the debugger to show actual outputs for MapLocation comparisons.
Let students guess what outputs they'll see when you run the code.
c. Small Challenges
Give students tasks in the middle of the lesson to apply what they’re learning:
Task 1: Write a method that tells whether two MapLocation objects are equal.
Task 2: Write and debug a fragment that checks if a bot is standing on an enemy flag location.
Discuss their solutions together.
4. Incorporate Visual Aids
For abstract programming concepts—like comparisons, memory references, or enums—visuals can be very helpful.
Example Visual Diagram:
For == vs .equals():
Draw two MapLocation objects in memory (showing they point to distinct blocks in memory).
Highlight that .equals() checks X and Y values, while == checks memory locations.
Example Enum Comparison:
Show the Team enum as possible integer mappings in memory:
TeamA: ordinal = 0
TeamB: ordinal = 1
Demonstrate the +1 logic in the spawn zone comparison (e.g., Team ordinal values aligning with Battlecode logic).
5. Reinforce Understanding
After completing the explanations and hands-on challenges:
Summarize key takeaways:
Use .equals() for objects; use == for primitive types or memory references.
Understand enums (Team, ordinal values) and their comparisons.
Troubleshoot common null pointer issues in Battlecode (e.g., rc or mapInfo being null).
Encourage questions:
Discuss any concepts that remain unclear or need further examples.
6. Test Their Knowledge
End the session with a small quiz or exercise that ensures they understand:
If given MapLocation objects loc1 and loc2, how do you compare them?
What happens if you use == instead of .equals()?
Why is rc.getTeam().ordinal() + 1 == mapInfo.getSpawnZoneTeam() used in Battlecode?
7. Bonus Engagement Ideas
For more involvement:
Example Battlecode-Specific Problem:
Ask them to write a method that checks if a robot has reached a specific spawn zone and if it's their home team spawn zone using proper comparisons.
Gamify Learning:
Create a competition where students write a quick method to check team flags using the enum comparison logic given.
8. Conclusion
Wrap up by revisiting the real-world importance of the lesson:
Properly understanding object comparison ensures bots behave reliably in actual games, preventing unintended crashes or bad decisions.
Mastering Java fundamentals like .equals() vs == and enum usage will help them not only in Battlecode, but also in professional development.
By combining guided instruction, interactive activities, and meaningful connections to the Battlecode game, you’ll create an engaging and effective learning experience. Good luck teaching!
Why Do We Need ArrayList in Battlecode?
In Battlecode, ArrayList often plays an essential role because of the dynamic nature of the robot's decisions and its environment. Unlike fixed-size arrays (int[] or Object[]) in Java, which have a predetermined size, ArrayList provides a flexible data structure that can grow or shrink dynamically as your bot encounters new situations. This makes it ideal for certain use cases in Battlecode.
Here’s a detailed explanation of why ArrayLists are important in Battlecode along with examples of when to use them.
1. Limitations of Regular Arrays
A fixed-size array like int[] or MapLocation[] is static and cannot accommodate:
Dynamic Sizes:
You need to know the exact number of elements at compile-time or initialization.
If the number of enemy robots or targets changes, it’s cumbersome to update the array.
Adding or Removing Elements:
With regular arrays, you cannot simply add or remove elements. You’d need to create a new array and copy all elements manually, which costs time and creates inefficiencies.
ArrayList solves these problems by dynamically resizing itself as you add or remove elements.
2. Common Use Cases for ArrayList in Battlecode
Here are some scenarios where ArrayList is essential in Battlecode programming:
a) Storing Robots Nearby
Your robots need to dynamically track lists of nearby friendlies or enemies to make decisions:
You use rc.senseNearbyRobots() to detect all robots within a radius.
This might return a varying number of robots each turn (depending on gameplay dynamics).
Storing these results in an ArrayList helps you easily manage and iterate through them.
Example:
java
RobotInfo[] nearbyRobots = rc.senseNearbyRobots(); // Returns a fixed-sized array
ArrayList<RobotInfo> enemies = new ArrayList<>();
for (RobotInfo robot : nearbyRobots) {
if (robot.getTeam() != rc.getTeam()) { // Check if it's an enemy
enemies.add(robot);
}
}
// Now you have a dynamically growing list of enemies!
for (RobotInfo enemy : enemies) {
System.out.println("Spotted enemy at: " + enemy.getLocation());
}
With ArrayList:
You separate out enemy robots cleanly without worrying about pre-allocated array sizes.
If no enemies are nearby, your list just stays empty—no wasted memory.
b) Dynamically Collecting Map Locations
Your robots often explore or track specific points on the map (like areas to visit, resource locations, flag locations, etc.). Since these locations change over time, a flexible structure like ArrayList is ideal for storing them.
Example:
Let’s say the bot searches for all nearby flag locations and stores them in a list to find the closest one:
java
MapLocation[] allFlags = rc.senseNearbyFlags(); // Fixed-size array
ArrayList<MapLocation> flagsToVisit = new ArrayList<>();
for (MapLocation flag : allFlags) {
flagsToVisit.add(flag); // Add to the dynamic list
}
// Simulate "visiting" the first flag (for example purposes):
if (!flagsToVisit.isEmpty()) {
MapLocation target = flagsToVisit.remove(0); // Removes the first element
System.out.println("Visiting flag at: " + target);
}
Why ArrayList is useful here:
You don’t know how many flags will be detected in each turn.
Flags might get collected or captured, so you can remove them easily.
c) Managing Task Queues
Robots often follow strategies where one task must be completed before moving on to the next task (like resource collection or attacking enemies). Using ArrayList as a task queue helps to manage this sequence efficiently.
Example:
java
ArrayList<String> taskQueue = new ArrayList<>();
// Add tasks dynamically
taskQueue.add("Collect crumbs at (5,5)");
taskQueue.add("Move to spawn zone");
taskQueue.add("Capture enemy flag");
// Execute the first task
if (!taskQueue.isEmpty()) {
String currentTask = taskQueue.remove(0); // Remove and get first task
System.out.println("Performing task: " + currentTask);
}
Why ArrayList is useful:
Dynamic addition and removal of tasks make it easy to manage robot behavior.
No size constraints allow your bot to adapt to changing strategies without requiring rigid structures.
d) Sharing Information Between Robots
When multiple robots collaborate (e.g., distributing tasks or alerting of enemy presence), you may need to dynamically build lists of coordinates, tasks, or objects to share via the shared array. ArrayList makes this process easier.
For example:
java
ArrayList<MapLocation> resourceLocations = new ArrayList<>();
// Gather resource locations
MapInfo[] sensedMapInfo = rc.senseNearbyMapInfo();
for (MapInfo info : sensedMapInfo) {
if (info.containsResource()) {
resourceLocations.add(info.getLocation());
}
}
// Communicate the list
for (int i = 0; i < resourceLocations.size() && i < rc.getSharedArrayLength(); i++) {
rc.writeSharedArray(i, encodeLocation(resourceLocations.get(i))); // Encoding location
}
3. Advantages of Using ArrayList
Compared to Arrays:
Dynamic Sizing:
Automatically resizes to fit added elements, unlike arrays.
No need to guess or predefine a size.
Ease of Use:
Provides methods like add(), remove(), contains(), and indexOf(), making it easier to manipulate data.
For example:
java
enemies.add(robot); // Add an enemy robot to the list
enemies.remove(robot); // Remove the specific enemy robot
System.out.println(enemies.contains(robot)); // Check if robot is in the list
Performance Tradeoff:
While ArrayList manages resizing and dynamic storage well, it slightly sacrifices speed compared to primitive arrays (due to resizing operations and object wrapping).
For scenarios like managing nearby robots or map zones, the flexibility of ArrayList usually outweighs its minor performance cost.
4. When NOT to Use ArrayList
While ArrayList is powerful, it isn’t always the best choice, especially if:
Performance is critical and the data size is fixed:
Regular arrays like RobotInfo[] or MapLocation[] are faster for fixed-size or read-only lists due to fewer overheads.
Real-time constraints:
If the ArrayList grows or shrinks too frequently (e.g., adding/removing elements 1000+ times in one turn), this can lead to expensive resizing operations and excessive computation.
Large Maps and Limits:
If you're collecting too much data dynamically (e.g., every possible map tile), you might max out memory unnecessarily.
In these cases, use arrays or capped ArrayList sizes.
Conclusion
In Battlecode, as robots manage ever-changing environments and dynamic gameplay data, ArrayList shines as a versatile and flexible tool. It lets your bots adapt in real-time to tasks, locations, enemy strategies, and more. While you may still use regular arrays for extremely strict performance needs, the benefits of ArrayList—like dynamic resizing, easy additions/removals, and being iterable with enhanced for loops—make it indispensable for most bot logic.
Teaching Tip
When explaining ArrayList to a class:
Relate it to real-life examples:
Imagine writing a "to-do list" (ArrayList: grows and shrinks as tasks change) vs trying to manage a fixed piece of paper (array: static size).
Provide code exercises:
Ask students to:
Filter nearby robots into separate ArrayLists (one for enemies, one for allies).
Create a list to visit map locations and dynamically remove them as they’re visited.
Emphasize trade-offs:
Let students understand when to use ArrayList and when regular arrays are better for speed and simplicity.
You'll foster an appreciation for its usability while training them to recognize the right tool for each problem!