import time, random
#WELSCR
print(WOF1)
print("\n")
print(WOF2)
print("\n"*2)
input("Hit enter to play")
print("\n"*45)
print(WOF1)
print("\n")
print(WOF2)
doublespace = print("\n\n")
singlespace = print("\n")
tripplespace = print("\n\n\n")
guessed = []
score = 1000
wrong = 0
puzzle , hint = random.choice(questions)
blank = puzzle
for round in range (1,10):
tries = 0
iscorrect = False
while (not iscorrect) and (tries < 6):
blank = puzzle
for letter in blank:
if letter in "abcdefghijklmnopqrstuvwxyz":
blank = blank.replace(letter, "-")
def print_puzzle():
print("\n"*45)
print(WOF1)
print("\n")
print(WOF2)
print("\n"*2)
print(blank.center(80))
print("The hint is:",hint.title())
print("You currently have $",score)
print_puzzle()
input("enter")
break
break
This is the beginning of my program that I just started, a wheel of fortune game for a class. I can get it to replace almost all of the letters with a dash, however, there are the occasional few letters that do not always get hidden by this code and I'm not sure why. I have a variable defined as question which is a nested tuple but I did not include it because it's long and contains about 150 different entries.
Nevermind, the problem was case sensitivity. I had proper nouns and capitalized them, but I did not include capital letters in my replace string.
Related
hello i m new to python and i m making a mud game so i m stuck at a certain point where i have to create a character and following is my code. as i need to give 2 option to the player with the description and then player will select one of the given choices. help me with the code in python.
def selectcharacter():
character = ""
while character != "Red pirate" and character != "dreed prince":
character = input("which character you want to choose? (Red pirate or Dreed prince ):")
return character
def checkcharacter(chosencharacter):
if (chosencharacter == Red pirate):
print("the ability of the character is to fight close range battles and has 125 health and 50 armor!"),
if (chosencharacter == Dreed prince):
print("the ability of the character is to fight long range battles and has 100 health and 25 armor!")
else:
print("no character selected.please select the character!")
checkcharacter()
selectcharacter()
You have some syntax errors and you need to pass a string as a function argument.
From what I can tell you want to first select a character and then change the output based on your selection.
Your code is almost working you just need to fix the syntax errors and save the selection in a variable, to be able to pass it to the next function.
def selectcharacter():
character = ""
while character != "Red pirate" and character != "Dreed prince":
character = input("which character you want to choose? (Red pirate or Dreed prince ):")
return character
def checkcharacter(chosencharacter):
if (chosencharacter == "Red pirate"): # should be string
print("the ability of the character is to fight close range battles and has 125 health and 50 armor!"),
elif (chosencharacter == "Dreed prince"): # should be string
print("the ability of the character is to fight long range battles and has 100 health and 25 armor!")
else:
print("no character selected.please select the character!")
selected_character = selectcharacter()
checkcharacter(selected_character)
The characters should be converted to strings, so you can check if they are equal to the passed argument chosencharacter. You also should use an elif instead of a second if because, otherwise the second if would get evaluated (to False) even if the first one is True.
I have a python code that is a song guessing game, you are given the artist and the songs first letter, I used 2 2d arrays with on being the artist and the other being the song. I know I should've done a 3d array though to change it this late into my code I'd have to restructure the whole code and I wouldn't have time. Here is the appropriate code below:
attemptnum = 5
attempts = 0
for x in range (10):
ArtCount = len(artist)
print(ArtCount)
randNum = int(random.randint(0, ArtCount))
randArt = artist[randNum]
ArtInd = artist.index(randArt)# catches element position (number)
songSel = songs[randNum]
print ("The artist is " + randArt)
time.sleep(1)
print( "The songs first letter be " + songSel[0])
time.sleep(1)
print("")
question = input("What song do you believe it to be? ")
if question == (songSel) or ("c"):
songs.remove(songSel)
artist.remove(randArt)
print ("Correct")
print ("Next Question")
else:
attempts = attempts + 1
att = attemptnum = attemptnum - attempts
print("")
print("Wrong,")
print (att) and print (" attempts left.")
print("")
time.sleep(0.5)
if attempts == 5:
print("GAME OVER")
#input leaderboard here
print("Exiting in 3 seconds")
time.sleep(3)
exit()
Apologies if my code isn't so polished, this is a project for school. So what this code does is randomly a number from 0 to the number of how many elements the artist's list has. It then chooses an artist using the random number, it catches the number used with index so that it can be used on the songs array to get the corresponding song (I know very bad) It pitches the question and shows the first letter of the song. If you get the song you get the same code again but with the prior song and artist removed to prevent dupes. That's where the problem comes in, when usually running the code it'll randomly give me the error where the element I'm trying to output is not in the list:
randArt = artist[randNum]
IndexError: list index out of range
This can happen anywhere throughout the code when you're being asked a question, you can get to question 3 and get the error, or not even get to question 9 and get the error. It's completely random. I feel like its trying to occasionally get a hold of an artist and song that's been removed but that doesn't make sense since it only chooses from the amount counted on the list, not the original 10. I'm not sure if my way of saying it is right or if any one would understand, because I sure don't. To clarify, my code counts how many elements there are in the list, uses that number to find a song and artist, then removes it after to stop duping, but from what I can see it seems like it's trying to find and element simply out of the range of how many elements there actually are. Thanks for bearing with my amateur code.
random.randint is inclusive in both ends. randint(0, 10) will return a number in the range
0 <= _ <= 10.
However Python uses 0-based indexes.
If li is [1, 2, 3] then len(li) is 3, but li[3] does not exist.
Only li[0], li[1] and li[2] do.
When you are doing
ArtCount = len(artist)
randNum = int(random.randint(0, ArtCount))
randArt = artist[randNum]
You are asking for a number in the range 0 <= n <= len(artist). If n == len(artist) then artist[n] will cause an IndexError.
BTW, randint returns an int (hence the int in its name). int(randint(...)) is totally unnecessary.
You should either ask for a random number in the range 0 <= n <= len(artist) - 1 or simply use random.choice:
randArt = random.choice(artist)
You may want to catch an IndexError just in case artist is an empty list:
try:
randArt = random.choice(artist)
except IndexError:
print('artist list is empty')
Mastermind Game using "ABCEF"I dont know how to check whether it is partial correct. I have to use red to mean correct letter and position. I use white to mean correct letter.
import random
def play_one_round():
N_code=''.join(random.sample("ABCDEF",4))
print (N_code)
guess=input("Enter your guess as 4 letters e.g. XXXX:")
count_guess= 1
while N_code != guess and count_guess < 10:
check(N_code,guess)
guess=input("Enter your guess as 4 letters e.g. XXXX:")
count_guess=count_guess + 1
print("This is your",count_guess, "guess")
if guess==N_code:
print('r') #Here I have if the code and guess are equal print r, which mean its the right letters in the right order.
def check(N_code,guess):
result=['r' if c1==c2 else c2 for c1,c2 in zip(guess, N_code)]
for index, char in enumerate(guess):
if result[index] !='r':
if char in result:
result[result.index(char)]='w'
print(result)
def Master_m():
print("Welcome to Mastermind!\n")
print("Start by Choosing four letters")
play_one_round()
answer=input("Play Again? ")
if answer[0]=='y':
Master_m()
Master_m()
I wrote this ages ago but it will do the trick
import random
import itertools
def start():
""" this function is used to initialise the users interaction with the game
Primarily this functions allows the user to see the rules of the game or play the game"""
print ('Mastermind, what would you like to do now?\n')
print ('Type 1 for rules')
print ('Type 2 to play')
path = input('Type your selection 1 or 2: ')
if path == '1':
print ('Great lets look at the rules')
rules()
elif path == '2':
print('Great lets play some Mastermind!\n')
begingame()
start()
else:
print('that was not a valid response there is only one hidden option that is not a 1 or a 2')
start()
def rules():
"""This just prints out the rules to the user."""
print ('The rules are as follows:\n')
print ('1)Mastermind will craft you a 4 digit number that will contain all unique numbers from 1-9, there is no 0s.\n')
print ('2)You will have 12 attempts to guess the correct number.\n')
print ('3)Whites represent a correct number that is not in the correct order\n')
print ('4)Reds represent a correct number in the correct order.\n')
print ('5)If you enter a single number or the same number during a guess it will consume 1 of your 12 guesses.\n')
print ('6)to WIN you must guess the 4 numbers in the correct order.\n')
print ('7)If you run out of guesses the game will end and you lose.\n')
print ('8)if you make a guess that has letters or more than 4 digits you will lose a turn.')
start()
def makeRandomWhenGameStarts():
"""A random 4 digit number is required this is created as its own
variable that can be passed in at the start of the game, this allows the user
to guess multiple times against the one number."""
#generate a 4 digit number
num = random.sample(range(1,9), 4)
#roll is the random 4 digit number as an int supplied to the other functions
roll = int(''.join(map(str,num)))
return roll
def begingame():
"""This is the main game function. primarily using the while loop, the makeRandomWhenGameStarts variable is
passed in anbd then an exception handling text input is used to ask the user for their guees """
print ('please select 4 numbers')
#bring in the random generated number for the user to guess.
roll = makeRandomWhenGameStarts()
whiteResults = []
redResults = []
collectScore = []
guessNo = 0
#setup the while loop to end eventually with 12 guesses finishing on the 0th guess.
guesses = 12
while (guesses > 0 ):
guessNo = guessNo + 1
try:
#choice = int(2468) #int(input("4 digit number"))
choice = int(input("Please try a 4 digit number: "))
if not (1000 <= choice <= 9999):
raise ValueError()
pass
except ValueError:
print('That was not a valid number, you lost a turn anyway!')
pass
else:
print ( "Your choice is", choice)
#Use for loops to transform the random number and player guess into lists
SliceChoice = [int(x) for x in str(choice)]
ranRoll = [int(x) for x in str(roll)]
#Take the individual digits and assign them a variable as an identifier of what order they exist in.
d1Guess = SliceChoice[0:1]
d2Guess = SliceChoice[1:2]
d3Guess = SliceChoice[2:3]
d4Guess = SliceChoice[3:4]
#combine the sliced elements into a list
playGuess = (d1Guess+d2Guess+d3Guess+d4Guess)
#Set reds and whites to zero for while loop turns
nRed = 0
nWhite = 0
#For debugging use these print statements to compare the guess from the random roll
# print(playGuess, 'player guess')
# print(ranRoll,'random roll')
#Use for loops to count the white pegs and red pegs
nWhitePegs = len([i for i in playGuess if i in ranRoll])
nRedPegs = sum([1 if i==j else 0 for i, j in zip(playGuess,ranRoll)])
print ('Oh Mastermind that was a good try! ')
#Take the results of redpegs and package as turnResultsRed
TurnResultsRed = (nRedPegs)
#Take the results of whitepegs and remove duplication (-RedPegs) package as TurnResultsWhite
TurnResultsWhite = ( nWhitePegs - nRedPegs) #nWhite-nRed
#Create a unified list with the first element being the guess number
# using guessNo as an index and storing the players choice and results to feedback at the end
totalResults = ( guessNo,choice , TurnResultsWhite ,TurnResultsRed)
# collectScore = collectScore + totalResults for each turn build a list of results for the 12 guesses
collectScore.append(totalResults)
#End the while loop if the player has success with 4 reds
if nRed == (4):
print('Congratulations you are a Mastermind!')
break
#Return the results of the guess to the user
print ('You got:',TurnResultsWhite,'Whites and',TurnResultsRed,'Red\n')
#remove 1 value from guesses so the guess counter "counts down"
guesses = guesses -1
print ('You have', guesses, "guesses left!")
#First action outside the while loop tell the player the answer and advise them Game Over
print('Game Over!')
print('The answer was', roll)
#At the end of the game give the player back their results as a list
for x in collectScore:
print ('Guess',x[0],'was',x[1],':','you got', x[2],'Red','and', x[3],'Whites')
if __name__ == '__main__':
start()
When you are stuck, decompose into smaller chunks and test those. Focusing on check, you can check whether a guess letter exactly matches the code via its index and whether its in the code at all with in. Here is a self-contained example. Notice that I've pulled out everything except the problem at hand.
If this works for you, I suggest writing a self-contained example of your next problem, test it, and if you are still stuck, post that as a new question.
def check(N_code, guess):
print('code', N_code, 'guess', guess)
result = []
# enumerate gives you each letter and its index from 0
for index, letter in enumerate(guess):
if N_code[index] == letter:
# right letter in right position
vote = 'red'
elif letter in N_code:
# well, at least the letter is in the code
vote = 'white'
else:
# not even close
vote = 'black'
# add partial result
result.append('{} {}'.format(letter, vote))
# combine and print
print(', '.join(result))
check('ABCD', 'ABCD')
check('DEFA', 'ABCD')
I'm trying to create a word guessing game, after each guess the computer should return the frequency of letters in the right place, however it is this part that I have been unable to manage to get working. Can anyone help me?
import random
def guess(secret,testWord):
return (len([(x, y) for x, y in zip(secret, testWord) if x==y]))
words = ('\nSCORPION\nFLOGGING\nCROPPERS\nMIGRAINE\nFOOTNOTE\nREFINERY\nVAULTING\nVICARAGE\nPROTRACT\nDESCENTS')
Guesses = 0
print('Welcome to the Word Guessing Game \n\nYou have 4 chances to guess the word \n\nGood Luck!')
print(words)
words = words.split('\n')
WordToGuess = random.choice(words)
GameOn = True
frequencies = []
while GameOn:
currentguess = input('\nPlease Enter Your Word to Guess from the list given').upper()
Guesses += 1
print(Guesses)
correctLength = guess(WordToGuess,currentguess)
if correctLength == len(WordToGuess):
print('Congragulations, You Won!')
GameOn = False
else:
print(correctLength, '/', len(WordToGuess), 'correct')
if Guesses >= 4:
GameOn = False
print('Sorry you have lost the game. \nThe word was ' + WordToGuess)
In your guess function, you are printing the value, not returning it. Later, however, you try to assign something to correctLength. Just replace print by return, and your code should work.
Update to answer question in comments:
I think a very easy possibility (without a lot of changes to your code posted in the comment) would be to add an else clause, such that in case that the input is empty, you return directly to the start of the loop.
while GameOn:
currentguess = input('\nPlease Enter Your Word to Guess from the list given').upper()
if len(currentguess) <=0:
print('Sorry you must enter a guess')
else:
correctLength = guess(WordToGuess,currentguess)
if correctLength == len(WordToGuess):
print('statement')
GameOn = False
elif Guesses <= 0:
GameOn = False
print('statement')
else:
Guesses = Guesses -1
print('statement')
print('statment')
What I am trying to do is alter my original hangman game into what is called evil hangman. In order to do this, I need to first generate a random length of a word and pull out all words of that length from the original list.
Here is the code I am working with:
def setUp():
"""shows instructions, reads file,and returns a list of words from the english dictionary"""
try:
print(60*'*' +'''\n\t\tWelcome to Hangman!\n\t
I have selected a word from an english dictionary. \n\t
I will first show you the length of the secret word\n\t
as a series of dashes.\n\t
Your task is to guess the secret word one letter at a time.\n\t
If you guess a correct letter I will show you the guessed\n\t
letter(s) in the correct position.\n
You can only make 8 wrong guesses before you are hanged\n
\t\tGood luck\n''' + 60*'*')
infile=open('dictionary.txt')
l=infile.readlines()# list of words from which to choose
infile.close()
cleanList = []
for word in l:
cleanList.append(l[:-1])
return(cleanList)
except IOError:
print('There was a problem loading the dictionary file as is.')
def sort_dict_words_by_length(words):
"""Given a list containing words of different length,
sort those words based on their length."""
d = defaultdict(list)
for word in words:
d[len(word)].append(word)
return d
def pick_random_length_from_dictionary(diction):
max_len, min_len = ( f(diction.keys()) for f in (max, min) )
length = random.randint(min_len, max_len)
return diction[length]
def playRound(w,g):
""" It allows user to guess one letter. If right,places letter in correct positions in current guess string g, and shows current guess to user
if not, increments w, number of wrongs. Returns current number of wrongs and current guess string"""
print('You have ' + str(8 - w) + ' possible wrong guesses left.\n')
newLetter = input('Please guess a letter of the secret word:\n')
glist = list(g)#need to make changes to current guess string so need a mutable version of it
if newLetter in secretWord:
for j in range (0,len(secretWord)):
if secretWord[j]==newLetter:
glist[j] = newLetter
g = ''.join(glist)#reassemble the guess as a string
print('Your letter is indeed present in the secret word: ' + ' '.join(g)+'\n')
else:
w += 1
print('Sorry, there are no ' + newLetter + ' in the secret word. Try again.\n')
return(w,g)
def endRound(wr, w,l):
"""determines whether user guessed secret word, in which case updates s[0], or failed after w=8 attempts, in s\which case it updates s[1]"""
if wr == 8:
l += 1
print('Sorry, you have lost this game.\n\nThe secret word was '+secretWord +'\n')#minor violation of encapsulation
else:
w +=1
print(15*'*' + 'You got it!' + 15*'*')
return(w,l)
def askIfMore():
"""ask user if s/he wants to play another round of the game"""
while True:
more = input('Would you like to play another round?(y/n)')
if more[0].upper() == 'Y' or more[0].upper()=='N':
return more[0].upper()
else:
continue
def printStats(w,l):
"""prints final statistics"""
wGames='games'
lGames = 'games'
if w == 1:
wGames = 'game'
if l ==1:
lGames = 'game'
print('''Thank you for playing with us!\nYou have won {} {} and lost {} {}.\nGoodbye.'''.format(w,wGames,l,lGames))
try:
import random
from collections import defaultdict
words=setUp()#list of words from which to choose
won, lost = 0,0 #accumulators for games won, and lost
while True:
wrongs=0 # accumulator for wrong guesses
secretWord = random.choice(words)[:#eliminates '\n' at the end of each line
print(secretWord) #for testing purposes
guess= len(secretWord)*'_'
print('Secret Word:' + ' '.join(guess))
while wrongs < 8 and guess != secretWord:
wrongs, guess = playRound(wrongs, guess)
won, lost = endRound(wrongs,won,lost)
if askIfMore()== 'N':
break
printStats(won, lost)
except:
quit()
What I would like to do is generate a random number with the lower bound being the shortest length word and the upper bound being the highest length word, and then use that random number to create a new container with words of only that length, and finally returning that container to be used by the game further. I tried using min and max, but it seems to only return the first and last item of the list instead of showing the word with the most characters. Any help is appreciated.
If your 'dictionary.txt' has a single word on each line, you could use the following, which is speed efficient, because it'll only go over the list once. But it'll consume the memory of your original list again.
from collections import defaultdict
import random
def sort_dict_words_by_length(words):
"""Given a list containing words of different length,
sort those words based on their length."""
d = defaultdict(list)
for word in words:
d[len(word)].append(word)
return d
def pick_random_length_from_dictionary(diction):
max_len, min_len = ( f(diction.keys()) for f in (max, min) )
length = random.randint(min_len, max_len)
return diction[length]
You would then pass the output from your setUp to sort_dict_words_by_length and that output to pick_random_length_from_dictionary.
If you are memory-limited, then you should first go over all words in the wordlist, keeping track of the minimal and maximal length of those words and then reiterate over that wordlist, appending only those words of the desired length. What you need for that is mentioned in the code above and just requires some code reshuffling. I'll leave that up to you as an exercise.