Python hangman problems - python

So I have my hangman almost working however, it is only placing the first correct guess on the first line, and not continuing if I guess the second letter correctly. Also, no matter what letter I guess, it always draws the head on the third letter guessed. I have it narrowed down to my getGuessLocationInPuzzle function, where my index is always printing out zero even if I have guessed my second letter. I've been staring at this code for 2 and 1/2 hours, and can't solve it. Please help!
''' Import Statements '''
from graphics import *
import copy
import random
import string
def drawGallows(window):
gallows = Rectangle(Point(300,280),Point(200,300))
gallows.draw(window)
gallows = Line(Point(250,300),Point(250,100))
gallows.draw(window)
gallows = Line(Point(250,100),Point(120,100))
gallows.draw(window)
gallows = Line(Point(120,100),Point(120,120))
gallows.draw(window)
def getPuzzle():
fh = open("puzzle.txt","r")
fileList = fh.read()
files = string.split(fileList)
puzzle = random.choice(files)
return puzzle
def drawPuzzle(length, window):
lines = Line(Point(15,275),Point(25,275))
for index in range(length):
newline = copy.copy(lines)
newline.move(20,0)
newline.draw(window)
def getGuess(entry, window):
letter = entry.getText()
return letter
def getValidGuess(Validguesses, entry, window):
guess = getGuess(entry, window)
for index in Validguesses:
if guess == index:
return guess
def createTextOverlay(guess):
textstring = ""
num = ord(guess)
for index in range(num - ord("a")):
textstring = textstring + " "
textstring= textstring + guess
for index in range(25-(ord(guess)-ord("a"))):
textstring = textstring+" "
overlay = Text(Point(150, 375), textstring)
overlay.setFace("courier")
overlay.setFill("red")
return overlay
def updateGallows(numWrongGuesses, window):
if numWrongGuesses==1:
head = Circle(Point(120,140),20)
head.draw(window)
if numWrongGuesses==2:
body = Line(Point(120,220),Point(120,160))
body.draw(window)
if numWrongGuesses==3:
arms1 = Line(Point(100,200),Point(120,160))
arms1.draw(window)
if numWrongGuesses==4:
arms2 = Line(Point(120,160),Point(140,200))
arms2.draw(window)
if numWrongGuesses==5:
leg1 = Line(Point(120,220),Point(100,250))
leg1.draw(window)
if numWrongGuesses==6:
leg2 = Line(Poin(120,220),Point(140,250))
leg2.draw(window)
def updatePuzzleDisplay(locations, letter, window):
# For each value in the locations list, print out the letter above the
# appropriate blank space.
# For each value in locations list, create a text object.
locationonspaces = 35
for index in locations:
locationonspaces = locationonspaces + 5
letterthatisguessed = Text(Point(locationonspaces, 265 ), letter)
letterthatisguessed.draw(window)
# Create text object
def getGuessLocationInPuzzle(puzzle, guess):
word = len(puzzle)
locations = []
for index in range(word):
if puzzle[index]==guess:
locations.append(index)
print guess
print index
return locations
def main():
window = GraphWin("Hangman Final", 400, 400)
drawGallows(window)
lettersToGuess = Text(Point(150, 375), "abcdefghijklmnopqrstuvwxyz")
lettersToGuess.setFace("courier")
lettersToGuess.draw(window)
guessInput = Entry(Point(250, 325), 10)
guessInput.draw(window)
puzzle = getPuzzle()
print puzzle
length = len(puzzle)
drawPuzzle(length,window)
guess = getGuess(guessInput,window)
window.getMouse()
Validguesses = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
numWrongGuesses=0
while True:
guess = getValidGuess (Validguesses,guessInput,window)
#print guess
window.getMouse
locations = getGuessLocationInPuzzle(puzzle,guess)
# print locations
if locations == []:
overlay = createTextOverlay(guess)
overlay.draw(window)
updateGallows(numWrongGuesses,window)
numWrongGuesses = numWrongGuesses + 1
else:
updatePuzzleDisplay(locations, guess, window)
overlay = createTextOverlay(guess)
overlay.draw(window)
if guess !=0:
Validguesses.remove(guess)
window.getMouse()
window.getMouse()
main()

Related

