简体   繁体   English

如何重置海龟并擦除海龟图形中的文本?

[英]How to reset the turtles and erase the text in turtle graphics?

I made this turtle game我做了这个乌龟游戏

import turtle
import random
import time
from turtle import Turtle

# Window

window = turtle.Screen()
window.title("Turtle Race")
window.bgcolor("forestgreen")
turtle.color("white")
turtle.speed(0)
turtle.penup()
turtle.setposition(-140, 200)
turtle.write("Turtle Race", font=("Arial", 40, "bold"))

# Dirt

turtle.setposition(-400, -180)
turtle.color("chocolate")
turtle.begin_fill()
turtle.pendown()
turtle.forward(800)
turtle.right(90)
turtle.forward(300)
turtle.right(90)
turtle.forward(800)
turtle.right(90)
turtle.forward(300)
turtle.end_fill()

# Finish line

stamp_size = 20
square_size = 15
finish_line = 200

turtle.color("black")
turtle.shape("square")
turtle.shapesize(square_size / stamp_size)
turtle.penup()

for i in range(10):
    turtle.setposition(finish_line, (150 - (i * square_size * 2)))
    turtle.stamp()

for j in range(10):
    turtle.setposition(finish_line + square_size, ((150 - square_size) - (j * square_size * 2)))
    turtle.stamp()

turtle.hideturtle()


def play():

    # Turtle 1

    turtle1 = Turtle()
    turtle1.speed(0)
    turtle1.color("black")
    turtle1.shape("turtle")
    turtle1.penup()
    turtle1.goto(-250, 100)
    turtle1.pendown()

    # Turtle 2

    turtle2 = Turtle()
    turtle2.speed(0)
    turtle2.color("cyan")
    turtle2.shape("turtle")
    turtle2.penup()
    turtle2.goto(-250, 50)
    turtle2.pendown()

    # Turtle 3

    turtle3 = Turtle()
    turtle3.speed(0)
    turtle3.color("magenta")
    turtle3.shape("turtle")
    turtle3.penup()
    turtle3.goto(-250, 0)
    turtle3.pendown()

    # Turtle 4

    turtle4 = Turtle()
    turtle4.speed(0)
    turtle4.color("yellow")
    turtle4.shape("turtle")
    turtle4.penup()
    turtle4.goto(-250, -50)
    turtle4.pendown()

    time.sleep(1)    # pausing the game for 1 sec before game starts

    # Asking user to play

    print("Please choose one colour out of \nBlack \nCyan \nMagenta \nYellow ")
    user_bet = input("Place your bet on your any one colour turtle: ").upper()

    while not(user_bet == "BLACK" or user_bet == "CYAN" or user_bet == "MAGENTA" or user_bet == "YELLOW"):
        print("Please choose one colour out of \nBlack \nCyan \nMagenta \nYellow ")
        user_bet = input("Place your bet on your any one colour turtle: ").upper()

    # Initial distance covered by turtles

    tut1_len = 0
    tut2_len = 0
    tut3_len = 0
    tut4_len = 0

    # Moving the turtles

    for _i in range(145):

        tut1 = random.randint(1, 5)
        tut2 = random.randint(1, 5)
        tut3 = random.randint(1, 5)
        tut4 = random.randint(1, 5)

        turtle1.forward(tut1)
        tut1_len += tut1

        turtle2.forward(tut2)
        tut2_len += tut2

        turtle3.forward(tut3)
        tut3_len += tut3

        turtle4.forward(tut4)
        tut4_len += tut4

    # Deciding the winner

    result_dic = {"black": tut1_len, "cyan": tut2_len, "magneta": tut3_len, "yellow": tut4_len}
    winner = max(result_dic, key=lambda x: result_dic[x]).upper()

    turtle.penup()
    turtle.color("blue")
    if user_bet == winner:
        turtle.goto(-140, 50)
        turtle.write("You won the bet", font=("Arial", 30, "bold"))
    else:
        turtle.goto(-140, 50)
        turtle.write("You lost the bet", font=("Arial", 30, "bold"))
    turtle.pendown()


play()

choice = input("Do you want to play again?\n Press y for yes and n for no: ").upper()

while choice == "y".upper() or choice == "yes".upper():
    play()
else:
    quit()

The game works and i wanted the game to ask user to play again and it does that but every time the game reruns the turtles run over previous turtle the the text which display ** You won the bet** or ** You lost the bet** is also written over previous another one.游戏正常运行,我希望游戏要求用户再次玩,它会这样做,但每次游戏重新运行时,海龟都会越过前一个海龟,显示的文本会显示**您赢了赌注**或**您输了赌注** 也写在前面的另一个上。

