【问题标题】:Update the score when two turtles collide两只海龟碰撞时更新分数
【发布时间】:2019-09-27 03:27:11
【问题描述】:
  1. 我正在做一个任务,我必须编写一个小游戏。当乌龟与屏幕上的一个点(虫子)发生碰撞时,它会在左上角的得分值上加一个点,并将虫子传送到另一个随机点。当它们发生碰撞时,我无法更新分数。

  2. 我尝试将分数更新放在游戏循环中,但没有奏效,因为它一直告诉我该值未定义。我尝试用一​​个全局值来解决这个问题,但这并没有做任何事情:

    import turtle
    import math
    import random

    #Set up the constants for the game.
    WINDOW_HEIGHT = 300
    WINDOW_WIDTH = 300
    FORWARD_STEP = 10       #how much does the turtle move forward
    TURN_STEP = 30          #how much does the turtle turn (in degrees)
    SHRINK_FACTOR = 0.95     #how much does the turtle shrink when it moves 
    DEATH_WIDTH = 0.05       #the size at which you stop the game because the user lost

    COLLISION_THRESHOLD = 10;#we say that two turtles collided if they are this much away
                            #from each other

    #Define functions

    def game_setup():
            '''set up the window for the game, a bug and the player turtle '''

            #create the screen
            wn = turtle.Screen()
            wn.screensize(WINDOW_HEIGHT,WINDOW_WIDTH)
            wn.bgcolor("light green")

            #Create player turtle
            player = turtle.Turtle()
            player.color("blue")
            player.shape("turtle")
            player.penup()
            player.setpos (random.randrange(1,301), random.randrange(1,301))

            #create a bug
            bug1 = turtle.Turtle()
            bug1.color("black")
            bug1.shape("circle")
            bug1.shapesize(stretch_wid=0.2, stretch_len=0.2)
            bug1.penup()
            bug1.speed(0) #the bug is not moving
            bug1.setposition(-200, 200)

            #create score turtle
            score_keeper = turtle.Turtle()
            score_keeper.hideturtle()
            score_keeper.penup()
            score_keeper.setposition (-400,360)
            score = 0
            scorestring = "Score: %s" %score
            score_keeper.write(scorestring, False, align="left", font=("Arial",14, "normal"))



            return (wn,player,bug1,score_keeper)

    def is_collision (player, bug1):
            distance = (math.sqrt((player.xcor()-bug1.xcor())**2 + (player.ycor() - bug1.ycor())**2))
            if distance < COLLISION_THRESHOLD:
                    return True
            else:
                    return False




    def main():


            #set up the window, player turtle and the bug
            (wn,player,bug1,score_keeper) = game_setup()

            #make the arrow keys move the player turtle
            bindKeyboard(player)

            #Set this veriableto True inside the loop below if you want the game to end.
            game_over = False

            player_width = get_width(player)

            #This is the main game loop - while the game is not over and the turtle is large enough print the width of the turtle
            #on the screen.
            while not game_over and player_width > DEATH_WIDTH:

                    #your collision detection should go here

                    if is_collision (player, bug1):
                            bug1.setpos (random.randrange(1,301), random.randrange(1,301))
                            player.shapesize(stretch_wid=1, stretch_len=1)



                    player_width = get_width(player)
                    player.showturtle()
                    print(player_width)

            print("Done")   
            wn.exitonclick()

    main()

  1. 这是大部分代码。我想要它做的就是当is_collision() 函数发生时,它将score 的值加1,然后score_keeper 乌龟在窗口中打印该值。

【问题讨论】:

    标签: python turtle-graphics python-3.7


    【解决方案1】:

    当它们发生碰撞时,我很难更新分数。

    我在下面对您的代码进行了精简返工(替换您遗漏的方法),以展示如何更新屏幕上的分数。像这样的代码不应该有一个明确的主循环,因为它都是事件驱动的,而是应该调用turtle的主事件循环:

    from turtle import Screen, Turtle
    from random import randrange
    from functools import partial
    
    # Set up the constants for the game.
    WINDOW_WIDTH, WINDOW_HEIGHT = 500, 500
    FORWARD_STEP = 10  # how much does the turtle move forward
    TURN_STEP = 30  # how much does the turtle turn (in degrees)
    COLLISION_THRESHOLD = 10  # we say that two turtles collided if they are this much away from each other
    CURSOR_SIZE = 20
    FONT = ('Arial', 14, 'normal')
    
    # Define functions
    
    def is_collision(player, bug):
        return player.distance(bug) < COLLISION_THRESHOLD
    
    def random_position(turtle):
        scale, _, _ = turtle.shapesize()
        radius = CURSOR_SIZE * scale
        return randrange(radius - WINDOW_WIDTH/2, WINDOW_WIDTH/2 - radius), randrange(radius - WINDOW_HEIGHT/2, WINDOW_HEIGHT/2 - radius)
    
    def forward():
        global score
    
        player.forward(FORWARD_STEP)
    
        if is_collision(player, bug):
            bug.setposition(random_position(bug))
    
            score += 1
            score_keeper.clear()
            score_keeper.write(f"Score: {score}", font=FONT)
    
    # Set up the window for the game, a bug and the player turtle.
    
    # Create the screen
    screen = Screen()
    screen.setup(WINDOW_WIDTH, WINDOW_HEIGHT)
    screen.bgcolor('light green')
    
    # Create score turtle
    score_keeper = Turtle(visible=False)
    score_keeper.penup()
    score_keeper.setposition(-230, 230)
    
    score = 0
    score_keeper.write(f"Score: {score}", font=FONT)
    
    # Create a bug
    bug = Turtle('circle', visible=False)
    bug.shapesize(4 / CURSOR_SIZE)
    bug.penup()
    bug.setposition(random_position(bug))
    bug.showturtle()
    
    # Create player turtle
    player = Turtle('turtle', visible=False)
    player.color('blue')
    player.speed('fastest')
    player.penup()
    player.setposition(random_position(player))
    player.showturtle()
    
    # make the arrow keys move the player turtle
    screen.onkey(partial(player.left, TURN_STEP), 'Left')
    screen.onkey(partial(player.right, TURN_STEP), 'Right')
    screen.onkey(forward, 'Up')
    
    screen.listen()
    screen.mainloop()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-19
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多