Home > Software engineering >  Python -- Why are my if statements not running inside while loop?
Python -- Why are my if statements not running inside while loop?

Time:07-11

I'm new to python and decided to practice by building a game similar to snake with the turtle library. I was able to initiate the turtle to continually move forward with a while True loop, but now I'm having trouble with getting the turtle to break this loop to make turns. I have tried various different ways of writing my conditionals but I can't seem to figure out where the issue is. Thanks in advance!

import turtle

window = turtle.Screen()
snake = turtle.Turtle()
snake.speed(1)
snake.penup()


#Functions that move the snake:
def forward():
  while True:
    snake.forward(.7)

def left():
  snake.left(90)

def right():
  snake.right(90)

#Movement functions all put together: 
def movesnake():
    while True:
        entry = input()

        if entry == 'w':
          forward()

        if entry == 'a':
          left()

        if entry == 'd':
          right()
        

movesnake()   

CodePudding user response:

Try this approach to move:

def forward():
    turtle.forward(how-many-pixels-forward)

turtle.onkey(forward,'what-key-you-want-to-listen-to') #when key pressed call forward function 

https://www.geeksforgeeks.org/turtle-onkey-function-in-python/

The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.

turtle.onkey() This function is used to bind fun to the key-release event of the key. In order to be able to register key-events, TurtleScreen must have focus.

CodePudding user response:

You can try increasing the value of the forward function:

def forward():
  while True:
    snake.forward(5)

Take a look at this book

https://argentinaenpython.com/quiero-aprender-python/doma-de-serpientes-para-ninos_swfk-es-linux-0.0.4.pdf

  • Related