【问题标题】:How can I have different vocabulary words for the different levels in Python maze game?如何在 Python 迷宫游戏中为不同级别设置不同的词汇?
【发布时间】:2019-05-13 22:01:39
【问题描述】:

我正在使用 Python 3,但我非常非常缺乏经验,所以请善待您的回答。另外,请尽可能简单地解释。 基本上,我有一个既是迷宫游戏又是语言词汇游戏的 Python 迷宫游戏。滚动“宝藏”时会弹出一个用户必须回答的问题!我在 .txt 文件中有我的词汇,这就是我获取词汇的方式。一切都很好,除了我希望能够为不同的级别使用不同的词汇。我知道如何做词汇部分,但我不知道如何参考每个单独的级别以便将词汇放入其中。

所以我正在考虑使用if 语句。它看起来像这样:

def gold_encounter():
    if start == combinedSpanishCommands:
        # Check for player collision with a question.
        # Iterate through the questions list.
        for question in questions:
            if player.collision(question):
                infile = open("translations.txt", "r")
                line = infile.readlines()
                ques = line[random.randrange(0, 232)]
                answer = simpledialog.askstring("Input", ques, parent=root)
                # Destroy the question.
                question.destroy()
                # Remove question from questions list.
                questions.remove(question)
                screen.listen()
    else:
        # Check for player collision with a question.
        # Iterate through the questions list.
        for question in questions:
            if player.collision(question):
                infile = open("translations.txt", "r")
                line = infile.readlines()
                ques = line[random.randrange(0, 232)]
                answer = simpledialog.askstring("Input", ques, parent=root)
                # Destroy the question.
                question.destroy()
                # Remove question from questions list.
                questions.remove(question)
                screen.listen()

除了我的问题是我使用的if 语句不起作用。我尝试了许多不同的if 语句,但它们都不起作用。请参考我下面的代码,这样你就可以看到上下文和我的级别等等。 我应该使用什么if 语句才能对所有级别/语言执行此操作?或者有其他方法吗?

from turtle import RawTurtle, TurtleScreen
import tkinter
from tkinter import PhotoImage, simpledialog
import random

largefont = ("Verdana", 12)

# Define function to create Spanish level.
def span():
    pen.setup(level_1)
    player.setup(level_1)
    setup(level_1)

# Define function to create French level.
def fren():
    pen.setup(level_2)
    player.setup(level_2)
    setup(level_2)

# Define function to create Japanese level.
def jpn():
    pen.setup(level_3)
    player.setup(level_3)
    setup(level_3)

# Define function to create Turkish level.
def turk():
    pen.setup(level_4)
    player.setup(level_4)
    setup(level_4)

# Create window and canvas using tkinter.
root = tkinter.Tk()
root.title("Language Labyrinth")

canvas = tkinter.Canvas(root, width=600, height=600)
canvas.pack()

screen = TurtleScreen(canvas)
screen.bgcolor('black')

# Define a function to set flag background for Spanish level
def spanishFlag():
    screen.bgpic("spainflag.png")

# Define a function to set flag background for French level
def frenchFlag():
    screen.bgpic("franceflaggrunge.png")

# Define a function to set flag background for Japanese level        
def japaneseFlag():
    screen.bgpic("japanflagoffwhite.png")

# Define a function to set flag background for Turkish level
def turkishFlag():
    screen.bgpic("turkishflagdiagonal.png")

# Define a function to combine the level and background setup functions for Spanish level
def combinedSpanishCommands():
    span()
    spanishFlag()

# Define a function to combine the level and background setup functions for French level
def combinedFrenchCommands():
    fren()
    frenchFlag()

# Define a function to combine the level and background setup functions for Japanese level
def combinedJapaneseCommands():
    jpn()
    japaneseFlag()

# Define a function to combine the level and background setup functions for Turkish level
def combinedTurkishCommands():
    turk()
    turkishFlag()

# Create class with separate window to choose level.
class StartPage():
    def __init__(self):
        # Creation of second window.
        wn = tkinter.Tk()
        wn.title("Welcome!")
        # Creation of game title on start page.
        label = tkinter.Label(wn, text="Language Labyrinth", font=largefont)
        label.pack()

        # Create Spanish level button.
        button = tkinter.Button(wn, text="Spanish", command=combinedSpanishCommands)
        button.pack()

        # Create French level button.
        button2 = tkinter.Button(wn, text="French", command=combinedFrenchCommands)
        button2.pack()

        # Create Japanese level button.
        button3 = tkinter.Button(wn, text="Japanese", command=combinedJapaneseCommands)
        button3.pack()

        # Create Turkish level button.
        button4 = tkinter.Button(wn, text="Turkish", command=combinedTurkishCommands)
        button4.pack()

        # Create quit button for start page.
        qbutton = tkinter.Button(wn, text="Quit", command=wn.destroy)
        qbutton.pack()