Having problem running python code (Markov Chain project)

I just got into python a few weeks ago and I've been learning the language using the PyCharm software.
I was hoping to use the following code for a project:
https://github.com/eohomegrownapps/markov-music
I installed the required library, and inserted a midi file in the mentioned folder (the input folder). I'm using the following midi file:
http://www.bachcentral.com/invent/invent1.mid
Once I run the code, nothing appears in the 'compositions' folder. Can anyone tell me what I'm doing wrong? I'll post a screenshot of the code below.
Thanks a million in advance
Updated Screenshot
import random
import midi
import datetime
class Markov(object):
"""docstring for Markov"""
def __init__(self, order=2):
super(Markov, self).__init__()
self.order = order
self.chain = {}
def add(self, key, value):
if self.chain.has_key(key):
self.chain[key].append(value)
else:
self.chain[key] = [value]
def load(self, midifile):
pattern = midi.read_midifile(midifile)
# track = pattern[1]
for track in pattern:
noteslist = []
curoffset = 0
for i in track:
if i.name == "Note On" and i.data[1] != 0:
note = (i.data[0], i.data[1], i.tick + curoffset)
# note = (i.data[0],i.data[1],i.tick)
noteslist.append(note)
curoffset = 0
else:
curoffset += i.tick
if len(noteslist) > self.order:
for j in range(self.order, len(noteslist)):
t = tuple(noteslist[j - self.order:j])
print t
print noteslist[j]
self.add(t, noteslist[j])
else:
print "Corpus too short"
def generate(self, length, filename):
pattern = midi.Pattern()
# Instantiate a MIDI Track (contains a list of MIDI events)
track = midi.Track()
# Append the track to the pattern
pattern.append(track)
tick = 0
currenttuple = random.choice(self.chain.keys())
prevnote = False
for i in range(0, self.order):
if prevnote != False:
on = midi.NoteOnEvent(tick=tick, velocity=0, pitch=prevnote)
track.append(on)
on = midi.NoteOnEvent(tick=0, velocity=currenttuple[i][1], pitch=currenttuple[i][0])
track.append(on)
tick = currenttuple[i][2]
prevnote = currenttuple[i][0]
result = random.choice(self.chain[currenttuple])
# print currenttuple
for i in range(1, length):
for j in range(0, self.order):
if prevnote != False:
if tick > 5000:
tick = 5000
on = midi.NoteOnEvent(tick=tick, velocity=0, pitch=prevnote)
track.append(on)
on = midi.NoteOnEvent(tick=0, velocity=currenttuple[j][1], pitch=currenttuple[j][0])
track.append(on)
tick = currenttuple[j][2]
prevnote = currenttuple[j][0]
currenttuple = list(currenttuple)
currenttuple.pop(0)
currenttuple.append(result)
currenttuple = tuple(currenttuple)
if self.chain.has_key(currenttuple):
result = random.choice(self.chain[currenttuple])
else:
result = random.choice(self.chain[random.choice(self.chain.keys())])
# Add the end of track event, append it to the track
eot = midi.EndOfTrackEvent(tick=1)
track.append(eot)
# Print out the pattern
print pattern
# Save the pattern to disk
midi.write_midifile(filename + ".mid", pattern)
if __name__ == '__main__':
directory = "compositions"
musicdir = "input"
musicdir += "/"
logname = directory + "/" + "{:%Y-%m-%d-%H:%M:%S}_genmusic".format(datetime.datetime.now())
m = Markov(3)
print "Loading music"
inp = raw_input('Name of midi file to load or g to generate: ')
while inp != "g":
try:
m.load(musicdir + inp)
except Exception as e:
print "File not found or corrupt"
inp = raw_input('Name of midi file to load or g to generate: ')
print "Done"
print m.chain
m.generate(1000, logname)

Tkinter: Win check in scalable tic tac toe not working

