I need to replace 1 symbol in a string with a letter, like a decoder game, but with the code I have currently created. I need to develop the part of the program that when someone inputs a symbol and a letter it replaces the symbol with the letter and saves the list, then you keep doing this untill all the symbols have been replaced to create a word.
The list of encoded words:
#+/084&"
#3*#%#+
8%203:
,1$&
!-*%
.#7&33&
#*#71%
&-&641'2
#))85
9&330*
The List of words uncoded:
ACQUIRED
ALMANAC
INSULT
JOKE
HYMN
GAZELLE
AMAZON
EYEBROWS
AFFIX
VELLUM
Clues:
A#
M*
N%
Code:
#Import Section
import random
import string
class Game():
def __init__(self):
words_open = open('Words.txt')
self.words = (words_open.read())
self.fixwords = self.words
solved_open = open('solved.txt')
self.solved = (solved_open.read())
def menu_display(self):
#Display the menu
self.menud = (''' MENU
1. Start Game
2. Quit Game
Please select 1 or 2''')
self.menu()
def menu(self):
print self.menud
#ask player to choose an option
self.menu_choice = raw_input(" >>> ")
print
self.menu_options()
def menu_options(self):
#When menu option is selected
if self.menu_choice == '1':
self.s_game()
elif self.menu_choice == '2':
pass
else:
print "not valid input"
self.menu()
def s_game(self):
print 'Words:'
print self.words
self.clues()
def clues(self):
clue = raw_input('Do you want clues? please enter Yes or No '
'>>> ')
clue = clue.upper()
print clue
clues_open = open('clues.txt')
self.cluesclues = (clues_open.read())
if clue == 'YES':
print '''Words:
'''
print self.words
print 'Clues:'
print self.cluesclues
self.sorting()
elif clue == 'NO':
print self.words
self.sorting()
else:
print "input is not valid"
self.clues()
def sorting(self):
#if self.fixwords == 0:
#self.fixwords = (words_open.read())
#else:
#pass
self.symbol = raw_input("what symbol would you like to replace? >>> ")
if self.symbol in self.fixwords:
self.nletter = raw_input("that symbol is valid, what letter would you like to swap it with >>> ")
self.nletter.upper()
#self.fixwords.replace(self.symbol, self.letter[, max])
#self.fixwords.replace(self.symbol, self.nletter)
string.replace(self.fixwords, self.symbol, self.nletter.upper)
print self.fixwords
print self.cluesclues
self.prechange()
elif self.symbol not in self.fixwords:
print "That symbol is not valid or has already been changed"
self.sorting()
def prechange(self):
self.change = raw_input("Do you want to change a letter for another letter? yes or no >>> ")
self.change = self.change
if self.change == "yes":
self.changing()
elif self.change == "no":
self.sorting()
else:
print "that is not a valid input"
self.prechange()
def changing(self):
self.chanlet = raw_input("what letter would you like to replace? >>> ")
if self.chanlet in self.fixwords:
self.letchan = raw_input("that letter is valid, what letter would you like to swap it with >>> ")
self.fixwords = string.replace(self.fixwords, self.chanlet, self.letchan)
print self.fixwords
self.sorting()
elif self.chanlet not in self.fixwords:
print "That letter does not exist"
self.changing()
game = Game()
game.menu_display()
you can use replace() function. It can replace any character in a string even if it exists several times. All you have to do is each time a user select a symbol to replace and a letter, you loop on the list of encoded words and replace that symbol with the letter :
symbol = input("Enter the symbol to replace : ")
letter = input("Enter the letter : ")
for i in range(0, len(encoded_list)) :
encoded_list[i] = encoded_list[i].replace(symbol, letter, len(encoded))
Related
This is my dictionary:
def get_dic(filename):
count = 0
db = {}
filename = "words.txt"
with open(filename, "r") as infile:
for line in infile:
if line:
eng_words, spa_words = line.rstrip().split(":")
key = eng_words
val = spa_words.split(",")
db[key] = val
count += 1
print(count, "entries found.")
return db
this is the file it reads from and converts it to a dictionary:
library:la biblioteca
school:el colegio,la escuela
restaurant:el restaurante
movie theater:el cine
airport:el aeropuerto
museum:el museo
park:el parque
university:la universidad
office:la oficina,el despacho
house:la casa
Now I wanna call my db and make a "quiz" game using random() method after user inputs a number from 1 to 10. Since my list is only 10 lines.
import random
def main():
db = get_dic(filename)
random.shuffle(db)
for keyword in db(10):
display = "{}"
print(display.format(keyword))
userinput = input("Enter 1 equivalent Spanish word(s). Word [1]: ")
print(db[keyword])
print(" ")
if userinput == (db[key]):
print("correct!")
correct += 1
If input is "5", how do I get the program to print 5 words?
And I wanna return the score "correct" into another function that is not main(). Which will later write the score to a seperate .txt file, Is this possible? Do I just "return correct" and call it in a function like usual? I've only seen codes call function in "def main():"
output example if input choosen is 2:
English word: museum
Enter 1 equivalent Spanish word(s). Word [1]: el museo
Correct!
---
English word: school
Enter 2 equivalent Spanish word(s). Word [1]: el colegio
Word [2]: la escuela
Correct!
This may be what you want. I ask the user how many rounds first. (I have not validated this input, though)
def main():
db = get_dic(filename)
keys = list(db.keys())
random.shuffle(keys)
rounds = int(input('Enter a number of rounds (1-10): '))
correct = 0
for keyword in keys[:rounds]:
print(keyword)
userinput = input("Enter 1 equivalent Spanish word(s). Word [1]: ")
print(db[keyword])
print(" ")
if userinput == (db[keyword]):
print("correct!")
correct += 1
return correct
correct = main()
print(f'{correct} answers correct')
to validate the input you can also do
def get_num(text,err_text,verify):
try:
the_input = int(input(text))
if verift(the_input):
return the_input
else:
print(err_text)
return get_num(text,err_text)
except:
print(err_text)
return get_num(text,err_text)
#...
rounds = get_num('Enter a number of rounds (1-10): ', 'please enter an integer between 1 and 10', verify=lambda x:x>0 and x <11)
Right sorry, heres the code
level_1 = "The _1_ man in the _2_ place can make all the _3_ in the _4_"
level_2 = "We both _1_ a lot of _2_ that you're going to _3_. But I _4_ \ we
can put our _5_ behind us. For science. " \
"You _6_ "
level_3 = "Everyone I have _1_ for has either _2_ or left me._3_ f***ing
except for \ _4_! So don't _5_ me I'd be _6_ " \
"with somebody else, because the _7_ is I would just be more _8_ "
blank_words = ["_1_", "_2_", "_3_", "_4_", "_5_", "_6_", "_7_", "_8_", ]
level_1_answers = ["right", "wrong", "difference", "world"]
level_2_answers = ["said", "things", "regret", "think", "differences",
"monster"]
level_3_answers = ["cared", "died", "everyone", "you", "tell", "safer",
"truth", "scared"]
def level_selector():
"""Gets input from the user to see which level the game starts on"""
while True:
try:
level = int(raw_input("There are 3 levels, pick which to start
with \n -->"))
except ValueError:
print "Please select a NUMBER"
else:
if 1 <= level <= 3:
if level == 1:
return level_1, level_1_answers, level
elif level == 2:
return level_2, level_2_answers, level
elif level == 3:
return level_3, level_3_answers, level
else:
print "Select a number within the level range"
def blanks_to_fill(word, blanks):
for blank in blanks:
if blank in word:
return blank
return None
def fill_blanks(word, replaced, blanks, user_input, index):
if blanks_to_fill(word, blanks) is None:
if word not in replaced:
replaced.append(word)
else:
replacement = blanks_to_fill(word, blanks)
word = word.replace(replacement, user_input.upper())
if replacement == blanks[index]:
if replacement not in replaced:
replaced.append(word)
else:
position = replaced.index(replacement)
replaced[position] = word
else:
replaced.append(replacement)
return replaced
def format_answers(quote, blanks, replaced, user_input, index):
split_quote = quote.split()
if type(replaced) == str:
replaced = replaced.split()
for word in split_quote:
fill_blanks(word, replaced, blanks, user_input, index)
replaced = " ".join(replaced)
return replaced
def user_answer(level, quote, answers):
replaced = []
user_input = ""
index = 0
blank_range = len(answers)
for blank in blank_words[:blank_range]:
prompt = "Fill the blank for " + blank
print prompt
user_input = raw_input("-->")
user_input = user_input.lower()
while user_input != answers[index]:
print "Incorrect, please try again."
user_input = raw_input("-->")
user_input = user_input.lower()
print "Good job!"
replaced = format_answers(quote, blank_words, replaced, user_input,
index)
print replaced
index += 1
return replaced, index
def play_again():
user_response = raw_input("Would you like to play again, yes or
no?").lower()
if user_response.startswith("y"):
play()
else:
pass
def play():
quote, answers, level = level_selector()
print quote
replaced = user_answer(level, quote, answers)
print "Well done, you finished the level"
play_again()
play()
The output I'm meant to get is the quote from the selected level with the correct response from the player. Instead I'm getting an output like http://i.imgur.com/ESAOFBB.png where words are missing and the "blank" placeholders are being tagged on the end of the output. From what I can see the problem is either in the "fill_blanks" or the "format_answers" functions but I can't see it myself.
Perhaps a fresh pair of eyes can shed some light.
Greatly appreciated if you do respond, I've tried for the most part to do it myself, but I just hit a brick wall
OK so what I need to do is make my code only allow the user to enter one letter and then one symbol at a time. The example below shows what I want in a better view.
At the moment my code allows the user to enter more than one character at a time which I don't want.
What letter would you like to add? hello
What symbol would you like to pair with hello
The pairing has been added
['A#', 'M*', 'N', 'HELLOhello']
What I want is a message to be displayed like this and the pairing not to be added to the list.
What letter would you like to add? hello
What symbol would you like to pair with hello
You have entered more than one character, the pairing was not added
['A#', 'M*', 'N',].
So far my code for this section is as follows...
It would also be great for when the user enters a number in the letter section, an error message to be printed.
def add_pairing(clues):
addClue = False
letter=input("What letter would you like to add? ").upper()
symbol=input("\nWhat symbol would you like to pair with ")
userInput= letter + symbol
if userInput in clues:
print("The letter either doesn't exist or has already been entered ")
elif len(userInput) ==1:
print("You can only enter one character")
else:
newClue = letter + symbol
addClue = True
if addClue == True:
clues.append(newClue)
print("The pairing has been added")
print (clues)
return clues
The easiest way to ensure user input is with a loop:
while True:
something = raw_input(prompt)
if condition: break
Something set up like this will continue to ask prompt until condition is met. You can make condition anything you want to test for, so for you, it would be len(something) != 1
Your method can be simplified to the following if you let the user enter a letter and symbol pair:
def add_pairing(clues):
pairing = input("Please enter your letter and symbol pairs, separated by a space: ")
clues = pairing.upper().split()
print('Your pairings are: {}'.format(clues))
return clues
Not exactly sure what you want to return but this will check all the entries:
def add_pairing(clues):
addClue = False
while True:
inp = input("Enter a letter followed by a symbol, separated by a space? ").upper().split()
if len(inp) != 2: # make sure we only have two entries
print ("Incorrect amount of characters")
continue
if not inp[0].isalpha() or len(inp[0]) > 1: # must be a letter and have a length of 1
print ("Invalid letter input")
continue
if inp[1].isalpha() or inp[1].isdigit(): # must be anything except a digit of a letter
print ("Invalid character input")
continue
userInput = inp[0] + inp[1] # all good add letter to symbol
if userInput in clues:
print("The letter either doesn't exist or has already been entered ")
else:
newClue = userInput
addClue = True
if addClue:
clues.append(newClue)
print("The pairing has been added")
print (clues)
return clues
I am fan of raising and catching exceptions in similar cases. Might be shocking for people with 'C-ish' background (sloooow), but it is perfectly pythonic and quite readable and flexibile in my opinion.
Also, you should add check for characters outside of set you are expecting:
import string
def read_paring():
letters = string.ascii_uppercase
symbols = '*##$%^&*' # whatever you want to allow
letter = input("What letter would you like to add? ").upper()
if (len(letter) != 1) or (letter not in letters):
raise ValueError("Only a single letter is allowed")
msg = "What symbol would you like to pair with '{}'? ".format(letter)
symbol = input(msg).upper()
if (len(symbol) != 1) or (symbol not in symbols):
raise ValueError("Only one of '{}' is allowed".format(symbols))
return (letter, symbol)
def add_pairing(clues):
while True:
try:
letter, symbol = read_paring()
new_clue = letter + symbol
if new_clue in clues:
raise ValueError("This pairing already exists")
break # everything is ok
except ValueError as err:
print(err.message)
print("Try again:")
continue
# do whatever you want with letter and symbol
clues.append(new_clue)
print(new_clue)
return clues
import random
words=["cat", "dog", "animal", "something", "whale", "crocodile", "lion", "summer", "boston", "seattle"]
the_word=random.choice(words)
#print(the_word)
a=len(the_word) #number of letter in the word
c=['_'for i in range(a)]#blanks seperated
blanks=" ".join(c)
print("This is a word with",a,"letter")
print("\t", blanks)
guess=0
while guess<3:
answer=input("Please enter a letter: ")
if answer in the_word:
the_index=the_word.index(answer)#find the index
c[the_index]=answer
blanks=" ".join(c)
print(blanks)
else:
guess=guess+1
print("There is no",answer,"in the word.")
I have two problems:
1st I can't reveal 2 words, summer for example, if a user input 'm' it will reveal only the first letter 'm'
2nd when the user input more than one word the program still consider right answer. For example: The user input "nm" for the word "something" the program still consider it right, and the word turn out like this "somethinmg"
You can check the length of answer via something like
if len(answer) != 1:
print "Please enter just one letter"
Or you can simply take only the first letter of what they enter
letter = answer[0]
See How to find all occurrences of an element in a list? on how to find multiple indexes that match.
Okay first of all to do the display I would take the word, split it up into letters and then create a list with the same length containing all '_'. This way you could display the _ _ _ _ etc by calling ' '.join(substitutelist)....
To get multiple letter responses:
each guess call
for letter in range(len(word)):
if word[letter]==guess.lower():
substitutelist[letter]=guess.lower()
Then every time a letter was called I would add it to a list titled something like "USED" and check each guess to make sure its not in zip(word, used) and if it is return a message error.
Here is an example hangman code I wrote to show the different functions...
import re, sys
from random import choice
def showmap(hangmanpic):
"""Will show the hangman pic after subtracting any
characters holding the place of a future body part"""
tempmap=''
x=str(range(7))
for i in hangmanpic:
if i in x:
tempmap+=' '
else:
tempmap+=i
return tempmap
def addbodypart(remaining, hangmanmap):
"""takes the hangman map and substitutes in a body
part when a wrong answer is chosen. Returns the new
hangmanmap"""
bodyparts={'6':'(_)',
'5':'|',
'3':'\\\\',
'2':'\\\\',
'4':'/',
'1':'/'
}
return re.sub(str(remaining), bodyparts[str(remaining)], hangmanmap)
def StartGame(hangmanmap, word):
"""Starts the game"""
dashword, wrong=[], []
remaining=6
for i in word:
dashword.append('_')
while remaining>0:
if '_' not in dashword:
remaining=0
continue
for i in range(5):
print ""
print "Guesses Left = %d" %(remaining)
print showmap(hangmanmap)
print ""
print "Used Letters: %s" %(', '.join(wrong))
print "Word: %s"%(' '.join(dashword))
guess=str(raw_input('Guess a letter:')).lower()
if guess in str(wrong)+str(dashword):
print ""
print "Sorry but you have already guessed that letter. Please guess again."
print ""
continue
if guess not in word:
hangmanmap=addbodypart(remaining, hangmanmap)
remaining-=1
wrong.append(guess)
else:
for i in range(0, len(word)):
if word[i]==guess:
dashword[i]=guess
if '_' not in dashword:
for i in range(5):
print ""
print "You WIN! Congrats"
print "The word was %s" %(word)
print showmap(hangmanmap)
print "Used Letters: %s" %(', '.join(wrong))
print "Word: %s"%(' '.join(dashword))
else:
for i in range(5):
print ""
print showmap(hangmanmap)
print "Word: %s" %(word)
print "Sorry but you've ran out of guesses! You Lose! The correct word was %s" %(word)
def main():
word=str(choice([line.strip() for line in open(sys.argv[1])])).lower()
hangmanmap=""" _________
|/ |
| 6
| 354
| 5
| 1 2
|
___|___"""
print "Welcome to AmazingReds Hangman Game!"
print "6 wrong answers and YOU LOSE! Good Luck."
StartGame(hangmanmap, word)
if __name__ == '__main__':
main()
I'm working on a simple text based hangman game in python. I have a rough program running but I've encountered two minor problems:
Why does the welcome message print twice?
When the user inputs a letter not in the word two times in a row, the second time, the "nope, try again"-message does not display and current word does not display. The first time an incorrect letter is input, it works. Why doesn't it work the second time?
from random import randrange
class HangmanApp:
def __init__(self, interface):
self.infile = open("hangman.txt", "r")
self.interface = textInterface()
for line in self.infile:
self.wordlist = line.split()
self.secretword = self.wordlist[randrange(len(self.wordlist))]
self.letter_list = list(self.secretword)
#tests the user's guess
def guess(self):
self.new_list = ["_"]*len(self.secretword)
#keep loop going as long as there are letters in the list
while self.letter_list != ["_"]*len(self.letter_list):
self.guess = self.interface.guess()
if self.guess in self.letter_list:
while self.guess in self.letter_list:
i = self.letter_list.index(self.guess)
#replace that letter from the list with "_"
self.letter_list[self.letter_list.index(self.guess)] = "_"
#add the chosen letter to a new list for display
self.new_list[i] = self.guess
#print list with letter added
self.interface.correct(self.new_list)
else:
self.interface.incorrect(self.new_list)
self.guess = self.interface.guess()
class textInterface:
def __init__(self):
print("Welcome to Hangman!")
def guess(self):
guess = input("Guess a letter! ")
return guess
def display (self, word):
string = ' '.join(word)
print(string)
def incorrect(self, word):
print("Nope, try again")
self.display(word)
def correct(self, word):
print("Correct")
self.display(word)
def main():
inter = textInterface()
app = HangmanApp(inter)
app.guess()
The welcome message is printed twice because you're creating two instances of textInterface: one in main() and another inside HangmanApp.__init__(). I think you meant to do:
self.interface = interface
instead of
self.interface = textInterface()
Inside HangmanApp.guess(), after receiving an incorrect guess (reaching the else: clause) you have an extra guess prompt that is not needed---one that doesn't pass through your checking code. I think this is probably causing the issue with it not working the second time around.