start = StartPage()

# Create Pen class to draw the maze.
class Pen(RawTurtle):
    def __init__(self):
        super().__init__(screen, shape='square')
        self.speed('fastest')
        self.color('white')
        self.penup()

    # Create setup so the maze will be drawn.
    def setup(self, level):
        for y in range(len(level)):
            screen_y = 288 - (y * 24)

            for x in range(len(level[y])):
                if level[y][x] == 'X':
                    screen_x = (x * 24) - 288

                    self.goto(screen_x, screen_y)
                    self.stamp()

                    walls.append((screen_x, screen_y))

# Create player class to have a player.
class Player(RawTurtle):
    def __init__(self):
        super().__init__(screen, shape='square')
        self.penup()
        self.speed('fastest')
        self.color('black')

    def bKey(self):
        global color
        print("b key pressed")
        self.color('blue')

    def rKey(self):
        global color
        print("r key pressed")
        self.color('red')

    def gKey(self):
        global color
        print("g key pressed")
        self.color('green')

    def pKey(self):
        global color
        print("p key pressed")
        self.color('purple')

    def yKey(self):
        global color
        print("y key pressed")
        self.color('goldenrod')

    def oKey(self):
        global color
        print("o key pressed")
        self.color('orange')

    # Create setup to create the player on the screen.
    def setup(self, level):
        for y in range(len(level)):
            for x in range(len(level[y])):
                if level[y][x] == 'P':
                    screen_x = (x * 24) - 288
                    screen_y = 288 - (y * 24)

                    self.goto(screen_x, screen_y)

                    return

    # Define a function that will allow player to move up.
    def move_up(self):
        # Calculate the spot to move to.
        movetoX = self.xcor()
        movetoY = self.ycor() + 24

        # Check if the space has a wall.
        if (movetoX, movetoY) not in walls:
            self.goto(movetoX, movetoY)

            gold_encounter()

    # Define a function that will allow player to move down.
    def move_down(self):
        # Calculate the spot to move to.
        movetoX = self.xcor()
        movetoY = self.ycor() - 24

        # Check if the space has a wall.
        if (movetoX, movetoY) not in walls:
            self.goto(movetoX, movetoY)

            gold_encounter()

    # Define a function that will allow player to move left.
    def move_left(self):
        # Calculate the spot to move to.
        movetoX = self.xcor() - 24
        movetoY = self.ycor()

        # Check if the space has a wall.
        if (movetoX, movetoY) not in walls:
            self.goto(movetoX, movetoY)

            gold_encounter()

    # Define a function that will allow player to move right.
    def move_right(self):
        # Calculate the spot to move to.
        movetoX = self.xcor() + 24
        movetoY = self.ycor()

        # Check if the space has a wall.
        if (movetoX, movetoY) not in walls:
            self.goto(movetoX, movetoY)

            gold_encounter()

    # Check if player touches the question.
    def collision(self, other):
        return self.distance(other) < 5

# Create Question class to create the "gold" in the game.
class Question(RawTurtle):
    def __init__(self, x, y):
        super().__init__(screen, shape='circle', visible=False)
        self.speed('fastest')
        self.color('hotpink')
        self.penup()
        self.goto(x, y)
        self.showturtle()

    # Define function that will remove gold when collided with.
    def destroy(self):
        self.hideturtle()

# Define function to setup the "gold" in the game.
def setup(level):
    for y in range(len(level)):
        for x in range(len(level[y])):
            char = level[y][x]

            screen_x = -288 + (x * 24)
            screen_y = 288 - (y * 24)

            if char == 'Q':
                questions.append(Question(screen_x, screen_y))

# Define a function for the quit button.
def quitPlaying():
    root.destroy()
    root.quit()