I'm making a scalable tic tac toe game in Tkinter (meaning the board size can be 2x2 up to whatever fits the screen). I'm using cget("image") to find what mark a button has. For some reason, the win check displays very random things. I've tried a lot of semi-random things to fix it, but had no success in fixing it. Here's the code:
from tkinter import *
class XOGame:
def main_game(self):
self.__game_window = Tk()
self.__grid_size = 3 # User inputted in a different part of the code
self.__game_window.title("Tic Tac Toe (" + str(self.__grid_size) + "x"
+ str(self.__grid_size) + ")")
# this is user inputted in a different part of the program.
self.__players = ["p1", "p2"]
self.__player1 = self.__players[0]
self.__player2 = self.__players[1]
self.build_board(self.__game_window)
self.__game_window.mainloop()
def build_board(self, window):
self.__size = self.__grid_size ** 2
self.__turn_nr = 1
self.__win = False
self.__empty_square = PhotoImage(master=window,
file="rsz_empty.gif")
self.__x = PhotoImage(master=window,
file="rsz_cross.gif")
self.__o = PhotoImage(master=window,
file="rsz_nought.gif")
self.__squares = [None] * self.__size
self.create_win_check_lists()
# Building the buttons and gridding them
for i in range(self.__size):
self.__squares[i] = (Button(window, image=self.__empty_square))
row = 0
column = 0
number = 1
for j in self.__squares:
j.grid(row=row, column=column)
j.config(command=lambda index=self.__squares.index(j):
self.change_mark(index))
column += 1
if number % 3 == 0:
row += 1
column = 0
number += 1
# This is the part where the picture changing happens.
def change_mark(self, i):
"""
Function changes mark of empty button to either X or O depending on the
player in turn. It also checks if the change in mark results in a win.
:param i: The button number, whose mark is being changed
:return: None
"""
if self.__turn_nr % 2 == 1:
self.__player_in_turn = self.__player1
else:
self.__player_in_turn = self.__player2
if self.__player_in_turn == self.__player1:
self.__mark = self.__x
else:
self.__mark = self.__o
self.__squares[i].configure(image=self.__mark, state=DISABLED)
self.__turn_nr += 1
self.check_win(i)
if self.__win is True:
print("this is thought to be a win")
else:
print("the game thinks this is not a win")
# Checking if the game tied.
if self.__turn_nr == self.__size + 1 and not self.__win:
print("the game thinks it tied.")
def check_win(self, i):
"""
Checks if mark placement leads to a win.
:param i: i is the button location.
:return: None
"""
# checks row
if self.__win == False:
for row in self.__rows:
if i + 1 in row:
self.__win = self.checksameimage(row)
if self.__win == True:
break
# checks column
if self.__win == False:
for column in self.__columns:
if i + 1 in column:
self.__win = self.checksameimage(column)
if self.__win == True:
break
# if i is in a diagonal, checks one/both diagonals
if self.__win == False:
for diag in self.__diagonals:
if i + 1 in diag:
self.__win = self.checksameimage(diag)
if self.__win == True:
break
return self.__win
# checking if all the images are same
# This is likely where the issue is. Either this part or checkEqual.
def checksameimage(self, lst):
images = []
for nr in lst:
try:
images.append(self.__squares[nr].cget("image"))
except IndexError:
pass
return self.checkEqual(images)
def checkEqual(self, lst):
"""
Function checks if all elements in a list are equal. Used for checking
if the dice throws are the same.
:param lst: The list the check is performed on
:return: True/False, True if all elements are equal.
"""
if all(x == lst[0] for x in lst):
return True
else:
return False
def create_win_check_lists(self):
"""
Creates lists whose elements are lists of the locations of each spot
of the game board that belongs to a row/column/diagonal
:return:
"""
self.__rows = [[] for _ in range(self.__grid_size)]
for i in range(self.__grid_size):
self.__rows[i].append(i + 1)
for k in range(1, self.__grid_size):
self.__rows[i].append(i + 1 + self.__grid_size * k)
self.__columns = [[] for _ in range(self.__grid_size)]
for i in range(self.__grid_size):
for j in range(1, self.__grid_size + 1):
self.__columns[i].append(i * self.__grid_size + j)
self.getDiagonals(self.__columns)
def getDiagonals(self, lst):
self.__diagonals = [[], []]
self.__diagonals[0] = [lst[i][i] for i in range(len(lst))]
self.__diagonals[1] = [lst[i][len(lst) - i - 1] for i in
range(len(lst))]
def start(self):
# Function starts the first window of the game.
self.main_game()
def main():
ui = XOGame()
ui.start()
main()
The images used in the code are 125x125. Here is a link that works for 24h: https://picresize.com/b5df006025f0d8
your problem is unquestionably with indices. We can see what index each square corresponds to by changing the image to be text corresponding to the index:
Try changing this loop in build_board:
for i in range(self.__size):
self.__squares[i] = (Button(window, image=self.__empty_square))
To instead show the index it corresponds to:
for i in range(self.__size):
self.__squares[i] = (Button(window, text=str(i)))
Then print out lst passed to checksameimage and you will see that the indices you are checking are all one higher than you intended.

