首页 > 解决方案 > 字符串回溯错误 Python

问题描述

我遇到了一个似乎非常基本的问题,但我无法解决......当我运行我的代码时,我总是得到一个“Traceback(最近一次调用最后一次):”错误。问题似乎出在 String 上?

我得到的错误代码如下:

Traceback (most recent call last):
File "<string>", line 250, in run_nodebug
File "C:\Users\ThinkPad\Documents\Projekt2k18\No Escape ! V1.8.py", line 122, in <module>
stylo = Stylo()
File "C:\Users\ThinkPad\Documents\Projekt2k18\No Escape ! V1.8.py", line 5, in __init__
Turtle.__init__(self, "mur.gif")
File "C:\EduPython\App\lib\turtle.py", line 3816, in __init__
visible=visible)
File "C:\EduPython\App\lib\turtle.py", line 2557, in __init__
self._update()
File "C:\EduPython\App\lib\turtle.py", line 2660, in _update
self._update_data()
File "C:\EduPython\App\lib\turtle.py", line 2646, in _update_data
self.screen._incrementudc()
File "C:\EduPython\App\lib\turtle.py", line 1292, in _incrementudc
raise Terminator
turtle.Terminator

这是我的代码:

from turtle import Turtle, Screen

class Stylo(Turtle):
    def __init__(self):
        Turtle.__init__(self, "mur.gif")
        self.color("white")
        self.penup()
        self.speed('fastest')

class Joueur(Turtle):
    def __init__(self):
        Turtle.__init__(self, "face.gif")
        self.color("blue")
        self.penup()
        self.speed('fastest')

def haut(self):
    move_to_x = self.xcor()
    move_to_y = self.ycor() + 24
    self.shape("back.gif")
    if (move_to_x, move_to_y) not in murs:
        self.goto(move_to_x, move_to_y)
    scorefn()

def bas(self):
    move_to_x = self.xcor()
    move_to_y = self.ycor() - 24
    self.shape("face.gif")
    if (move_to_x, move_to_y) not in murs:
        self.goto(move_to_x, move_to_y)
    scorefn()

def gauche(self):
    move_to_x = self.xcor() - 24
    move_to_y = self.ycor()
    self.shape("left.gif")
    if (move_to_x, move_to_y) not in murs:
        self.goto(move_to_x, move_to_y)
    scorefn()

def droite(self):
    move_to_x = self.xcor() + 24
    move_to_y = self.ycor()
    self.shape("right.gif")
    if (move_to_x, move_to_y) not in murs:
        self.goto(move_to_x, move_to_y)
    scorefn()

def collision(self, other):
    return self.distance(other) < 5

class Tresor(Turtle):
    def __init__(self, x, y):
        Turtle.__init__(self, "tresor.gif")
        self.penup()
        self.speed('fastest')
        self.goto(x, y)

def destruction(self):
    self.hideturtle()
    self.goto(2000, 2000)

class Forme(object):
    def __init__(self, length, width, color, sides):
        self.length = length
        self.width = width
        self.color = color
        self.sides = sides

def draw(self):
    t = turtle.Pen()


boucle=True
while boucle:       #Boucle menu
    a=int(input("Choisissez la figure à réaliser avec Turtle :\n1. Jouer \n2. Leaderboard \n0. Sortir"))