# Game loop in regards to the gold.
def gold_encounter():
    if start == combinedSpanishCommands:
        # Check for player collision with a question.
        # Iterate through the questions list.
        for question in questions:
            if player.collision(question):
                infile = open("translations.txt", "r")
                line = infile.readlines()
                ques = line[random.randrange(0, 232)]
                answer = simpledialog.askstring("Input", ques, parent=root)
                # Destroy the question.
                question.destroy()
                # Remove question from questions list.
                questions.remove(question)
                screen.listen()
    else:
        # Check for player collision with a question.
        # Iterate through the questions list.
        for question in questions:
            if player.collision(question):
                infile = open("translations.txt", "r")
                line = infile.readlines()
                ques = line[random.randrange(0, 232)]
                answer = simpledialog.askstring("Input", ques, parent=root)
                # Destroy the question.
                question.destroy()
                # Remove question from questions list.
                questions.remove(question)
                screen.listen()

# Create frame where button(s) will be.
frame = tkinter.Frame(root)
frame.pack()

# Add questions list.
questions = []

# Wall coordinate list.
walls = []

# Create a levels list.
levels = []

# Define first level.
level_1 = [
"XXXXXXXXXXXXXXXXXXXXXXXXX",
"XP XXXXXXX          XXXXX",
"X  XXXXXXX  XXXXXX  XXXXX",
"X       XX  XXXXXX  XXXXX",
"X       XX  XXX        XX",
"XXXXXX  XX  XXX   Q    XX",
"XXXXXX  XX  XXXXXX  XXXXX",
"XXXXXX  XX    XXXX  XXXXX",
"X  XXX Q      XXXX  XXXXX",
"X  XXX  XXXXXXXXXXXXXXXXX",
"X         XXXXXXXXXXXXXXX",
"X     Q          XXXXXXXX",
"XXXXXXXXXXXX     XXXXX  X",
"XXXXXXXXXXXXXXX  XXXXX  X",
"XXX  XXXXXXXXXX         X",
"XXX               Q     X",
"XXX         XXXXXXXXXXXXX",
"XXXXXXXXXX  XXXXXXXXXXXXX",
"XXXXXXXXXX              X",
"XX   XXXXX        Q     X",
"XX   XXXXXXXXXXXXX  XXXXX",
"XX    XXXXXXXXXXXX  XXXXX",
"XX    Q     XXXX        X",
"XXXX                    X",
"XXXXXXXXXXXXXXXXXXXXXXXXX"
]

# Define second level.
level_2 = [
"XXXXXXXXXXXXXXXXXXXXXXXXX",
"XP  XX       XX      XXXX",
"X   XX       XX      XXXX",
"X   XXXXXXX  XX  XX     X",
"X   XXXXXXX  XX  XX Q   X",
"X   XX   XX  XX  XXXXX  X",
"X   XX   XX  XX  XXXXX  X",
"XQ         Q     XX  X  X",
"X                XX  X  X",
"X   XXXXXXX   XXXXX  XXXX",
"X   XX   XX             X",
"XXXXXX   XX        Q    X",
"XXXXXX   XXXXXXXXXXXX   X",
"X      Q      XX   XX   X",
"X             XX   XX   X",
"XXXXXXXXXX    XX        X",
"XXXXXX   X    XX     Q  X",
"XXXXXX   X    XX   XX   X",
"X                 X  X  X",
"X       Q         X  X  X",
"XXXXXX   XXXXXXXXXX  X  X",
"XXXXXX   XXXXXXXXXX     X",
"X         X             X",
"X         XQ     XXXXXXXX",
"XXXXXXXXXXXXXXXXXXXXXXXXX"
]

# Define third level.
level_3 = [
"XXXXXXXXXXXXXXXXXXXXXXXXX",
"X      X   XP           X",
"X    Q X   X            X",
"X   XXXX   XXXXXXXXXX   X",
"X   XXXX   XXXXXXXXXX   X",
"X         Q    XX       X",
"X              XX       X",
"XXXXXXXXXXXX   XXXX   XXX",
"X              XXXX   XXX",
"X              XXXX   XXX",
"XXXXX Q XXXXXXXXXXX   XXX",
"X                   Q   X",
"X                       X",
"XXXXXXXXXX Q  XXXXXXX   X",
"XXXXXXXXXX    XXXXXXX   X",
"XXXX         XXXXXXXXX  X",
"XXX      XXXXXXXXX      X",
"XXXXXX   XXXXXXXXXXXX   X",
"X            X      Q   X",
"X  Q         X       XXXX",
"XXXXXXX            XXXXXX",
"XXXXXXXXXXXX Q XXXXXXXXXX",
"X                       X",
"X Q         XXX       Q X",
"XXXXXXXXXXXXXXXXXXXXXXXXX"
]

