I am new to IDLE Python,
My IDLE python Hangman game is a bit complex(contains different pictures and windows)
I want to add a one time use hint button in my hangman game.
The word is chosen from a txt file.
How do i get the random choice function to get working?
Here is the start game code :
def startgame():
global word
infile_name = getInfile()
# Choose a word at random from the acquired word list
word, word_len = chooseWord(infile_name)
if word_len < 1:
messagebox.showinfo("Error", "Please enter a word!")
startgame()
## lots of variables for actual game ##
global wordarray
wordarray = []
global guessedletters
guessedletters = []
i = 0
while i < word_len:
wordarray.append('_')
wordarray.append(' ')
i = i + 1
global correctcounter
correctcounter = 0
global incorrectcounter
incorrectcounter = 0
## end variables ##
game = Toplevel()
game.wm_title("Hangman")
game.minsize(100,100)
game.geometry("500x450")
man = PhotoImage(file="gallows.gif")
hiddenword = StringVar()
gamelabel1 = Label(game, image=man)
gamelabel1.image = man
gamelabel1.pack()
gamelabel2 = Label(game, textvariable=hiddenword)
gamelabel2.pack()
guessfield = Entry(game)
guessfield.pack()
remainingguesses = 9 - incorrectcounter
wordprint = ''.join(wordarray) + "\n"
wordprint = wordprint + "Guessed Letters: " + ', '.join(guessedletters) + "\n"
wordprint = wordprint + "Incorrect Guesses Remaining: " + str(remainingguesses) + "\n"
hiddenword.set(wordprint)
bguessletter = Button(game, text="Guess Letter", width=15, command=lambda:
letterguess(guessfield, hiddenword, game, gamelabel1, man))
bguessletter.pack()
bguessword = Button(game, text="Guess Word [ONE CHANCE]", width=25, command=lambda:wordguess(guessfield, hiddenword, game, man))
bguessword.pack()
game.mainloop()
You want random choice? Then that seems like you want random.choice. See random choice.
Related
Im trying to put hint in output like this >>
--e - - ca
p--i--a-
how can i?
import random
word_list = ["india", "pakistan", "america"]
chosen_word = random.choice(word_list)
word_length = len(chosen_word)
display = []
for _ in range (word_length):
letter = chosen_word[_]
display += '_'
print(display)
lives = 8
game_over = False
while not game_over:
guess = input("enter a guess:").lower()
for position in range(word_length):
random.choice(display[position])
letter = chosen_word[position]
if letter == guess:
display[position] = letter
if guess not in chosen_word:
lives -= 1
if lives == 0:
If you always want your hint to contain 3 letters and the letters should be random, you could do:
hint = ["-"]*word_length
# Gets 3 random positions to have for the letters
positions = random.sample(range(0,word_length), 3)
# At those positions, change the "-" in hint to a letter.
for i in positions:
hint[i] = chosen_word[i]
hint = "".join(hint)
print(hint)
I'm new to programming and I'm trying to make an app that calculates the smallest common for you, but for some reason whenever i run it, tkinter seems to just freeze and i don't know what the error seems to be. I suspect that it's the myLabel part, since I can still read the result inside the Terminal.
Thanks in advance~
from tkinter import *
root = Tk()
root.title("I can find the smallest common, unless you enter letters... I'm dyslexic.")
numbers_list = []
global numbers
numbers = Entry(root, width = 10, borderwidth = 5, state = DISABLED)
numbers.pack()
numbers.insert(0, "")
#
def button_click():
#each gets a button
get_smallest_common = Button(root, text = 'Confirm your number!'
, command = smallest_common)
get_smallest_common.pack()
get_smallest_common = Button(root, text = 'Undo!'
, command = lambda: undo())
get_smallest_common.pack()
get_smallest_common = Button(root, text = 'Start the search!'
, command = lambda: find_the_s_common())
get_smallest_common.pack()
#disable the start button
def switch():
myButton['state'] = DISABLED
#configure helps bringing a disabled thing back to normal state
numbers.configure(state = "normal")
def smallest_common():
#add to the list for late use
numbers_list.append(numbers.get())
print(numbers_list)
numbers.delete(0, END)
def undo():
#add to the list for late use
numbers_list.pop()
print(numbers_list)
numbers.delete(0, END)
def find_the_s_common():
process_list = []
condition = True
x = 0
while condition:
#the multiplication keep rising till count is 3
a = int(x) + 1
x = a
#loop to multiply the number with x + 1
for number in numbers_list:
y = int(number) * int(a)
process_list.append(y)
#check whether the result has been added to append into list
if y in process_list:
#check whether the list contains two duplicates to
if process_list.count(y) == 3:
condition = False
result = 'The number is ' + str(y) + '!'
print(result)
else:
continue
else:
continue
myLabel = Label(root, text = result)
myLabel.pack()
#combine the two function for myButton
def button_click_switch():
button_click()
switch()
myButton = Button(root, text = 'Click me to start'
, command = lambda: [button_click(), switch()])
myButton.pack()
root.mainloop()
Most probably, you have problem if the numbers entered is less than 3. As a result, one simple way is to decrease the condition to 2 and if a single number is entered the result is the number itself, if 2 or more no freezing.
NOTE: Freezing here is actually, while loop is running as condition is always True, because of process_list.count(y) == 3 will always be False if less than 3 number entered.
See my suggestion:
from tkinter import *
root = Tk()
root.title("I can find the smallest common, unless you enter letters... I'm dyslexic.")
numbers_list = []
global numbers
numbers = Entry(root, width = 10, borderwidth = 5, state = DISABLED)
numbers.pack()
numbers.insert(0, "")
#
def button_click():
#each gets a button
get_smallest_common = Button(root, text = 'Confirm your number!', command = smallest_common)
get_smallest_common.pack()
get_smallest_common = Button(root, text = 'Undo!', command = lambda: undo())
get_smallest_common.pack()
get_smallest_common = Button(root, text = 'Start the search!' , command = lambda: find_the_s_common())
get_smallest_common.pack()
#disable the start button
def switch():
myButton['state'] = DISABLED
#configure helps bringing a disabled thing back to normal state
numbers.configure(state = "normal")
def smallest_common():
#add to the list for late use
numbers_list.append(numbers.get())
print(numbers_list)
numbers.delete(0, END)
def undo():
#add to the list for late use
numbers_list.pop()
print(numbers_list)
numbers.delete(0, END)
def find_the_s_common():
process_list = []
condition = True
x = 0
if len(numbers_list) == 1: # RETURN IF THE LIST HAS A SINGLE VALUE
result = 'The number is ' + str(numbers_list[0]) + '!'
else:
while condition:
#the multiplication keep rising till count is 3
a = int(x) + 1
x = a
#loop to multiply the number with x + 1
for number in numbers_list:
y = int(number) * int(a)
process_list.append(y)
#check whether the result has been added to append into list
if y in process_list:
#check whether the list contains two duplicates to
if process_list.count(y) == 2: # DECREASE THE CONDITIONS TO 2
condition = False
result = 'The number is ' + str(y) + '!'
print(result)
else:
continue
else:
continue
myLabel = Label(root, text = result)
myLabel.pack()
#combine the two function for myButton
def button_click_switch():
button_click()
switch()
myButton = Button(root, text = 'Click me to start', command = lambda: [button_click(), switch()])
myButton.pack()
root.mainloop()
Suggestion to add two conditons;
(1) create a condition until at least 1 number is entered! if len(numbers_list) == 0, loop to enter a number.
(2) create a condition, until N number is added, let's say user must enter at least 3 numbers, change process_list.count(y) == 3 to process_list.count(y) == N and add condition if len(numbers_list) != N, loop to enter more numbers.
NOTE:
This is not a duplicate of
Python integer incrementing with ++
I triedw_sword += 1 and it still showed up as 0.
Okay so this is my code as of now.
#creates random monsters with xp points, leveling up player, and adding upgrades
#imports
from clint.textui import colored, puts
import random
def game():
sticks = 2
stumps = 2
stone = 0
iron = 0
gold = 0
diamond = 0
platinum = 0
w_sword = 0
w_shield = 0
items = ('sticks:' + str(sticks) + ' stumps:' + str(stumps) + ' stone:' + str(stone) + ' iron:' + str(iron) + ' gold:' + str(gold) + ' diamond:' + str(diamond) + ' platinum:' + str(platinum) + ' Wooden sword(s):' + str(w_sword) +
' wooden shield(s):' + str(w_shield))
#start of the game
def start_game():
print(' Hello player! Welome to a text based game involving killing monsters, leveling up, crafting weapons, and upgrading weapons!!!')
print(' To get started enter in (i)inventory (c)craft items (d)description of items (m)types of monsters or (f)fight monsters.')
print(' ENTER (help) FOR HOW THE GAME WORKS')
print(' ENTER(?) FOR TO PRINT THIS AGAIN')
print(' WHILE YOU ARE IN A CATEGORY SUCH AS (i)inventory PRESS (?) CAN BE USED TO GO BACK AND GO TO ANOTHER CATEGORY')
start_game()
main_In = input()
level = 0
Pxp = 0
gold = 0
if main_In == ('c'):
ws_sticks = 2
ws_stumps = 1
def craft():
print('Would you like to craft an item??')
print('( Red = uncraftable )')
print('( Green = craftable )')
print('( Type items in lowercase )')
if sticks < ws_sticks:
puts(colored.red('Wooden sword'))
else:
puts(colored.green('Wooden sword'))
if stumps < ws_stumps:
puts(colored.red('Wooden shield'))
else:
puts(colored.green('Wooden shield'))
craft()
C_item = input()
def re_craft():
print('press ENTER to go back to the start screen, or enter c to craft an(other) item.')
cor_go = input()
if cor_go == ('c'):
craft()
C_item = input()
else:
game()
if C_item == ('no'):
print('press ENTER to go back to the start screen')
input()
game()
if C_item == ('wooden sword') and sticks >= ws_sticks:
print('Wooden sword added to your inventory')
re_craft()
if C_item == ('wooden sword') and sticks < ws_sticks:
print('You need ' + str(ws_sticks - sticks) + ' stick(s) to craft a wooden sword')
re_craft()
if C_item == ('wooden shield') and stumps >= ws_stumps:
print('Wooden shield added to your inventory')
re_craft()
if C_item == ('wooden shield') and stumps < ws_stumps:
print('You need' + str(ws_stump - stumps) + ' stumps to craft a wooden shield.')
re_craft()
while ('Wooden shield added to your inventory'):
w_shield = +1
while ('Wooden sword added to your inventory'):
w_sword = +1
if main_In == ('i'):
puts(colored.yellow('Level: ' + str(level)))
puts(colored.yellow('xp: ' + str(Pxp)))
puts(colored.yellow('gold:' + str(gold)))
puts(colored.yellow('Items: ' + str(items)))
puts(colored.yellow('press ENTER to return to the start screen'))
input()
game()
if main_In == ('?'):
game()
game()
Now as you can see, w_sword and w_shield are both = to 0 correct?
Right around where it says w_sword = +1 and w_shield = +1 is where I think the problem is.
When you run the program, enter c, and then craft a wooden sword/shield, it should automatically add 1 to w_sword/w_shield once you go to your (i)inventory. But for some reason when you go back to your (i)inventory, w_sword/w_shield (depending on which one you crafted) comes up as 0.
I thought this code would work mostly because in the items assignment, it contains str(w_sword) and str(w_shield) and the others. So when you craft and item like a wooden sword or wooden shield then it str(w_shield) or str(w_sword) should come up as 1.
Does anyone know what my problem is??
I use python 3.3 as said in the title.
The syntax is w_sword += 1 , not w_sword =+ 1.
I'm trying to make a program that stores a user's recipe, using a tkinter gui to do so. I need to make a way to keep track of what is inputted, and store it in a text file. I have tried using lists to no avail, and think that using a string is the way forward, but have run into a problem - each time I try to add to the string, it over writes and doesn't keep the data from before. I have tried to use
mystring.join(a + b + etc)
but that didnt work, and my new code is as follows:
from tkinter import *
number_people = 1
itemslist = ''
itemslist1 = ''
def script (): # Puts main body of program into a function so that it can be re-run #
global number_people
number_people = 1
global itemslist, itemslist1
itemslist = ''
itemslist1 = ''
#### MAIN ####
fake_window = Tk() # #
new_recipe_window = fake_window # Opens window, allows it be closed #
start_window = fake_window # #
start_window.title("Recipe Book Task") # #
#### MAIN ####
### Functions ###
def close (x):
global start_window
global new_recipe_window
(x).withdraw()
def moreitems ():
a = item_box.get()
b = quantity_units_box.get()
c = len(a)
if a == '':
pass
elif b == '':
pass
else:
item_box.delete(0,c)
quantity_units_box.delete(0,c)
global itemslist
global itemslist1
itemslist1 = itemslist + a + ', ' + b + ', '
print ("Items list =", itemslist1)
def new_recipe ():
new_recipe_window = Tk()
new_recipe_window.title("New Recipe")
close(start_window)
recipe_name_label = Label(new_recipe_window, text="Recipe Name: ")
recipe_name_label.grid(row=0, column=0)
recipe_name_box = Entry(new_recipe_window)
recipe_name_box.grid(row=0, column=1)
def continue_1 ():
global check_box
check_box = recipe_name_box.get()
if check_box == '':
pass
else:
global itemslist
global itemslist1
itemslist1 = itemslist + check_box + ', '
print (itemslist1)
continue_button_1.destroy()
item_label = Label(new_recipe_window, text="Ingredient: ")
item_label.grid(row=1, column=0)
global item_box
item_box = Entry(new_recipe_window)
item_box.grid(row=1, column=1)
quantity_units_label = Label(new_recipe_window, text="Quantity and Units: ")
quantity_units_label.grid(row=2, column=0)
global quantity_units_box
quantity_units_box = Entry(new_recipe_window)
quantity_units_box.grid(row=2, column=1)
def continue_2 ():
check_box_1 = item_box.get()
check_box_2 = quantity_units_box.get()
if check_box_1 == '':
pass
elif check_box_2 == '':
pass
else:
global itemslist
itemslist.join(check_box_1)
itemslist.join(check_box_2)
continue_button_2.destroy()
more_items.destroy()
add_people_label = Label(new_recipe_window, text="Choose amount of people")
add_people_label.grid(row=3, column=0, columnspan=2)
def add ():
global number_people
number_people += 1
num_people_label.config(text="Number of people: " + str(number_people))
def minus ():
global number_people
if number_people > 1:
number_people -= 1
num_people_label.config(text="Number of people: " + str(number_people))
def finish ():
itemslist.join(str(number_people))
print("ItemsList = " + itemslist)
saveFile = open("Recipe_Book.txt", "a")
saveFile.write(itemslist + '\n')
saveFile.close
close(new_recipe_window)
script()
num_people_label = Label(new_recipe_window, text="Number of people: " + str(number_people))
num_people_label.grid(row=4, column=0, columnspan=2)
add_people_button = Button(new_recipe_window, text="+")
add_people_button.grid(row=5, column=1)
add_people_button.config(command=add)
minus_people_button = Button(new_recipe_window, text="-")
minus_people_button.grid(row=5, column=0)
minus_people_button.config(command=minus)
finish_button = Button(new_recipe_window, text="Finish")
finish_button.grid(row=6, column=0, columnspan=2)
finish_button.config(command=finish)
continue_button_2 = Button(new_recipe_window, text="Continue...")
continue_button_2.grid(row=3, column=0)
continue_button_2.config(command=continue_2)
more_items = Button(new_recipe_window, text="Add another item", command=moreitems)
more_items.grid(row=3, column=1)
continue_button_1 = Button(new_recipe_window, text="Continue...")
continue_button_1.grid(row=1, column=0)
continue_button_1.config(command=continue_1)
new_recipe = Button(start_window, text="New Recipe", command=new_recipe)
new_recipe.grid(row=0, column=0)
script()
So to recap, my question is how do I keep the string itemslist and itemslist1 from being overwritten, or is there another way I can do this?
EDIT FOR AAAANTOINE
I was about to clarify for you what I wanted, but I just figured out what I was doing wrong, thanks for your help, you taught me what .join does, thanks.
Your code never actually assigns to itemslist other than at the beginning of script(). The only time it ever appears on the left side of the assignment operator is when it's being initialized.
You can probably change all instances of itemslist1 to itemslist and have a working program.
Edit
On further review, I suspect that you think str.join(v) appends string v to the str. That's not how join works.
>>> s = 'something'
>>> s.join('a')
'a'
join takes a list as an argument and joins its contents together, with the str instance as a separator. Typically, the source string would actually be an empty string or a comma.
>>> s.join(['a', 'b', 'c'])
'asomethingbsomethingc'
>>> ','.join(['a', 'b', 'c']) # comma separation
'a,b,c'
>>> '-'.join(s) # spell it out!
's-o-m-e-t-h-i-n-g'
How do I do it, then?
You append to strings using this syntax:
>>> s = s + 'a'
>>> s
'somethinga'
(Or the shorthand version:)
>>> s += 'a'
>>> s
'somethinga'
Ok, so I am definitely new to Python so please bear with my ignorance.
I am writing a practice interactive function with PyCharm.
Basically, I want to generate an interactive window with two text input fields and two buttons.
One button (QUIT) will quit the app, and the other one (Run DNA Scan) starts it.
The first text input field takes a DNA sequence (ex: atgcagatgac) and the other one takes a smaller 'search' sequence (ex: cag).
The plan is that once the two text fields are filled in, pressing the 'Run DNA Sequence' will start the DNA_scan() function - which I wrote and works fine when called on its own.
The problem is, the 'QUIT' button works the way it should, but the 'Run DNA Sequence' button does nothing.
Thanks in advance!
Here is my code as I have it now:
import tkinter
from tkinter import *
class Application(Frame):
def DNA_scan(self): #this is a search function I wrote myself - it works fine on its own
dataf = str(input())
s = str(input())
datar = dataf[::-1]
print('Your data input contains ' + str((dataf.count(s))) + ' instances of your search input on the FORWARD strand:')
data = dataf.lower()
b = s.lower()
c = b.upper()
print(data.replace(b,c))
datar = datar.lower()
i = 0
reverse = ''
s = s.lower()
for ch in datar:
if ch == 'a':
ch = 't'
reverse = reverse + ch
i = i+1
elif ch == 't':
ch = 'a'
i = i+1
reverse = reverse + ch
elif ch == 'c':
ch = 'g'
i = i+1
reverse = reverse + ch
elif ch == 'g':
ch = 'c'
i = i+1
reverse = reverse + ch
print('And, your data input contains ' + str((reverse.count(s))) + ' instances of your search input on the REVERSE strand:')
a = reverse.lower()
b = s.lower()
c = b.upper()
print(a.replace(b,c))
def createWidgets(self):
root.title("DNA scan")
Label (text="Please enter your DNA sequence:").pack(side=TOP,padx=10,pady=10)
dataf = Entry(root, width=10).pack(side=TOP,padx=10,pady=10)
Label (text="Please enter your search sequence:").pack(side=TOP,padx=10,pady=10)
s = Entry(root, width=10).pack(side=TOP,padx=10,pady=10)
self.button = Button(root,text="Run DNA scan",command=self.DNA_scan)
self.button.pack()
self.QUIT = Button(self)
self.QUIT["text"] = "QUIT"
self.QUIT["fg"] = "red"
self.QUIT["command"] = self.quit
self.QUIT.pack({"side": "left"})
def __init__(self, master=None):
Frame.__init__(self, master)
self.filename = None
self.pack()
self.createWidgets()
root = Tk()
root.title("DiNA")
root.quit()
app = Application(master=root)
app.mainloop()