mardi 10 avril 2018

Python: How come the math operators won't work?

I've been following a tutorial that shows beginners how to make a "Space Invaders" game. I mostly just wanted a way to play around with the turtle graphics or something of the sort. Everything was going smoothly until I noticed that my if statement, founded where I defined my move_left function, does not work. The problem however is not the if statement itself. It is that any math operation I try to do under it just gets completely ignored by the program with no error messages or anything. I even attempted to make a print statement under the if statement just to see rather or not the actual statement was responsive and saw that indeed, the statement printed as I planned. So what gives? How come I cannot do any math equations or anything of the like under those two functions?

So, here is the code that I had followed below:

import turtle
import os

def main():
    #Set up the screen

    wn = turtle.Screen()
    wn.bgcolor("black")
    wn.title("Space Invaders")

    #Draw Border
    border_pen = turtle.Turtle()
    border_pen.speed(0)
    border_pen.color("white")
    border_pen.penup()
    border_pen.setposition(-300, -300)
    border_pen.pendown()
    border_pen.pensize(3)

    for side in range (4):
        border_pen.fd(600)
        border_pen.lt(90)
    border_pen.hideturtle()

    #create the player turtle

    player = turtle.Turtle()
    player.color("blue")
    player.shape('triangle')
    player.penup()
    player.speed(0)
    player.setposition(0, -250)
    player.setheading(90)


    #Player controls

    playerspeed = 15

    def move_left():
        x = player.xcor()
        x -= playerspeed
        player.setx(x)
        print(x)
        if x < -280:
            print("Reached") #It is here I tested rather or not the if statement 
                             #above works, which it does
            x = -280 #The following code here will not take effect. I tried all
                     #of different signs to use. Nothing happens. Not even an 
                     #error

    def move_right(): #I did not put the if statement here since I noticed the
                      #problem with the left side first
        x = player.xcor()
        x += playerspeed
        player.setx(x)
        if x > 280:
            x = 280

    turtle.listen()
    turtle.onkey(move_left, "Left")
    turtle.onkey(move_right, "Right")

    turtle.mainloop()

main()

Aucun commentaire:

Enregistrer un commentaire