简体   繁体   中英

how do I clear the python interpreter while still executing script?

I'm trying to build my own hangman game and I want to give the user the choice of putting in their own words. It all seems to work so far but when the user does want to put in his own word to be guessed the other person guessing it will still be able to see it in the interpreter or wherever the script will be run.

import random

# welcome-message as ASCII
welcome = """
  **      **       **       ****     **     ********    ****     ****       **       ****     **
/**     /**      ****     /**/**   /**    **//////**  /**/**   **/**      ****     /**/**   /**
/**     /**     **//**    /**//**  /**   **      //   /**//** ** /**     **//**    /**//**  /**
/**********    **  //**   /** //** /**  /**           /** //***  /**    **  //**   /** //** /**
/**//////**   **********  /**  //**/**  /**    *****  /**  //*   /**   **********  /**  //**/**
/**     /**  /**//////**  /**   //****  //**  ////**  /**   /    /**  /**//////**  /**   //****
/**     /**  /**     /**  /**    //***   //********   /**        /**  /**     /**  /**    //***
//      //   //      //   //      ///     ////////    //         //   //      //   //      /// 
"""

# preset for words to be guessed
random_nouns = ["brick", "servant", "pan", "vest", "bead", "end", "stocking", "lettuce", "flag", "wash", "sea", "ice",
                "amount", "fruit", "train", "railway", "dolls", "stitch",
                "bone", "shame", "step", "smell", "error", "stone", "theory", "cows", "shape", "apparatus",
                "representative", "crown", "wish", "space", "calculator", "actor",
                "beginner"]
numerals = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
solution = None

print(welcome)

user_choice = input(
    "Do you want to guess a preset word or do you want your own word to be guessed? Y for preset, N for own word. ").lower()
if user_choice == "y":
    print("\nA preset word has been chosen. The game will begin now!\n")
    solution = random_nouns[random.randint(0, len(random_nouns) - 1)]
elif user_choice == "n":
    solution = input(str("\nWhich word do you want to be guessed? ")).lower()
    for letter in solution:
        if letter in numerals or " " in solution:
            print("\nYour word contains invalid characters (i.e. numbers or spaces), please start again.")
            quit()
        else:
            print("\nA word to be guessed has been chosen. The game will begin now!\n")
            break
elif user_choice != "y" and user_choice != "n":
    print("\nWrong choice. Either enter Y for preset word or N for own word. Try again.\n")
    quit()

# split word in characters and add it to a list so the guessed letters can be matched
solution_chars = list(solution)
solution_as_underscore = list("_" * len(solution_chars))
solution_as_underscore_string = "".join(solution_as_underscore)
# print(solution)
# print(solution_chars)

# to check if input is not numerical and only alphabetical
number_of_chars = len(solution)
solution_try = []
right_letter_index = 0
fail_count = 0
fail_count_max = len(solution)
all_indexes = []

print(solution_as_underscore_string, "\n")

while fail_count < len(solution):
    solution_as_underscore = [x for x in solution_as_underscore if x != " "]
    # print(solution_as_underscore_string, "\n")
    # print(solution_chars)
    guessed_letter = input("Try a letter! ").lower()
    if len(guessed_letter) > 1:
        print("\nInvalid input, input can only be 1 letter.\n")
        print("".join(solution_as_underscore), "\n")
        fail_count += 1
        pass
    elif guessed_letter in numerals:
        print("\nPlease only use letters, not numbers.\n")
        print("".join(solution_as_underscore), "\n")
        fail_count += 1
        pass
    elif guessed_letter not in solution_chars:
        # TODO: Build Hangman
        print("\nThat was not correct.\n")
        print("".join(solution_as_underscore), "\n")
        fail_count += 1
        # print(fail_count)
        pass
    elif guessed_letter in solution_chars:
        for fum, letter in enumerate(solution_chars):
            if letter == guessed_letter:
                for i in range(0, len(solution_chars)):
                    if solution_chars[i] == guessed_letter:
                        solution_as_underscore[i] = guessed_letter
                    elif solution_chars[0] == guessed_letter:
                        solution_as_underscore[0] = guessed_letter.upper()
                print("\nThat was correct.\n")
                print("".join(solution_as_underscore), "\n")
                if "_" not in solution_as_underscore:
                    print(f"You won! The solution was \"{solution.title()}\".")
                    quit()
                break
    if solution_as_underscore[0] != "_":
        solution_as_underscore[0] = solution_as_underscore[0].upper()
    if fail_count == len(solution):
        print(f"\nOut of guesses. You lost. The solution was \"{solution.title()}\".")
        quit()

This is my output if I put in "hello" as a test.

"Which word do you want to be guessed? hello

A word to be guessed has been chosen. The game will begin now!"

I want to remove the first line after a word has been put in and then print the welcome message.

Any ideas?

You can do this

import os
os.system('cls' if os.name == 'nt' else 'clear')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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