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:
xg = flagGreen.pos.x
yg = flagGreen.pos.y
self.buildXY("fence", xg, yg)
xb = flagBlack.pos.x
yb = flagBlack.pos.y
self.buildXY("fire-trap", xb, yb)
self.buildXY("fence", flagGreen.pos.x, flagGreen.pos.y)
self.buildXY("fire-trap", flagBlack.pos.x, flagBlack.pos.y)
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!