if a==1:
    fn = Screen()
    fn.bgcolor("black")
    fn.title("No Escape!")
    fn.setup(700, 700)

    IMAGES = ["right.gif", "left.gif", "face.gif", "back.gif", "tresor.gif", "mur.gif", "sol.gif"]

    for image in IMAGES:
        # On ajoute l'image a notre labyrinthe.
        fn.addshape(image)

    POLICE1 = ('Arial', 24, 'bold')
    POLICE2 = ('Arial', 50, 'bold')

    NIVEAUX = [[
        "XXXXXXXXXXXXXXXXXXXXXXXXX",
        "XJ X      X             X",
        "X  X XXX  X    XXXXXXX  X",
        "X  X  TX  X          X  X",
        "X  XXXXX  X  X XXXXXXX  X",
        "XT          X  X        X",
        "XXXXXXXX    X  XT X X   X",
        "X X    X XXXXXXXXXXXXXX X",
        "X X X  X X            X X",
        "X X XT X   X X   X    XTX",
        "X X XXXX X X XXXXXX X XXX",
        "X X    X X X TX     X   X",
        "X XXX XX   XXXXXXXXXXXXXX",
        "X        X X            X",
        "XXXXXXXX   XTX  X X XXX X",
        "X      X X XXX  X X XT  X",
        "X  XXX X X      X X XXXXX",
        "X XXT  X X  XXXXXXX X X X",
        "X  XXXXX X              X",
        "X          XXXXXXXXXX X X",
        "XXXXX  XXXXX            X",
        "X          X X X XX XXXXX",
        "X XXXXXXXX X XXX  X    XX",
        "X     TX   X  XT X   X  X",
        "XXXXXXXXXXXXXXXXXXXXXXXXX"]]

    #fn.tracer(False)  # On enleve les mises a jour de l'ecran.

    stylo = Stylo()
    joueur = Joueur()

    tresors = []
    murs = []
    setup_labyrinthe(NIVEAUX[0])

    def setup_labyrinthe(niveau):
        for y in range(len(niveau)):
            for x in range(len(niveau[y])):
                caractere = niveau[y][x]
                ecran_x = -288 + (x * 24)
                ecran_y = 288 - (y * 24)

                if caractere == "X":
                    stylo.goto(ecran_x, ecran_y)
                    stylo.stamp()
                    murs.append((ecran_x, ecran_y))
                elif caractere == "J":
                    joueur.goto(ecran_x, ecran_y)
                elif caractere == "T":
                    tresors.append(Tresor(ecran_x, ecran_y))

    def scorefn():
        global score

        for tresor in tresors:
            if joueur.collision(tresor):
                tresor.destruction()
                tresors.remove(tresor)
                score += 100
                marker.undo()
                marker.write(score, font=POLICE1)

                if score == 1000 :
                    marker.goto(-150, 0)
                    marker.write("You Win !", font=POLICE2)

    fn.onkeypress(joueur.gauche, "Left")
    fn.onkeypress(joueur.droite, "Right")
    fn.onkeypress(joueur.haut, "Up")
    fn.onkeypress(joueur.bas, "Down")
    fn.onkey(fn.bye, "Escape")
    fn.listen()

    score = 0

    marker = Turtle(visible=False)
    marker.penup()
    marker.color('gray')
    marker.goto(-275, 305)
    marker.write("No Escape !", font=POLICE1)
    marker.goto(240, 305)
    marker.write(score, font=POLICE1)

    fn.tracer(True)  # On remet les mises a jour de l'ecran

    fn.mainloop()

if a==0:
    boucle=False

有人可以告诉我为什么我会遇到这个问题并帮助我解决它吗?

非常感谢,

最大限度。

标签: pythonturtle-graphics

解决方案


我在您的代码中看到的主要问题是这个整体while控制结构不起作用:

boucle = True

while boucle:  # Boucle menu
    a = int(input("Choisissez la figure à réaliser avec Turtle :\n1. Jouer \n2. Leaderboard \n0. Sortir"))

    if a == 1:
        fn = Screen()
        ...
        fn.mainloop()

    if a == 2:
        pass  # implement leaderboard

    if a == 0:
        boucle = False

一旦你mainloop()在选项 1 下调用,你将控制权交给 tkinter,如果/当它返回时,海龟世界的状态可能是不可重新运行的。

我建议您考虑将此海龟程序嵌入到 tkinter 窗口层次结构中,以允许您将排行榜作为单独的 tkinter 窗口弹出。另外,再次播放的选项应该是事件循环中的类似按钮的事件,而不是控制台的问题。

其他几个问题:

代替:

Turtle.__init__(self, "mur.gif")

考虑:

super().__init__("mur.gif")

这重复的逻辑:

move_to_x = self.xcor()
move_to_y = self.ycor() + 24
if (move_to_x, move_to_y) not in murs:
    ...

注定最终失败。海龟在浮点平面上徘徊,假设平等并不总是像你期望的那样工作。强制从海龟返回的位置值int()将有所帮助。

正如你提到的,我已经删除了 while 循环,但我仍然无法弄清楚为什么我的程序无法运行

下面是我为我播放的你的程序的返工。我用海龟形状和标题替换了图像,所以 SO 上的任何人都可以播放它。我尽可能简化了代码并重新设置了样式:

from turtle import Turtle, Screen

POLICE1 = ('Arial', 24, 'bold')
POLICE2 = ('Arial', 50, 'bold')