When I run my python script it shows a blank screen and disappears quickly

When I run my .py file, it quickly shows a blank black screen then disappears and does nothing. The script works fine in the editor though! The full code is down below, I know it could use some improvement but I'm just looking for answers to the blank screen for now. :) (The script is a simple genetic algorithm btw)
#!/usr/bin/python3
from fuzzywuzzy import fuzz
import random
import string
def error_msg():
print('\nSomethine went wrong!\nMake sure you typed the information correctly!')
mainF()
def mainF():
try:
while 7 == 7:
print()
stri = input('Enter string here: ')
gene = input('Enter number of generations here: ')
agen = input('Enter number of agents here: ')
muta = input('Enter chance of mutation here (0 - 1): ')
thre = input('Enter threshold here: ')
if stri == '' or gene == '' or agen == '' or thre == '' or muta == '' or stri.isdigit() or gene.isalpha() or agen.isalpha() or thre.isalpha() or muta.isalpha():
print('\nSomethine went wrong!\nMake sure you typed the information correctly!')
else:
ga(stri, len(stri), agen, gene, thre, muta)
except:
error_msg()
class Agent:
def __init__(self, length):
self.string = ''.join(random.choice(string.ascii_letters) for _ in range(length))
self.fitness = -1
def __str__(self):
return 'String: ' + str(self.string) + ', Fitness: ' + str(self.fitness) + '.'
def init_agents(population_p, length):
try:
population = int(population_p)
return [Agent(length) for _ in range(population)]
except:
error_msg()
def fitness(agents, in_str_p):
try:
in_str = in_str_p
for agent in agents:
agent.fitness = fuzz.ratio(agent.string, in_str)
return agents
except:
error_msg()
def selection(agents):
try:
agents = sorted(agents, key=lambda agent: agent.fitness, reverse=True)
print('\n'.join(map(str, agents)))
agents = agents[:int(0.2 * len(agents))]
return agents
except:
error_msg()
def crossover(agents, in_str_len_p, population_p):
try:
population = int(population_p)
in_str_len = in_str_len_p
offspring = []
for _ in range((population - len(agents)) // 2):
parent1 = random.choice(agents)
parent2 = random.choice(agents)
child1 = Agent(in_str_len)
child2 = Agent(in_str_len)
split = random.randint(0, in_str_len)
child1.string = parent1.string[0:split] + parent2.string[split:in_str_len]
child2.string = parent2.string[0:split] + parent1.string[split:in_str_len]
offspring.append(child1)
offspring.append(child2)
agents.extend(offspring)
return agents
except:
error_msg()
def mutation(agents, in_str_len_p, mutation_chance_p):
try:
mutation_chance = float(mutation_chance_p)
in_str_len = in_str_len_p
for agent in agents:
for idx, param in enumerate(agent.string):
if random.uniform(0.0, 1.0) <= mutation_chance:
agent.string = agent.string[0:idx] + random.choice(string.ascii_letters) + agent.string[idx+1:in_str_len]
return agents
except:
error_msg()
def ga(in_str_p, in_str_len_p, population_p, generations_p, threshold_p, mutation_chance_p):
mutation_chance = mutation_chance_p
threshold = int(threshold_p)
population = population_p
generations = int(generations_p)
in_str = in_str_p
in_str_len = in_str_len_p
agents = init_agents(population, in_str_len)
for generation in range(generations):
print('Generation: ' + str(generation))
agents = fitness(agents, in_str)
agents = selection(agents)
agents = crossover(agents, in_str_len, population)
agents = mutation(agents, in_str_len, mutation_chance)
if any(agent.fitness >= threshold for agent in agents):
print('Threshold met!')
mainF()
if __name__ == '__main__':
mainF()

Randomized Vigenere Cipher with Python

To clarify before beginning: I'm aware there are similar topics, but nothing that has really offered any direct help. Also: this is a class project; so I'm not looking for anyone to code my project for me. Tips and advice is what I'm looking for. (I would go to my professor for this kind of thing, but he can't be bothered to check his e-mail.)
This program is meant to take a user supplied seed, generate a key based on the integer, then to generate a 95 x 95 matrix in which all printable ascii characters are available for encryption/decryption purposes. (Key is all alpha, and capitalized)
The kicker: all the cells must be randomized. See image below:
Randomized Vigenere Matrix
I will post my code below (Python is certainly not my forte, though I will definitely take constructive criticisms.):
import random
class Vigenere(object):
def __init__(self, seed):
random.seed(seed)
#string containing all valid characters
self.symbols= """!"#$%&'()*+,-./0123456789:;?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\] ^_`abcdefghijklmnopqrstuvwxyz{|}~"""
self.eTable = [[0 for i in range(len(self.symbols))] for i in range(len(self.symbols))]
self.dTable = [[0 for i in range(len(self.symbols))] for i in range(len(self.symbols))]
self.keyWord = ""
self.message = ""
self.ciphertext = ""
self.keywordFromSeed(seed)
def setMessage(self,message):
self.message = message
#Generate psuedorandom keyword from seed
def keywordFromSeed(self,seed):
Letters = []
while seed > 0:
Letters.insert(0,chr((seed % 100) % 26 + 65))
seed = seed // 100
self.keyWord = "".join(Letters)
self.buildVigenere()
#Contructs a 95 x 95 matrix filled randomly
def buildVigenere(self):
n = len(self.symbols)
#Build the vigenere matrix
for i in range(n):
temp = self.symbols
for j in range(n):
r = random.randrange(len(temp))
self.eTable[i][j] = temp[r]
#This line below does not fill entire matrix. Why?
self.dTable[j][(ord(temp[r])-32)] = chr(i+32)
temp = temp.replace(temp[r],'')
def encrypt(self):
for i in range(len(self.message)):
mi = i
ki = i % len(self.keyWord)
self.ciphertext = self.ciphertext + self.eRetrieve(ki,mi)
def decrypt(self):
for i in range(len(self.message)):
emi = i
ki = i % len(self.keyWord)
char = self.dRetrieve(ki,emi)
self.ciphertext = self.ciphertext + char
print(self.ciphertext)
def eRetrieve(self,ki,mi):
row = ord(self.message[mi]) - 32
col = ord(self.keyWord[ki]) - 32
print(row, col)
return self.eTable[row][col]
def dRetrieve(self,ki,emi):
n = len(self.symbols)
whichRow = ord(self.keyWord[ki]) - 32
whichCol = ord(self.message[emi]) - 32
return(self.dTable[whichRow][whichCol])
And just in case it helps, here's my main.py:
import argparse
import randomized_vigenere as rv
def main():
#Parse parameters
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--mode", dest="mode", default = "encrypt", help="Encrypt or Decrypt")
parser.add_argument("-i", "--inputfile", dest="inputFile", default = "inputFile.txt", help="Input Name")
parser.add_argument("-o", "--outputfile", dest="outputFile", default = "outputFile.txt", help="Output Name")
parser.add_argument("-s", "--seed", dest="seed", default =7487383487438734, help="Integer seed")
args = parser.parse_args()
#Set seed and generate keyword
seed = args.seed
#Construct Matrix
f = open(args.inputFile,'r')
message = f.read()
Matrix = rv.Vigenere(seed)
Matrix.setMessage(message)
if(args.mode == 'encrypt'):
Matrix.encrypt()
Matrix.setMessage(Matrix.ciphertext)
Matrix.decrypt()
else:
Matrix.decrypt()
o = open(args.outputFile,'w')
o.write(str(Matrix.ciphertext))
if __name__ == '__main__':
main()
I've just been using the default seed: 7487383487438734
My Plaintext: ABCdefXYZ
I am going to answer this question:
#This line below does not fill entire matrix. Why?
I think it is your current question. If I am not mistaken, this should be the first line of your question, not a simple comment in function:
def buildVigenere(self):
n = len(self.symbols)
#Build the vigenere matrix
for i in range(n):
temp = self.symbols
for j in range(n):
r = random.randrange(len(temp))
self.eTable[i][j] = temp[r]
#This line below does not fill entire matrix. Why?
self.dTable[j][(ord(temp[r])-32)] = chr(i+32)
temp = temp.replace(temp[r],'')
First thing I did was to build a small self-contained example like this:
import random
def buildVigenere():
symbols= """!"#$%&'()*+,-./0123456789:;?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\] ^_`abcdefghijklmnopqrstuvwxyz{|}~"""
n = len(symbols)
eTable = [[0 for i in range(len(symbols))] for i in range(len(symbols))]
dTable = [[0 for i in range(len(symbols))] for i in range(len(symbols))]
#Build the vigenere matrix
for i in range(n):
temp = symbols
for j in range(n):
r = random.randrange(len(temp))
eTable[i][j] = temp[r]
print (r, len(temp), j, len(symbols), temp[r])
#This line below does not fill entire matrix. Why?
print (ord(temp[r])-32)
dTable[j][(ord(temp[r])-32)] = chr(i+32)
temp = temp.replace(temp[r],'')
print dTable
buildVigenere()
You really should learn to do that if you want answers here, and more generally be a successful programmer. Finding where the problem is and being able to reproduce it in a simple case is often the key.
Here I get an error:
Exception "unhandled IndexError"
list assignment index out of range
I add some print statements(see above) and I found that the error come from the fact that < > = are missing in the symbols string.
Why don't you use chr to build your string symbols?
And for buildVigenere, you can make a much simpler version by using
random.shuffle(x)
I was able to get it working. I'll post my implementation below:
main.py
import argparse
import randomized_vigenere as rv
def main():
#Parse parameters
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--mode", dest="mode", default = "encrypt", help="Encrypt or Decrypt")
parser.add_argument("-i", "--inputfile", dest="inputFile", default = "inputFile.txt", help="Input Name")
parser.add_argument("-o", "--outputfile", dest="outputFile", default = "outputFile.txt", help="Output Name")
parser.add_argument("-s", "--seed", dest="seed", default =7487383487438734, help="Integer seed")
args = parser.parse_args()
#Set seed and generate keyword
seed = args.seed
#Construct Matrix
f = open(args.inputFile,'r')
message = f.read()
Matrix = rv.Vigenere(seed)
Matrix.setMessage(message)
if(args.mode == 'encrypt'):
Matrix.encrypt()
else:
Matrix.decrypt()
o = open(args.outputFile,'w')
o.write(str(Matrix.ciphertext))
print("Seed used:",Matrix.seed)
print("Key Generated:",Matrix.keyWord)
print("Original Message:",Matrix.message)
print("Decoded Message:",Matrix.ciphertext)
if __name__ == '__main__':
main()
randomized_vigenere.py
(Be sure to add '<', '=', and '>' to the symbol list. For some reason they keep getting removed from this post.)
import random
class Vigenere(object):
#Initialize Vigenere object.
#Sets the random seed based on integer passed to the object
#Establishes all valid symbols
#Generates empty matrix which will contain values for encryption/decryption
#Generates a keyword based on the integer passed to the object
def __init__(self, seed):
random.seed(seed)
self.seed = seed
self.symbols= """ !"#$%&'()*+,-./0123456789:;?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
self.Table = [[0 for i in range(len(self.symbols))] for i in range(len(self.symbols))]
self.keyWord = ""
self.message = ""
self.ciphertext = ""
self.keywordFromSeed(seed)
#Sets the plaintext that will be encrypted/decrypted
def setMessage(self,message):
self.message = message
#Generate psuedorandom keyword from seed
def keywordFromSeed(self,seed):
Letters = []
while seed > 0:
Letters.insert(0,chr((seed % 100) % 26 + 65))
seed = seed // 100
self.keyWord = "".join(Letters)
self.buildVigenere()
#Contructs a 95 x 95 matrix filled randomly with no repeats within same line
def buildVigenere(self):
random.seed(self.seed)
temp = list(self.symbols)
random.shuffle(temp)
temp = ''.join(temp)
for sym in temp:
random.seed(self.seed)
myList = []
for i in range(len(temp)):
r = random.randrange(len(temp))
if r not in myList:
myList.append(r)
else:
while(r in myList):
r = random.randrange(len(temp))
myList.append(r)
while(self.Table[i][r] != 0):
r = (r + 1) % len(temp)
self.Table[i][r] = sym
#Encryption function that iterates through both the message and the keyword
#and grabs values from Table based on the ordinal value of the current
#character being pointed to be the iterator
def encrypt(self):
for i in range(len(self.message)):
mi = i
ki = i % len(self.keyWord)
self.ciphertext = self.ciphertext + self.eRetrieve(ki,mi)
def eRetrieve(self,ki,mi):
row = ord(self.message[mi]) - 32
col = ord(self.keyWord[ki]) - 32
return self.Table[row][col]
#Decryption function that iterates through both the message and the keyword
#and grabs values from Table based on the ordinal value of the current
#keyWord character being pointed to be the iterator, then traversing the
#row that corresponds to that value. While traversing that row, once there
#is a match of the message value being searched for, take the iterator value
#and convert it to an ascii character. This is the decrypted character
def decrypt(self):
self.ciphertext = ""
for i in range(len(self.message)):
emi = i
ki = i % len(self.keyWord)
self.ciphertext = self.ciphertext + self.dRetrieve(ki,emi)
def dRetrieve(self,ki,emi):
n = len(self.symbols)
whichRow = ord(self.keyWord[ki]) - 32
for i in range(n):
if self.Table[i][whichRow] == self.message[emi]:
decryptChar = chr(i + 32)
return(decryptChar)
Thank you to #Eric-Levieil for assistance

New Hangman Python

I am working on a Hangman game, but I am having trouble replacing the dashes with the guessed letter. The new string just adds on new dashes instead of replacing the dashes with the guessed letter.
I would really appreciate it if anyone could help.
import random
import math
import os
game = 0
points = 4
original = ["++12345","+*2222","*+33333","**444"]
plusortimes = ["+","*"]
numbers = ["1","2","3"]
#FUNCTIONS
def firstPart():
print "Welcome to the Numeric-Hangman game!"
def example():
result = ""
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
return ori
# def actualGame(length):
#TOP LEVEL
firstPart()
play = raw_input("Do you want to play ? Y - yes, N - no: ")
while (play == "Y" and (points >= 2)):
game = game + 1
points = points
print "Playing game #: ",game
print "Your points so far are: ",points
limit = input("Maximum wrong guesses you want to have allowed? ")
length = input("Maximum length you want for the formulas (including symbols) (must be >= 5)? ")
result = "" #TRACE
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
test = eval(result[:-1])
v = random.choice(plusortimes) #start of randomly generated formula
va = random.choice(plusortimes)
formula = ""
while (len(formula) <= (length - 3)):
formula = formula + random.choice(numbers)
formula2 = str(v + va + formula)
kind = ""
for i in range(2,len(formula2)):
if i % 2 == 0:
kind = kind + formula2[i] + formula2[0]
else:
kind = kind + formula2[i] + formula2[1]
formula3 = eval(kind[:-1])
partial_fmla = "------"
print " (JUST TO TRACE, the program invented the formula: )" ,ori
print " (JUST TO TRACE, the program evaluated the formula: )",test
print "The formula you will have to guess has",length,"symbols: ",partial_fmla
print "You can use digits 1 to 3 and symbols + *"
guess = raw_input("Please enter an operation symbol or digit: ")
a = 0
new = ""
while a<limit:
for i in range(len(formula2)):
if (formula2[i] == partial_fmla[i]):
new = new + partial_fmla[i]
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
a = a+1
print new
guess = raw_input("Please enter an operation symbol or digit: ")
play = raw_input("Do you want to play ? Y - yes, N - no: ")
The following block seems problematic:
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
Python does not allow modification of characters within strings, as they are immutable (cannot be changed). Try appending the desired character to your new string instead. For example:
elif formula2[i] == guess:
new += guess
else:
new += '-'
Finally, you should put the definition of new inside the loop directly under, as you want to regenerate it after each guess.

Categories