I din't find any method to clear text written in screen nor to erase the turtles lines.我找不到任何方法来清除屏幕上写的文本,也找不到擦除海龟线的方法。 Please help me.请帮我。

And it would me really helpful if you guys give me suggestion on how to improve this code like how to make it more short and i am little confused about my own logic on line 106 about that or operator but this is secondary please help me on my primary problem first.如果你们给我关于如何改进这个代码的建议,比如如何让它更短,我对我自己在line 106关于那个or操作符的逻辑有点困惑,但这是次要的,请帮助我首先是首要问题。

My recommendation in a situation like this, where text is being updated on the screen, is that you have a turtle dedicated just to writing that text.在这种情况下,我的建议是在屏幕上更新文本,你有一只海龟专门用于编写该文本。 Put that turtle into position before the action starts and then just use clear() and write() on that turtle from then on.在动作开始之前将该海龟放入 position 中,然后从那时起对该海龟使用clear()write() Don't use it for anything else.不要将它用于其他任何事情。

it would me really helpful if you guys give me suggestion on how to improve this code如果你们给我关于如何改进这段代码的建议,我真的很有帮助

One key thing with a program like this is to not assume how many racers there will be, and write your code accordingly.像这样的程序的一个关键是不要假设会有多少赛车手,并相应地编写你的代码。 You should be able to adjust the number up or down slightly (or just change your color choices) without having to do a major rewrite.您应该能够稍微向上或向下调整数字(或者只是更改您的颜色选择),而无需进行重大重写。

I've reworked your code to address both of the above issues:我已经修改了您的代码以解决上述两个问题:

from turtle import Screen, Turtle
from random import randint

STAMP_SIZE = 20
SQUARE_SIZE = 15
FINISH_LINE = 200
LANE_WIDTH = 50

BIG_FONT = ('Arial', 40, 'bold')
MEDIUM_FONT = ('Arial', 30, 'bold')

COLORS = ['black', 'cyan', 'magenta', 'yellow', 'white']

def play():
    pen.clear()

    lane = LANE_WIDTH

    for n, color in enumerate(COLORS, start=1):
        turtle = turtles[color]

        turtle.hideturtle()
        turtle.goto(-250, n // 2 * lane)
        turtle.showturtle()

        lane = -lane

    # Asking user to play

    user_bet = None

    while user_bet not in COLORS:
        print("Please choose one colour out of", *["\n" + color.title() for color in COLORS])
        user_bet = input("Place your bet on your any one colour turtle: ").lower()

    # Moving the turtles

    for _ in range(145):

        for turtle in turtles.values():
            distance = randint(1, 5)
            turtle.forward(distance)

    # Deciding the winner

    winner = max(turtles, key=lambda x: turtles[x].xcor())

    pen.clear()
    if user_bet == winner:
        pen.write("You won the bet!", align='center', font=MEDIUM_FONT)
    else:
        pen.write("You lost the bet.", align='center', font=MEDIUM_FONT)

# Screen

screen = Screen()
screen.title("Turtle Race")
screen.bgcolor('forestgreen')

turtle = Turtle()
turtle.hideturtle()
turtle.speed('fastest')
turtle.penup()

# Dirt

turtle.setposition(-400, -180)
turtle.color('chocolate')

turtle.begin_fill()
for _ in range(2):
    turtle.forward(800)
    turtle.right(90)
    turtle.forward(300)
    turtle.right(90)
turtle.end_fill()

# Finish line

turtle.color('black')
turtle.shape('square')
turtle.shapesize(SQUARE_SIZE / STAMP_SIZE)

for i in range(10):
    turtle.setposition(FINISH_LINE, 150 - i * SQUARE_SIZE*2)
    turtle.stamp()
    turtle.setposition(FINISH_LINE + SQUARE_SIZE, (150 - SQUARE_SIZE) - i * SQUARE_SIZE*2)
    turtle.stamp()

turtle.setposition(0, 200)
turtle.write("Turtle Race", align='center', font=BIG_FONT)

pen = Turtle()
pen.hideturtle()
pen.color('blue')
pen.penup()
pen.setposition(0, 50)

turtle_prototype = Turtle()
turtle_prototype.hideturtle()
turtle_prototype.shape('turtle')
turtle_prototype.speed('fastest')
turtle_prototype.penup()

turtles = {}

for color in COLORS:
    turtle = turtle_prototype.clone()
    turtle.color(color)
    turtles[color] = turtle

choice = 'yes'

while choice.lower() in ('y', 'yes'):

    play()

    choice = input("Do you want to play again?\nPress y for yes and n for no: ")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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