简体   繁体   中英

Python -- Why are my if statements not running inside while loop?

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()   

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM