Quote:
Originally Posted by catsec
My two questions are:
1. Passing the size of 200 as an argument to the drawArena method was a requirement, did I do that correctly with lines 14, 16, 18 and 59? I commented/bolded the lines for ease of visibility.
The scoping rules in Python can generate some surprises:
Code:
size = 200
def f():
print(size)
f()
>> 200
but...
Code:
size = 200
def f(size):
print(size)
f()
>>> Traceback (most recent call last):
TypeError: f() missing 1 required positional argument: 'size'
So, you have to be careful.
Quote:
2. Is there anything that's blatantly inefficient, or wrong about my code? I improved my drawArena function with a for loop, instead of hard coding the square. I'm unsure if the forward function is excessive with all the if statements, but it works fine so I think it's good. Just want to double check though.
When you find yourself copy/pasting code, you should be thinking about how you can abstract the function. You have the exact same thing in the code. You also have mixed ideas working, seeming to imply forward movement involves death.
I would move all of the copy / paste functions to its own function, like so:
Code:
def dead ():
snakeTurtle.penup()
snakeTurtle.goto(0,0)
snakeTurtle.pendown()
snakeTurtle.write("Dead")
print("Dead")
window.ontimer(quit, 2500)
def forward():
snakeTurtle.forward(25)
if snakeTurtle.xcor() >= 100:
dead()
if snakeTurtle.xcor() <= -100:
dead()
if snakeTurtle.ycor() >= 100:
dead()
if snakeTurtle.ycor() <= -100:
dead()
That reveals more patterns and generalities. As you have it written, you can break it down to something much simpler:
Code:
def dead ():
snakeTurtle.penup()
snakeTurtle.goto(0,0)
snakeTurtle.pendown()
snakeTurtle.write("Dead")
print("Dead")
window.ontimer(quit, 2500)
def forward():
snakeTurtle.forward(25)
if abs(snakeTurtle.xcor()) == 100 or abs(snakeTurtle.ycor()) = 100:
dead()
But I don't really like this either. Why? Because the walls are hard-coded in the function. At this point, you may consider finding the edges. The following tries to demonstrate this (I don't have turtle installed, so nothing is tested, you'll have to debug this yourself):
Code:
TOP = 100
RIGHT = 100
LEFT = -100
RIGHT = -100
def dead ():
snakeTurtle.penup()
snakeTurtle.goto(0,0)
snakeTurtle.pendown()
snakeTurtle.write("Dead")
print("Dead")
window.ontimer(quit, 2500)
def forward():
snakeTurtle.forward(25)
if (snakeTurtle.xcor() == RIGHT or
snakeTurtle.xcor() == LEFT or
snakeTurtle.ycor() == TOP or
snakeTurtle.ycor() == BOTTOM):
dead()
forward()
The CAPS variables means "global" variable in this code. Be sure that you aren't doing mutations in your functions.