Sarven Sentry Uh Oh

# Use different colored flags to perform different tasks.

loop:
    flagGreen = self.findFlag("green")
    flagBlack = self.findFlag("black")
    xg = flagGreen.pos.x
    yg = flagGreen.pos.y
    xb = flagBlack.pos.x
    yb = flagBlack.pos.y
    # If there's a flagGreen...
    if flagGreen:
        # Build a fence at flagGreen's position.
        self.buildXY("fence", xg, yg)
        # Pick up the flag!
        self.pickUpFlag(flagGreen)
    # If there's a flagBlack...
    if flagBlack:
        # Build a fire-trap at flagBlack's position.
        self.buildXY("fire-trap", xb, yb)
        # Pick up the flag!
        self.pickUpFlag(flagBlack)
    # Move back to the center.
    self.moveXY(43, 31)
    

My guy first builds the fence/trap in the middle then he moves to the flag. WHAT AM I DOING WRONG

When I run your code, I actually get an error before placing any flag, because it tries to define your xg/yg/xb/yb variables immediately at the start, when there are no flags and thus their position doesn’t exist and is null. You can’t define a variable as flagGreen.pos.x if there is no green flag, because then your green flag doesn’t have any coordinates.

You could either define the variables inside the if: for each flag (so that they are defined only when the flag actually exists), or, more simply, you could simply build at (flag.pos.x, flag.pos.y) rather than using variables.

So basically, remove your 4 variables defined at the start, and instead either do this:

if flagGreen:
    xg = flagGreen.pos.x
    yg = flagGreen.pos.y
    self.buildXY("fence", xg, yg)
    self.pickUpFlag(flagGreen)
if flagBlack:
    xb = flagBlack.pos.x
    yb = flagBlack.pos.y
    self.buildXY("fire-trap", xb, yb)
    self.pickUpFlag(flagBlack)

or this:

if flagGreen:
    self.buildXY("fence", flagGreen.pos.x, flagGreen.pos.y)
    self.pickUpFlag(flagGreen)
if flagBlack:
    self.buildXY("fire-trap", flagBlack.pos.x, flagBlack.pos.y)
    self.pickUpFlag(flagBlack)

Then it should work. I had problems like those a lot too. It’s a good idea to define variables as late as possible in most cases. Sometimes you know immediately you’ll need a variable, but it’s easy to forget that you can’t actually make one until the thing it refers to exists!