Python Forum
Any pointers on my programm before I hand it in?(I'm new to python, so go easy on me)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Any pointers on my programm before I hand it in?(I'm new to python, so go easy on me)
#1
import random
import sys
import time
# generate random word
list_w = ["broad", "apple", "banana", "strawberry"]

# the blanks equal the length of the word
# list_space = ["-"] * len(word)


# create the function for the game

def random_word():
    global word
    global list_space1
    global guessed_letters
    global wrong_guesses
    word = random.choice(list_w)
    list_space1 = ["-"] * len(word)
    guessed_letters = []
    wrong_guesses = []
    print("".join(list_space1))
    
#if "-" not in list_space1:
 #   print("You have guessed the word")

def run():
    if "-" not in list_space1:
        print("You have guessed the word!\n")
        # ask if you want to close the programm
        ask = input("Do you want to play again?\n")
        
        # you call the random function again because it was called once in 
        # the beginning.
        if ask == "Yes" or ask == "yes":
            random_word()

        elif ask == "no" or ask == "No":
            time.sleep(1)
            sys.exit()
        
    answer = input("Guess a letter: \n")

    
    # check if answer in word
    # loop through all the numbers in range(len(word))
    # if word len = 4 then loop through range(4)
    # if answer == word[i]
    # list_space[i] = answer\

    # when loop again it checks if you guessed the letter
    # if so print etc. This shouldnt change the for loop.
    if answer in guessed_letters:
        print("You already guessed that!")
    # if answer is not in the word, add that answer
    # to wrong guesses
    elif answer not in word:
        print("Wrong guess!")
        wrong_guesses.append(answer)

    # only if answer not in guessed_letters, execute for loop.   
    elif answer not in guessed_letters and answer not in wrong_guesses:
        print("It's in the word")
        for i in range(len(word)):
                if answer == word[i]:
                    list_space1[i] = answer
        guessed_letters.append(answer)

    print("\n")                    
    print("".join(list_space1))

            
# only re-call random_word when you've guessed the word
random_word()
run_game = True
while run_game:
    run()
Reply
#2
Your replay logic does not work. You can only play the game once. If I try to play again the game says "You have guessed the word!" each time I enter a letter. It is also odd that the replay logic is inside the function that manages the game.

The random_word function is a neat idea, but poorly executed. Randdom_word should return a random word. In the future you might change this game to pull words out of a file or a database or some other means. The actual mechanism should be invisible to the rest of your game. But your implementation of random_word is full of game details. Random_word should not have to know about guessed_letters and wrong_guesses and list_space1. Those are game details, not getting the random word details.

You overuse "global". Global variables should be uses sparingly. In a small program like this it does not cause many problems, but if you had a large program with many global variables it would be difficult to keep track of where variables are used and where they are modified. There is no reason for you to use any global variables in your game at all.

Your comments could be better. What does this program do? I ran it and it plays hangman. Why isn't there a docstring right at the top of the file saying "This program plays hangman"? Why isn't there a docstring describing the purpose and use of each function?

Your comments are also too long. Write your code using code, not comments. If it isn't clear what the code does, reorganize the code so the purpose is clear. This comment:
    # check if answer in word
    # loop through all the numbers in range(len(word))
    # if word len = 4 then loop through range(4)
    # if answer == word[i]
    # list_space[i] = answer\
 
    # when loop again it checks if you guessed the letter
    # if so print etc. This shouldnt change the for loop.
Should be more like this comment:
Update display to show correctly guessed letters.  Game is over when all letters are guessed.
I think the wrong_guesses list is a great idea, but the implementation is not quite right. Instead of checking against previous guesses and saying "You already guessed that", why not display the guessed letters? Something like this:
Output:
Word: __e_d Guessed Letters: cedgm
Why is there a 1 second delay when I quit the game? I thought something had broken. Why are you using sys.exit()? Can you think of a more elegant way to exit the program?

Overall, not bad. Lots of room for improvement, but better than the first program I wrote.
Reply
#3
Thanks for your response,

I checked the programm again and the replay logic does work. So I don't know why you have that issue. I do agree with you about the commenting. That was kinda bad on my part. You talked about exiting the programme and why I used sys.exit(). Well the thing is, I don't know how to break out of the function any other way. Because the function already started up again, when I'm asking if you wan't to quit the game. So the only way to remedy that was to use the sys.exit(). If you have any better ways, I'd like to hear it.

Thanks!
Reply
#4
To test the play again logic try entering something other than Yes or No. I guess I did a typo (probably just Y or N) when I tested. Your logic has three possible outcomes; quit, replay with a new word; replay with the old word already solved.

Your replay logic is in the wrong place and that is why you have to use sys.exit to quit the program. The main body of the program should manage the replay logic and the run function should implement the game logic. By removing the replay logic from the run function you can initialize the game at the top of the run function, removing the initialization stuff from the random_word function (or removing the random word function).
"""Hangman game"""
import random

def play_game():
    """Player enters guesses until all letters in word are guessed"""
    # Initialize word, guesses, etc
    while '_' in list_space1:
        # get guess
        # process guess
    print('You guessed the word!')

while True:
    play_game()
    if input('Would you like to play again (y/n)? ').upper()[0] == 'N':
        print('Thanks for playing!')
        break;
If you don't want to reorganize the replay logic you can still get rid of the sys.exit() call. In run:
if ask.upper()[0] == 'Y':
    random_word()
else:
    run_game = False
    return
Still so ugly.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Need to improve a programm Richard_SS 4 2,791 Mar-17-2019, 04:16 AM
Last Post: Richard_SS
  Help on Creating Program to find the Median and Mode by hand EvanCahill 3 2,929 Jul-19-2018, 06:17 PM
Last Post: woooee

Forum Jump:

User Panel Messages

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