Commentare un programma

di il
1 risposte

Commentare un programma

Potreste commentarmi la funzione "def readCSV(K)"? E'è l'ultima funzione prima del -MAIN-
import random
import os
import sys
import csv


HANGMANPICS = ['''

  +---+
  |   |
      |
      |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
      |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
  |   |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========''', '''

  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========''']
words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra'.split()

def clearScreen():
    if sys.platform.startswith('linux'):
        os.system('clear') #on linux
    elif sys.platform.startswith('win32'):
        os.system('cls') #on windows
        
    return

def initGame(wordsList):
    global missedLetters, correctLetters, secretWord, gameIsDone
    
    missedLetters = ''
    correctLetters = ''
    secretWord = getRandomWord(wordsList)
    gameIsDone = False
    
    return

def getRandomWord(wordList):
    # This function returns a random string from the passed list of strings.
    wordIndex = random.randint(0, len(wordList) - 1)
    return wordList[wordIndex]

def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord):
    print(HANGMANPICS[len(missedLetters)])
    print()

    end=' '
    print('Missed letters:', end)
    for letter in missedLetters:
        end=' '
        print(letter, end)
    print()

    blanks = '_' * len(secretWord)

    for i in range(len(secretWord)): # replace blanks with correctly guessed letters
        if secretWord[i] in correctLetters:
            blanks = blanks[:i] + secretWord[i] + blanks[i+1:]

    for letter in blanks: # show the secret word with spaces in between each letter
        end=' '
        print(letter, end)
    print()

def getGuess(alreadyGuessed):
    # Returns the letter the player entered. This function makes sure the player entered a single letter, and not something else.
    while True:
        print('Guess a letter.')
        guess = input()
        guess = guess.lower()
        if len(guess) != 1:
            print('Please enter a single letter.')
        elif guess in alreadyGuessed:
            print('You have already guessed that letter. Choose again.')
        elif guess not in 'abcdefghijklmnopqrstuvwxyz':
            print('Please enter a LETTER.')
        else:
            return guess

def playAgain():
    # This function returns True if the player wants to play again, otherwise it returns False.
    print('Do you want to play again? (yes or no)')
    return input().lower().startswith('y')


def playAgainWithCheck():
    # This function returns True if the player wants to play again, otherwise it returns False.
    # The answer is checked
    while True:
        answer=input('Do you want to play again? (yes or no):')
        if (answer.lower()=='y' or answer.lower()=='yes'):
            return True
        elif (answer.lower()=='n' or answer.lower()=='no'):
            return False
        else:
            print("Please answer just yes/no or y/n")

def printCustomMessage(message):
    print (" ")
    print ("-----------------------------")
    print ("***",message,"***")
    print ("-----------------------------")
    print (" ")

    return

def DebugMode():
    secretWord = getRandomWord(words)
    print "Game started in DEBUG MODE"
    print ("[DEBUG] --- secret word:",secretWord)


list1=[]

def readCSV(K):
    #with open('hangmanWordList.csv', 'rb') as f:
    try:
        global list1
        with open( K, 'rb') as f:
            reader = csv.reader(f)
            for row in reader:
                list1=list1+row
                return list1
    except IOError:
        print "No such file or directory with name",K



#- MAIN -
clearScreen()

print('H A N G M A N')

print "Please chose a option: \n-1 Start DEBUG MODE \n-2 Upload game loading words from a csv file \n-3 Start Game"

ch=input(">>> ")

missedLetters = ''

correctLetters = ''

secretWord = getRandomWord(words)

gameIsDone = False

while True:
    if ch == 1:
        DebugMode()
        print "Play!!"

        displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)

        guess = getGuess(missedLetters + correctLetters)

        if guess in secretWord:
            correctLetters = correctLetters + guess
            foundAllLetters = True
            for i in range(len(secretWord)):
                if secretWord[i] not in correctLetters:
                    foundAllLetters = False
                    break
            if foundAllLetters:
                print('Yes! The secret word is "' + secretWord + '"! You have won!')
                gameIsDone = True
        else:
            missedLetters = missedLetters + guess
            if len(missedLetters) == len(HANGMANPICS) - 1:
                displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
                print('You have run out of guesses!\nAfter ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')
                gameIsDone = True
        if gameIsDone:
            if playAgainWithCheck():
                initGame(words)
            else:
                printCustomMessage("Good Bye!!! :-) ")
                break
        clearScreen()
#################################################################################################################
    elif ch == 2:
        namefile=raw_input("Please write the name of file: ")
        readCSV(namefile)
        secretWord = getRandomWord(list1)
        print "Play!!"

        displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)

        guess = getGuess(missedLetters + correctLetters)

        if guess in secretWord:
            correctLetters = correctLetters + guess
            foundAllLetters = True
            for i in range(len(secretWord)):
                if secretWord[i] not in correctLetters:
                    foundAllLetters = False
                    break
            if foundAllLetters:
                print('Yes! The secret word is "' + secretWord + '"! You have won!')
                gameIsDone = True
        else:
            missedLetters = missedLetters + guess
            if len(missedLetters) == len(HANGMANPICS) - 1:
                displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
                print('You have run out of guesses!\nAfter ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')
                gameIsDone = True
        if gameIsDone:
            if playAgainWithCheck():
                initGame(words)
            else:
                printCustomMessage("Good Bye!!! :-) ")
                break
        clearScreen()

#################################################################################################################
    elif ch == 3:
        secretWord = getRandomWord(words)
        print "Play!!"

        displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)

        guess = getGuess(missedLetters + correctLetters)

        if guess in secretWord:
            correctLetters = correctLetters + guess
            foundAllLetters = True
            for i in range(len(secretWord)):
                if secretWord[i] not in correctLetters:
                    foundAllLetters = False
                    break
            if foundAllLetters:
                print('Yes! The secret word is "' + secretWord + '"! You have won!')
                gameIsDone = True
        else:
            missedLetters = missedLetters + guess
            if len(missedLetters) == len(HANGMANPICS) - 1:
                displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
                print('You have run out of guesses!\nAfter ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')
                gameIsDone = True
        if gameIsDone:
            if playAgainWithCheck():
                initGame(words)
            else:
                printCustomMessage("Good Bye!!! :-) ")
                break
        clearScreen()

1 Risposte

Devi accedere o registrarti per scrivere nel forum
1 risposte