代码之家  ›  专栏  ›  技术社区  ›  Tornadosalama

Turtle模块.pos()函数出现问题

  •  0
  • Tornadosalama  · 技术社区  · 1 年前

    我正在做一个蛇游戏,有一些苹果你需要捡起来。

    但有时当的前部 蛇能检测到它是否在触摸苹果——有时它不会检测到苹果——甚至当它在苹果上面的时候。请帮忙。

    当蛇的前部碰到苹果时,我预计它会传送到不同的位置。 我想尽一切办法把它修好了。

    from turtle import Turtle
    
    from turtle import Screen
    
    import time
    
    import random
    
    def screen_setup():
        screen.bgcolor("black")
        screen.title("Snake Game")
        screen.listen()
    
    def snake_setup():
        snake.shape("square")
        snake.color("green")
        snake.speed("fastest")
        snake.penup()
    
    def turn_east():
        snake.setheading(0)
    
    def turn_north():
        snake.setheading(90)
    
    def turn_west():
        snake.setheading(180)
    
    def turn_south():
        snake.setheading(270)
    
    def check():
        apple_x = int(apple.xcor())
        apple_y = int(apple.ycor())
    
        snake_x = int(snake.xcor())
        snake_y = int(snake.ycor())
    
    
        if snake_y == apple_y and snake_x == apple_x:
            return True
        else:
            return False
    
    
    def apple_first_spawn():
        apple_x = int(random.randrange(60, 301, 20))
        apple_y = int(random.randrange(60, 301, 20))
        apple.goto(apple_x, apple_y)
    
    def apple_spawn():
        apple_x = int(random.randrange(60, 301, 20))
        apple_y = int(random.randrange(60, 301, 20))
        apple.goto(apple_x, apple_y)
    
    
    
    snake = Turtle()
    snake_setup()
    
    screen = Screen()
    screen_setup()
    
    text = Turtle()
    text.speed("fastest")
    text.hideturtle()
    text.penup()
    text.color("white")
    text.sety(screen.window_width() / 2 - 150)
    text.write(f"score = 0", move=False, align='center', font=('Arial', 15, 'normal'))
    
    apple = Turtle()
    apple.shape("circle")
    apple.speed("fastest")
    apple.penup()
    apple.color("red")
    apple_first_spawn()
    
    loop = True
    cycle = 0
    score = 0
    snake_parts = []
    got_apple = False
    apple_location = apple.pos()
    while loop == True:
        cycle += 1
        snake_stamp = snake.stamp()
        snake_parts.append(snake_stamp)
        if check() == True:
            apple_spawn()
            got_apple = True
            score += 1
            text.clear()
            text.write(f"score = {score}", move=False, align='center', font=('Arial', 15, 'normal'))
    
        if cycle > 3:
            if got_apple == False:
                snake.clearstamp(snake_parts[0])
                snake_parts.pop(0)
    
        got_apple = False
        snake.forward(20)
        time.sleep(0.1)
        screen.onkeypress(fun=turn_east, key="d")
        screen.onkeypress(fun=turn_west, key="a")
        screen.onkeypress(fun=turn_south, key="s")
        screen.onkeypress(fun=turn_north, key="w")
    
    screen.exitonclick()
    
    0 回复  |  直到 1 年前