NIVEAUX = [[
    "XXXXXXXXXXXXXXXXXXXXXXXXX",
    "XJ X      X             X",
    "X  X XXX  X    XXXXXXX  X",
    "X  X  TX  X          X  X",
    "X  XXXXX  X  X XXXXXXX  X",
    "XT          X  X        X",
    "XXXXXXXX    X  XT X X   X",
    "X X    X XXXXXXXXXXXXXX X",
    "X X X  X X            X X",
    "X X XT X   X X   X    XTX",
    "X X XXXX X X XXXXXX X XXX",
    "X X    X X X TX     X   X",
    "X XXX XX   XXXXXXXXXXXXXX",
    "X        X X            X",
    "XXXXXXXX   XTX  X X XXX X",
    "X      X X XXX  X X XT  X",
    "X  XXX X X      X X XXXXX",
    "X XXT  X X  XXXXXXX X X X",
    "X  XXXXX X              X",
    "X          XXXXXXXXXX X X",
    "XXXXX  XXXXX            X",
    "X          X X X XX XXXXX",
    "X XXXXXXXX X XXX  X    XX",
    "X     TX   X  XT X   X  X",
    "XXXXXXXXXXXXXXXXXXXXXXXXX"]]

class Stylo(Turtle):
    def __init__(self):
        super().__init__("square")
        self.speed('fastest')
        self.color("white")
        self.penup()

class Joueur(Turtle):
    def __init__(self):
        super().__init__("turtle")
        self.speed('fastest')
        self.color("green")
        self.penup()

    def haut(self):
        self.setheading(90)

        x, y = self.position()
        move_to = (int(x), int(y) + 24)

        if move_to not in murs:
            self.goto(move_to)

        scorefn()

    def bas(self):
        self.setheading(270)

        x, y = self.position()
        move_to = (int(x), int(y) - 24)

        if move_to not in murs:
            self.goto(move_to)

        scorefn()

    def gauche(self):
        self.setheading(180)

        x, y = self.position()
        move_to = (int(x) - 24, int(y))

        if move_to not in murs:
            self.goto(move_to)

        scorefn()

    def droite(self):
        self.setheading(0)

        x, y = self.position()
        move_to = (int(x) + 24, int(y))

        if move_to not in murs:
            self.goto(move_to)

        scorefn()

    def collision(self, other):
        return self.distance(other) < 5

class Tresor(Turtle):
    def __init__(self, position):
        super().__init__("triangle")
        self.setheading(90)  # make look like pile of gold
        self.color("gold")
        self.penup()
        self.goto(position)
        tresors.append(self)

    def destruction(self):
        tresors.remove(self)
        self.hideturtle()

def setup_labyrinthe(niveau):

    screen.tracer(False)

    for y in range(len(niveau)):
        for x in range(len(niveau[y])):
            caractere = niveau[y][x]
            ecran = ((x * 24) - 288, 288 - (y * 24))

            if caractere == "X":
                stylo.goto(ecran)
                stylo.stamp()
                murs.append(ecran)
            elif caractere == "J":
                joueur.goto(ecran)
            elif caractere == "T":
                Tresor(ecran)

    screen.tracer(True)

def scorefn():
    global score

    for tresor in tresors:
        if joueur.collision(tresor):
            tresor.destruction()

            score += 100
            marker.undo()
            marker.write(score, font=POLICE1)

            if score >= 1000:
                marker.goto(-150, 0)
                marker.color('red')
                marker.write("You Win!", font=POLICE2)

                # disable movements but leave Escape/exit active
                for direction in ["Left", "Right", "Up", "Down"]:
                    screen.onkeypress(None, direction)

screen = Screen()
screen.bgcolor("black")
screen.title("No Escape!")
screen.setup(700, 700)

tresors = []
murs = []

stylo = Stylo()
joueur = Joueur()

setup_labyrinthe(NIVEAUX[0])

score = 0

marker = Turtle(visible=False)
marker.penup()
marker.color('gray')
marker.goto(-275, 305)
marker.write("No Escape!", font=POLICE1)
marker.goto(240, 305)
marker.write(score, font=POLICE1)

screen.onkeypress(joueur.gauche, "Left")
screen.onkeypress(joueur.droite, "Right")
screen.onkeypress(joueur.haut, "Up")
screen.onkeypress(joueur.bas, "Down")
screen.onkey(screen.bye, "Escape")
screen.listen()

screen.mainloop()

如果这仍然无法为您运行,您可能会寻找程序无法运行的外部原因。(例如,您是否将其中一个文件命名为与 Python 库模块相同的名称;您的任何 Unicode 文本(字符串或文件名)是否会混淆 Python;您是否正在运行标准版本的 Python;您是否拥有标准版本的 turtle。 py 等)

在此处输入图像描述


推荐阅读