Python Forum
i want to shorten a working section
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
i want to shorten a working section
#11
input("do you speek german? (ja/no):")
Reply
#12
Instead of rewriting the game code for each language, write the game code once and translate the displayed text to the desired language while the game is running.

The code below is an example of how this can be achieved using a translation dictionary:
import random


translations = {
    "deutch": {
        "maximum": "maximal",
        "minimum": "minimal",
        "invalid value. try again": "ungültiger wert. versuche es noch einmal",
        "round": "rundden",
        "how many rounds do you want to play? ": "wie viele runden wilst du speilen? ",
        "what should the minimum be? ": "was soll das minimum sein? ",
        "what should the maximum be? ": "was soll das maximum sein? ",
        "the minimum cannot be more than the maximum": "das minimum kann nicht mehr als das maximum sein",
        "how many attempts do you want? ": "wie viele versuch wilst du haben? ",
        "number between": "nummer zwischen",
        "is correct!": "ist richtig!",
        "is too much": "ist zu viel",
        "is too little": "ist zu wenig",
        "you took too many tries": "du hast zu viele versuche gebraucht",
        "the number was": "die zahl war",
        "rounds successfully completed": "unden erfolgreich absolviert",
        "guesses used: ": "vermutungen verwendet: ",
        "guesses remaining: ": "verbleibende vermutungen: ",
        "play again? (yes/no): ": "nochmal spielen? (ja/nein): ",
        "yes": "ja",
        "no": "nein",
        "of": "von",
        "your average is": "dein durchschnitt ist"
    }
}


def _(string):
    """Translate string from english to selected language."""
    return language.get(string, string)


def int_input(prompt, value_type="", max_value=None, min_value=None):
    """Get integer input.
    
    use max_value and min_value to limit range of input.
    """
    while True:
        try:
            value = int(input(_(prompt)))
            if max_value is not None and value > max_value:
                print(_("maximum"), max_value, _(value_type))
            elif min_value is not None and value < min_value:
                print(_("minimum"), min_value, _(value_type))
            else:
                return value
        except ValueError:
            print(_("invalid value. try again"))
            print("----------------------------------")


def play_game(average=False):
    count = 0
    rounds = int_input("how many rounds do you want to play? ", "round", max_value=15)
    for round in range(1, rounds + 1):
        print("----------------------------------")
        print(_("round"), round)
        while True:
            low = int_input("what should the minimum be? ", min_value=-500000)
            high = int_input("what should the maximum be? ", max_value=500000)
            if low > high:
                print("----------------------------------")
                print(_("the minimum cannot be more than the maximum"))
                print("----------------------------------")
            else:
                break
        print("----------------------------------")
        number = random.randint(low, high)
        if average:
            max_guesses = None  # Unlimited guesses
        else:
            max_guesses = int_input("how many attempts do you want? ", max_value=min(100, high-low))

        guesses = 0
        while True:
            guesses += 1
            guess = int_input(f"{_('number between')}  ({low} - {high}): ", min_value=low, max_value=high)
            if guess == number:
                print(guess, _("is correct!"))

                print(_("guesses used: "), guesses)
                if average:
                    count += guesses
                else:
                    count += 1
                break
            if guess > number:
                print(guess, _("is too much"))
                high = guess
            else:
                print(guess, _("is too little"))
                low = guess
            if max_guesses is not None:
                if guesses >= max_guesses:
                    print(_("you took too many tries"))
                    print(_("the number was"), number)
                    break
                print(_("guesses remaining: "), max_guesses-guesses)
            print("----------------------------------")

    if average:
        print(_("your average is"), count / rounds)
    else:
        print(count, _("of"), rounds, _("rounds successfully completed"))


while True:
    # Select language for instructions.
    language = translations.get(input("language (english, deutch): "), {})
    play_game()
    print("----------------------------------")
    if input(_("play again? (yes/no): ")).lower() != _("yes"):
        break
The code is awkward looking, and the translation dictionary difficult to write. That is why there are tools to make this easier to do. One tool is gettext.

manual page: https://docs.python.org/3/library/gettext.html
tutorial: https://phrase.com/blog/posts/translate-...u-gettext/
Reply
#13
a bit proly translated but ok thx
Reply
#14
Kann nicht aus dem Wirrwarr schlau werden, kann aber mit dem Deutsch helfen.
Can't help with the chaotic code, can help with the German. (It's too painful!)

Quote:translations = {
"Deutsch": {
"maximum": "(das) Maximum",
"minimum": "(das) Minimum",
"invalid value. try again": "ungültiger Wert. Bitte versuche es noch einmal",
"round": f"(dies ist) Runde Nummer: {number}"
"how many rounds do you want to play? ": "wie viele Runden willst du spielen? ",
"what should the minimum be? ": "Gib das Minimum ein.",
"what should the maximum be? ": "Gib das Maximum ein? ",
"the minimum cannot be more than the maximum, or else it would not be the minimum!": "das Minimum kann ja nicht mehr als das Maximum sein, sonst wäre es doch nicht das Minimum, oder?",
"how many attempts do you want? ": "Wie viele Versuche möchtest du? ",
"number between": "Eine Nummer zwischen",
"is correct!": "Richtig!",
"is too much": "Zu hoch!",
"is too little": "Zu klein",
"you took too many tries": "Zu oft versucht!",
"the number was": "die Zahl war",
"rounds successfully completed": "Runden erfolgreich abgeschlossen",
"guesses used: ": f"Du hast schon {guesses} mal geraten.“: ",
"guesses remaining: ": "Du kannst noch {remainingguesses} mal raten: ",
"play again? (yes/no): ": "nochmal spielen? (ja/nein): ",
"yes": "ja",
"no": "nein",
"of": "von",
"your average is": "dein Durchschnitt ist"
}
}
Reply
#15
hätte ich selber hingegrigt
Reply
#16
For pizzakafz the dictionaries should translate from Deutsch to the display language so all the translation keys are in Deutsch.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  If I need to do regex replacement 27000 times, how to shorten it? tatahuft 4 831 Dec-26-2024, 01:51 AM
Last Post: deanhystad
  How to add multi-line comment section? Winfried 2 1,361 Jun-04-2024, 07:24 AM
Last Post: Gribouillis
  python multiple try except block in my code -- can we shorten code mg24 10 14,875 Nov-10-2022, 12:48 PM
Last Post: DeaD_EyE
  Want to shorten the python code shantanu97 3 2,056 Apr-25-2022, 01:12 PM
Last Post: snippsat
  Append data to Yaml section tbaror 0 8,814 Feb-09-2022, 06:56 PM
Last Post: tbaror
  Create an isolated section in bash? yxk 1 2,585 Feb-27-2020, 11:16 AM
Last Post: Larz60+
  Best section to do a while loop in my code mrapple2020 0 2,122 Apr-15-2019, 01:14 AM
Last Post: mrapple2020
  ConfigParser.NoSectionError: No section: 'Default' degenaro 1 16,364 Jun-08-2018, 08:33 PM
Last Post: ljmetzger
  How to shorten the size of program garikhgh0 11 8,093 Feb-22-2018, 06:35 PM
Last Post: snippsat
  Help understanding code section raz631 4 4,134 Dec-14-2017, 09:32 PM
Last Post: raz631

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020