# Define fourth level.
level_4 = [
"XXXXXXXXXXXXXXXXXXXXXXXXX",
"XXXXXXXXXX  P  XXXXXXXXXX",
"XXXXXXXXXX     XXXXXXXXXX",
"XXXXXXXXXXX Q XXXXXXXXXXX",
"X                       X",
"X          XXX          X",
"XXXXX  Q  XXXXX  Q  XXXXX",
"X          XXX          X",
"XXXXXXXX    X    XXXXXXXX",
"X Q         X         Q X",
"X           X           X",
"XXXXXXXXXX QXQ XXXXXXXXXX",
"X                       X",
"X                       X",
"XXXXXXXXXXXXXXXXXXXXX   X",
"XXXXXXXXXXXXXXXXXXXXX   X",
"XXXXXX   XXXXXXXXX      X",
"XXXXXX   XXXXXXX Q  XXXXX",
"XQ                      X",
"X                       X",
"XXXXXXXXXXX   XXXXXXX   X",
"XXXXXXXX      XXXXXXX   X",
"XXXXXX     XXXXXXXXXX   X",
"XXXXX  Q XXXXXXXXXXX Q  X",
"XXXXXXXXXXXXXXXXXXXXXXXXX"
]

# Add the level(s) to the levels list.
levels.append(level_1)
levels.append(level_2)
levels.append(level_3)
levels.append(level_4)

# Class instances.
pen = Pen()
player = Player()

# Creation of quit button.
quitButton = tkinter.Button(frame, text='Quit', command=quitPlaying)
quitButton.pack()

# Button commands for player movement
screen.onkeypress(player.move_up, 'Up')
screen.onkeypress(player.move_down, 'Down')
screen.onkeypress(player.move_left, 'Left')
screen.onkeypress(player.move_right, 'Right')

# Button commands for customizable player colors 
screen.onkeypress(player.bKey, "b")
screen.onkeypress(player.rKey, "r")
screen.onkeypress(player.gKey, "g")
screen.onkeypress(player.pKey, "p")
screen.onkeypress(player.yKey, "y")
screen.onkeypress(player.oKey, "o")

screen.listen()

# Call main game loop.
screen.mainloop()

所以我希望能够使用if 语句(或者如果有更好的方法,请告诉我)以便为每种特定语言/级别提供特定词汇。

【问题讨论】:

  • 为什么不只加载一次翻译文本,然后将其存储在字典中?类似{"level_1":[list_of_words_for_level_1],"level_2":[list_of_words_for_level_2],...}
  • @Henry Yik 我可以这样做,但这不是我所指的问题。 :( 我的问题是我的if 声明。即使我将它存储在一个字典中,这也不能解决我能够为每个单独级别加载不同字典的问题。我该怎么做?
  • 你不能只跟踪你当前的水平吗?对我来说似乎很简单。我不知道你为什么被困在if 上,正如你提到的那样
  • @HenryYik 跟踪我目前的水平是什么意思? gold_encounter() 函数是我存储问题的地方,它适用于所有级别。因此,我在该函数中输入的任何内容都将用于所有级别,除非我用 if 语句将其分解,如我在上面的代码中所示。但是我使用的语句不起作用,这就是我卡住的地方。除非有更好的方法来做到这一点,但我不知道还有什么方法可以确保我在正确的级别获得正确的词汇。

标签: python tkinter turtle-graphics maze


【解决方案1】:

有趣的问题 - 我对 python 也很陌生,但我会这样做。

所以你可以有一个文件包含这样的东西 {level1},

“问题等等”, 回答

“问题等等”, 回答

“问题等等”, 回答(有尽可能多的等)

{level2} “问题等等”, 回答

“问题等等”, 回答

“问题等等”, 回答

从这里,您可以加载文件并使用例如 for 循环遍历它。 在文件中搜索字符串“level1”或“level2”等。 在此之后只需打印出您遇到的第一个问题,并检查用户输入是否与下一行匹配

您可以逐行浏览文本文件 - 稍微便宜的方法,但应该适合你 希望这会有所帮助

【讨论】:

  • 我可以这样做,但这并不能真正解决我的主要问题。我目前关心的是我的if 声明。我上面显示的那个不起作用。即使我将它存储在不同的字典中,我仍然无法为每个单独的级别加载不同的字典。我该怎么做? :(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多