Does anyone know how to combine these functions? - python

I want to combine the functions def clicked and def clicked2 because they are the same but I don't know how to do that. I haven't tried yet but I can't think of a way to do it.
from tkinter import *
import random
window = Tk()
x = round(random.random()) + 1
m = 7
window.title("NIM-7 spel")
window.geometry('350x200')
lbl = Label(window, text="Player " + str(x) + " next")
lbl2 = Label(window, text="Their are " + str(m) + " coins left")
lbl.grid(column=0, row=1)
lbl2.grid(column=1, row=0)
def clicked():
global x
global m
m -= 1
if m < 1:
lol = "Player " + str(x) + " won!"
res = ""
else:
if x == 1:
x = 2
else:
x = 1
lol = "Their are " + str(m) + " coins left"
res = "Player " + str(x) + " is next"
lbl.configure(text=res)
lbl2.configure(text=lol)
def clicked2():
global x
global m
m -= 2
if m < 1:
lol = "Player " + str(x) + " won!"
res = ""
else:
if x == 1:
x = 2
else:
x = 1
lol = "Their are " + str(m) + " coins left"
res = "Player " + str(x) + " is next"
lbl.configure(text=res)
lbl2.configure(text=lol)
btn1 = Button(window, text="Take 1 coin", command=clicked)
btn2 = Button(window, text="Take 2 coins", command=clicked2)
btn1.grid(column=1, row=1)
btn2.grid(column=2, row=1)
window.mainloop()
Does anyone know how to do it?

You can add arguments to tkinter buttons if you use a lambda function.
Some identical questions were asked already:
Functions in Tkinter
How to call a function with arguments in "Button" function from "tkinter" python package?
def clicked(value):
global x
global m
m -= value
if m < 1:
lol = "Player " + str(x) + " won!"
res = ""
else:
if x == 1:
x = 2
else:
x = 1
lol = "Their are " + str(m) + " coins left"
res = "Player " + str(x) + " is next"
lbl.configure(text=res)
lbl2.configure(text=lol)
btn1 = Button(window, text="Take 1 coin", command = lambda:clicked(1))
btn2 = Button(window, text="Take 2 coins", command = lambda:clicked(2))

Pass in how much you want to decrement m as a parameter. So:
def clicked(decrement):
global x
global m
m -= decrement
if m < 1:
lol = "Player " + str(x) + " won!"
res = ""
else:
if x == 1:
x = 2
else:
x = 1
lol = "Their are " + str(m) + " coins left"
res = "Player " + str(x) + " is next"
lbl.configure(text=res)
lbl2.configure(text=lol)
Then call it like this: clicked(1) and clicked(2).
Because you are passing it as a parameter to Button, you can create dummy functions:
def clicked1():
clicked(1)
and similar for clicked2.

Related

Why is this code showing number 2 multiple times?

So I'm trying to make a calculator but when i do plus (also with other things but for example) it does work but after the outcome comes it asks for number 2 again, I just want the code to start again.
this is the plus piece of the code:
q = input(str("Wil je de bewerkingsteken legende zien? (j/n): "))
if q == "J" or q == "j" :
print ("\nplus = + ")
print ("min = -")
print ("maal = X")
print ("delen door = :")
print ("quadrateren = Q")
print ("tot de kracht van = P")
print ("Worteltrekken = W")
print ("Procent = %")
num1 = float(input("\n Nummer 1: "))
bew = input("\n Bewerkingsteken: ")
num1_word = (str(num1))
if bew == "+" :
plus_num2 = input(float("\nNummer 2: "))
plus_num2_con = (str(plus_num2))
plus_out = (num1 + plus_num2)
plus_out1 = (str(plus_out))
print ("\n" + num1_con +" + " + num2_con + " = " + plus_out1)
First, you write the input wrong for plus_num2. Try this;
plus_num2 = float(input("\nNummer 2: "))
Second, you define the number's name different from last print function. Try This;
print ("\n" + num1_word +" + " + plus_num2_con + " = " + plus_out1)
Third, if you want to start the code again you can add while True on first line.

Python tkinter can't use Entry.get() fucntion

So I have been working on a quizzing application for some time now (about 4 days). I managed to make all the logical part of the code (the quiz taking, the quiz question handling, score outputting, etc.) I know that this code is neither the best nor the most efficient as it can be but I'm just a beginner. Anyways, the get() function for the entry function for tkinter does not return anything. I am aware that there is a way to fix it however I'm not sure how to implement the solution with an external loop. Please help me. Here is my code:
import random
from time import sleep
import tkinter as tk
from tkinter import *
import threading
class App(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def callback(self):
self.root.quit()
def run(self):
self.root = tk.Tk()
self.root.protocol("WM_DELETE_WINDOW", self.callback)
#label = tk.Label(self.root, text="Hello World")
#label.pack()
#Button(self.root, text = "Choose", command=btnPressed).pack()
tk.Label(self.root, text="Answer: ").grid(row=0,column=0)
#answerField_get = StringVar()
answerField = tk.Entry(self.root)
answerField.grid(row=0, column=1)
#Button(self.root, text='Show').grid(row=3, column=1, sticky=tk.W, pady=4)
print(str(answerField.get()))
Button(self.root, text='Show', command = lambda arg1=answerField.get():btnPressed("<"+str(arg1)+">")).grid(row=3, column=1, sticky=tk.W, pady=4)
self.root.mainloop()
def sendTMP(self, sendStr):
btnPressed(sendStr)
SCORE_SET = []
qasTmp = {}
qas = {}
qasSequenced = {}
incorrectResponses = []
incorrectResponses_replies = []
quiztaker_name = ""
attachAnsCode = "%% Fun fact: rgb computer parts lovers are somewhat weird hehe %%********^^&&^^&&^^&&"
qasQsSequenced = False
qasQsL = 0
qasQsL_divisionFactor = 2
qasINDEX = 0
err_noCode = "<!>NO_CODE<!>"
codes_answerCorrect = "A_C"
codes_answerIncorrect = "A_I"
answerCode = err_noCode
score = 0
randQs = False
# File
# the metadata will corrupt the reading from the file, a separate file, created in the targeted system, must be used to properly read the data.
# comment out the file name that is not being used.
filename_windows = "qas-windows"
filename_rpi = "qas-rpi"
filename = filename_windows
fileformat = "txt"
file_name_format = filename + "." + fileformat
spaceIndicator = "|"
char_commentLine_qasFile = "*"
char_newline = "`"
print("Information about modes: ")
print(" *Easy: No point deductions for an incorrect response")
print(" *Hard: One point deducted for every incorrect response")
modes_err = "0"
modes_ez = "1"
modes_hard = "2"
gameOn = False
selectedMode = modes_err
askReplay = True
data_prev = []
with open("SCORES.txt", 'r') as scores_prev:
data_prev = scores_prev.readlines()
scores_prev.close()
for i in range(0, len(data_prev)):
SCORE_SET.append(data_prev[i])
def btnPressInform():
print("A button has been pressed!")
def importAndClean():
# import questions from qas-windows.txt
with open(file_name_format, 'r') as document:
for line in document:
if line.strip():
key, value = line.split(None, 1)
if key[0] != char_commentLine_qasFile: # Custom comments for the txt file
qasTmp[key] = value.split()
# Clean up dictionary input from the txt file
for i in range(0, len(qasTmp)): # FIVE FOR LOOPS!!!! (FOUR IN THIS ONE)
for ii in qasTmp:
output = ""
output_ans = ""
for iii in range(0, len(ii)):
if ii[iii] != spaceIndicator:
output += ii[iii]
else:
output += " "
for iiii in range(0, len(qasTmp[ii])):
TEMP = str(qasTmp[ii])
for iiiii in range(2, len(TEMP) - 2): # IGNORE [' and ']
# print(TEMP[iiiii])
if TEMP[iiiii] != spaceIndicator:
output_ans += TEMP[iiiii]
else:
output_ans += " "
# print(output + " : " + output_ans) #Output question: answer
qas[output] = output_ans
importAndClean()
def getL():
qasQsL = len(qas) / qasQsL_divisionFactor # only ask 1/qasQsL_divisionFactor the questions
qasQsL = int(qasQsL) # round to an integer as odd numbers will end in .5 after division
if qasQsL < 1:
qasQsL = 1 # Have atleast ONE question
return qasQsL
def debug1(keys, vals, index, i):
print(str(index) + "/" + str((len(keys) - 1)))
print(keys)
print(vals)
print()
print(keys[index] + " : " + vals[index] + "\n")
print("Sorting original index " + str(i) + " at random index " + str(index))
def debug2(keys, vals, index):
print(keys)
print(vals)
print("\n")
def debugFinal():
print("Temp (OG reading): ")
print(qasTmp)
print("\nQAS (Non-sequenced, cleaned): ")
print(qas)
print("\nQAS Sequenced (Randomly sequenced, cleaned): ")
print(qasSequenced)
def randomize(qasQsL_tmp):
qas_keys = list(qas.keys())
qas_vals = list(qas.values())
if randQs == False:
qasQsL_tmp = len(qas_keys) # all questions
print("You will be asked all " + str(qasQsL_tmp) + " questions")
else:
qasQsL_tmp = getL() # random question
print("You will be asked " + str(qasQsL_tmp) + " questions out of " + str(len(qas)) + " possible questions!")
print("\n\nRandomly sequencing questions...")
for i in range(0, qasQsL_tmp):
INDEX = random.randint(0, qasQsL_tmp - 1)
# debug1(qas_keys, qas_vals, INDEX, i)
qasSequenced[qas_keys[INDEX]] = qas_vals[INDEX]
qas_keys.pop(INDEX)
qas_vals.pop(INDEX)
qasQsL_tmp -= 1
# debug2(qas_keys, qas_vals, INDEX)
sleep(0.05)
# debugFinal()
print("Done sequencing! Starting quiz now! \n\n")
return "0"
def quizController(index):
qas_keys = list(qasSequenced.keys())
qas_vals = list(qasSequenced.values())
# print(qas_keys)
# print(qas_vals)
lines = []
lines_index = 0
tmp = ""
# Splitter
for i in range(0, len(qas_keys[index])):
if lines_index < len(qas_keys[index]) - 1:
if qas_keys[index][i] != char_newline:
tmp += qas_keys[index][i]
else:
lines.append(tmp)
tmp = ""
lines.append(tmp)
# Multiple choice
mChoiceQ = False
mChoice_startBrackets = 0
mChoice_endBrackets = 0
mChoice_options = []
mChoice_numOptions = 0
mChoice_seperatorsAt = []
for i in range(0, len(qas_keys[index])):
if qas_keys[index][i] == "[":
mChoice_startBrackets = i
mChoiceQ = True
elif qas_keys[index][i] == "]":
mChoice_endBrackets = i
elif qas_keys[index][i] == "/":
mChoice_seperatorsAt.append(i)
if mChoiceQ == True:
TEMP = ""
for i in range(mChoice_startBrackets, mChoice_endBrackets + 1):
if qas_keys[index][i] != "[":
if qas_keys[index][i] != "/" and qas_keys[index][i] != "]":
TEMP += qas_keys[index][i]
else:
mChoice_options.append(TEMP)
TEMP = ""
mChoice_numOptions = len(mChoice_seperatorsAt) + 1
# Default options (yes, no) full names
for i in range(0, len(mChoice_options)):
if mChoice_options[i].lower() == "y":
mChoice_options.append("yes")
elif mChoice_options[i].lower() == "n":
mChoice_options.append("no")
# if mChoiceQ == True:
# print("It is a multiple choice question! There are " + str(mChoice_numOptions) + " options. They are: ")
# print(mChoice_options)
print("\nQuestion " + str(index + 1) + "/" + str(qasQsL) + ":")
for i in range(0, len(lines)):
print(lines[i])
# answer = ""
answer = input(">")
# answer = input(qas_keys[index]+ ": ")
if mChoiceQ == False:
if len(answer) > 0:
if answer.lower() == str(qas_vals[index]).lower():
return codes_answerCorrect
else:
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
# print("DEBUG: Incorrect response! Expected '" + str(qas_vals[index]).lower() + "', received " + answer.lower())
return codes_answerIncorrect
else:
print("Please insert an answer!")
else:
allowedResponse = False
for i in range(0, len(mChoice_options)):
if answer.lower() == mChoice_options[i].lower():
allowedResponse = True
if allowedResponse == True:
ans = qas_vals[index].lower()
yn = False
ans_yesno = ""
if ans.lower() == "y" or ans.lower() == "n":
yn = True
else:
yn = False
if yn == True:
if ans == "y":
ans_yesno = "yes"
elif ans == "n":
ans_yesno = "no"
if len(answer) > 0:
if yn == True:
if answer.lower() == ans.lower() or answer.lower() == ans_yesno.lower():
return codes_answerCorrect
else:
return codes_answerIncorrect
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
else:
if answer.lower() == ans.lower():
return codes_answerCorrect
else:
return codes_answerIncorrect
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
else:
print("Please insert an answer!")
else:
print("Invalid response! You may only enter the following: " + str(mChoice_options))
def saveScore():
# Clear file!
score_file_CLEAR = open("SCORES.txt", "wt")
score_file_CLEAR.close()
# Save contents
score_file = open("SCORES.txt", "wt")
for i in range(0, len(SCORE_SET)):
score_file.write(SCORE_SET[i])
print("Done saving!")
def btnPressed(tmp):
print(tmp)
app = App()
while True:
qasQsL = len(qasSequenced)
if gameOn == True and selectedMode != modes_err:
if qasQsSequenced == True:
if qasINDEX < qasQsL:
answerCode = quizController(qasINDEX)
else:
output = randomize(qasQsL)
if output == "0":
qasQsSequenced = True
if qasINDEX < qasQsL:
if answerCode == codes_answerCorrect:
score += 1
qasINDEX += 1
# print("DEBUG: Correct! Score set to: " + str(score))
elif answerCode == codes_answerIncorrect:
if selectedMode == modes_hard:
score -= 1
qasINDEX += 1
# print("Score set to: " + str(score))
else:
print("")
if qasQsL != 0:
score_per = score / qasQsL
if score_per < 0:
score_per = 0
if score < 0:
score = 0
print("You score was lower than 0, therefore it was set to 0")
# print("Your score: " + str(score) + "/" + str(len(qasSequenced)) + " (" + str(int(score_per*100)) + "%)")
# if score != qasQsL:
# print("You responded to the following questions incorrectly:")
# print(incorrectResponses)
if score / qasQsL == 1:
SCORE_SET.append(quiztaker_name + " scored " + str(score) + " out of " + str(qasQsL) + "(" + str(
int(score / qasQsL) * 100) + "%). PART OF Qs: " + str(
int(randQs)) + " at division factor 1/" + str(qasQsL_divisionFactor) + ", MODE: " + str(
int(selectedMode)) + "\n")
if score / qasQsL != 1:
SCORE_SET.append(quiztaker_name + " scored " + str(score) + " out of " + str(qasQsL) + " (" + str(
int(score / qasQsL) * 100) + "%). PART OF Qs: " + str(
int(randQs)) + " at division factor 1/" + str(qasQsL_divisionFactor) + ", MODE: " + str(
int(selectedMode)) + " They got the following questions wrong: \n")
for i in range(0, len(incorrectResponses)):
SCORE_SET.append(" " + str(i + 1) + ") " + incorrectResponses[i] + " --RESPONSE-- " +
incorrectResponses_replies[i] + "\n")
SCORE_SET.append("\n")
saveScore()
qasQsSequenced = False
gameOn = False
print("\nGame over!")
askReplay = True
else:
continue
elif askReplay == False:
TEMP = input("What mode would you like? (E = Easy, H = Hard): ")
if len(str(TEMP)) > 0:
if str(TEMP).lower() == "e":
selectedMode = modes_ez
gameOn = True
print("Set mode to: NO POINT DEDUCTIONS")
elif str(TEMP).lower() == "h":
selectedMode = modes_hard
gameOn = True
print("Set mode to: POINT DEDUCTIONS ALLOWED")
else:
print("Error: Undefined response. Please try again!")
elif askReplay == True:
TEMP = input("Would you like to (re)do the quiz? (Y/N): ")
if len(str(TEMP)) > 0:
if str(TEMP).lower() == "y":
askReplay = False
qasQsSequenced = False
qasQsL = 0
qas.clear()
qasSequenced.clear()
qasTmp.clear()
qasINDEX = 0
incorrectResponses.clear()
answerCode = err_noCode
score = 0
selectedMode = modes_err
importAndClean()
randQs = False
USER_TEMP = input("Please enter your name >")
if len(USER_TEMP) > 0:
quiztaker_name = str(USER_TEMP)
print("Welcome " + quiztaker_name + "!")
USER_TEMP = input("Would you like all questions (a) or a part of the questions(p)? (A/P) > ")
if len(USER_TEMP) > 0:
if USER_TEMP.lower() == "a":
print("Set to all questions!")
randQs = False
elif USER_TEMP.lower() == "p":
print("Set to 1/" + str(qasQsL_divisionFactor) + " questions (pre-set variable)")
randQs = True
else:
print("Undefined response! Setting to default value (ALL)")
randQs = False
gameOn = False
askReplay = False
elif str(TEMP).lower() == "n":
selectedMode = modes_hard
gameOn = False
print("Exiting now!")
saveScore()
sleep(2)
exit(0)
else:
print("Error: Undefined response. Please try again!")
Entry() doesn't work like input(). It doesn't wait for your data but it only informs tkitner that you want to display Entry widget (and mainloop() will display it) and Python goes to next lines of code and it runs print(str(answerField.get())) before it even displays window - so you try to get from empty Entry.
You should get it in function assigned to Button which you will press after you put some text in Entry.
The same problem is with
lambda arg1=self.answerField.get():print(arg1)
it assigns to args value from Entry only once when lambda is defined at start - so it get empty string. You should use it inside function
command=lambda:print(self.answerField.get())
or create normal function and assign to button.
Minimal working code
import tkinter as tk
import threading
class App(threading.Thread):
def run(self):
self.root = tk.Tk()
#self.root.protocol("WM_DELETE_WINDOW", self.on_close)
self.answerField = tk.Entry(self.root)
self.answerField.grid(row=0, column=1)
#b = tk.Button(self.root, text='Show', command=lambda:print(self.answerField.get()))
b = tk.Button(self.root, text='Show', command=self.on_click)
b.grid(row=1, column=1)
self.root.mainloop()
def on_click(self):
print(self.answerField.get())
#def on_close(self):
# self.root.destroy()
App().start()
#App().run()

Displaying a function in GUI

I am trying to make a "command generator" for a game where the user can input numbers into text boxes and my program will generate the command for them. I have this working almost perfectly, but the generated command is printed to the console, I want it to input to the GUI.
Sorry if my code is messy or not done the most efficient way, I am brand new to programming.
from tkinter import *
#Create window that is 500x500
window = Tk()
window.geometry("500x500")
#This is the final command that is outputted
def save():
print("/" + var2.get() + " " + entryx1.get() + " " + entryy1.get() + " " + entryz1.get() + " " + entryx2.get() + " " + entryy2.get()
+ " " + entryz2.get() + " " + var1.get())
#This is what you call when you want to display the dropdown input
var2 = StringVar()
#Creating the dropdown
drop2 = OptionMenu(window,var2,"fill","setblock")
drop2.configure(font=("Arial",10))
#This makes the text that displays in the window
coordx1 = Label(window,text="First X Coordinate: ")
coordy1 = Label(window,text="First Y Coordinate: ")
coordz1 = Label(window,text="First Z Coordinate: ")
coordx2 = Label(window,text="Second X Coordinate: ")
coordy2 = Label(window,text="Second Y Coordinate: ")
coordz2 = Label(window,text="Second Z Coordinate: ")
result = Label(window,text=save)
#This makes the text boxes that the user types in
entryx1 = Entry(window)
entryy1 = Entry(window)
entryz1 = Entry(window)
entryx2 = Entry(window)
entryy2 = Entry(window)
entryz2 = Entry(window)
#This is the submit button
submit = Button(window,text="Submit",command=save)
#Second dropdown variable
var1=StringVar()
#Creation of second dropdown list
drop1 = OptionMenu(window,var1,"destroy","hollow","keep","outline","replace")
drop1.configure(font=("Arial",10))
dropdownLabel = Label(window,text="Selector: ")
dropdownLabel2 = Label(window,text="Command: ")
#This says what goes where. 'E' and 'W' represent East and West
coordx1.grid(row=1,sticky=E)
coordy1.grid(row=2,sticky=E)
coordz1.grid(row=3,sticky=E)
coordx2.grid(row=4,sticky=E)
coordy2.grid(row=5,sticky=E)
coordz2.grid(row=6,sticky=E)
entryx1.grid(row=1,column=1)
entryy1.grid(row=2,column=1)
entryz1.grid(row=3,column=1)
entryx2.grid(row=4,column=1)
entryy2.grid(row=5,column=1)
entryz2.grid(row=6,column=1)
dropdownLabel.grid(row=7,column=0,sticky=E)
dropdownLabel2.grid(row=0,column=0,sticky=E)
drop1.grid(row=7,column=1,sticky=W)
drop2.grid(row=0,column=1,sticky=W)
submit.grid(row=8,columnspan=2,sticky=E)
mainloop()
To be clear, I want the function save() to be printed onto the GUI
First, you didn't grid your result Label.
Secondly, you can change your save() function to modify the result text everytime.
from tkinter import *
#Create window that is 500x500
window = Tk()
window.geometry("500x500")
#This is the final command that is outputted
def save():
result.config(text="/" + var2.get() + " " + entryx1.get() + " " + entryy1.get() + " " + entryz1.get() + " " + entryx2.get() + " " + entryy2.get()+ " " + entryz2.get() + " " + var1.get())
#This is what you call when you want to display the dropdown input
var2 = StringVar()
#Creating the dropdown
drop2 = OptionMenu(window,var2,"fill","setblock")
drop2.configure(font=("Arial",10))
#This makes the text that displays in the window
coordx1 = Label(window,text="First X Coordinate: ")
coordy1 = Label(window,text="First Y Coordinate: ")
coordz1 = Label(window,text="First Z Coordinate: ")
coordx2 = Label(window,text="Second X Coordinate: ")
coordy2 = Label(window,text="Second Y Coordinate: ")
coordz2 = Label(window,text="Second Z Coordinate: ")
result = Label(window,text=save)
#This makes the text boxes that the user types in
entryx1 = Entry(window)
entryy1 = Entry(window)
entryz1 = Entry(window)
entryx2 = Entry(window)
entryy2 = Entry(window)
entryz2 = Entry(window)
#This is the submit button
submit = Button(window,text="Submit",command=save)
#Second dropdown variable
var1=StringVar()
#Creation of second dropdown list
drop1 = OptionMenu(window,var1,"destroy","hollow","keep","outline","replace")
drop1.configure(font=("Arial",10))
dropdownLabel = Label(window,text="Selector: ")
dropdownLabel2 = Label(window,text="Command: ")
#This says what goes where. 'E' and 'W' represent East and West
coordx1.grid(row=1,sticky=E)
coordy1.grid(row=2,sticky=E)
coordz1.grid(row=3,sticky=E)
coordx2.grid(row=4,sticky=E)
coordy2.grid(row=5,sticky=E)
coordz2.grid(row=6,sticky=E)
entryx1.grid(row=1,column=1)
entryy1.grid(row=2,column=1)
entryz1.grid(row=3,column=1)
entryx2.grid(row=4,column=1)
entryy2.grid(row=5,column=1)
entryz2.grid(row=6,column=1)
dropdownLabel.grid(row=7,column=0,sticky=E)
dropdownLabel2.grid(row=0,column=0,sticky=E)
drop1.grid(row=7,column=1,sticky=W)
drop2.grid(row=0,column=1,sticky=W)
submit.grid(row=8,columnspan=2,sticky=E)
result.grid(row=9,columnspan=1)
window.mainloop()
This should do the trick.

Python 2.7.8: printing color/value with out the format

I'm new to python and about a month into learning. I came across an issue where when I run this code it's supposed to print out the numbers in red. The second example shows what it really prints out and I'm stuck. Please help.
It's supposed to print ('Enemy HP:', 1150/1200)
but it actually prints ('Enemy HP:', '\x1b[91m1150/1200\x1b[0m\n')
import random
class bcolors:
HEADER = '\033[95m'
OKBLUE = "\x1b[94m"
OKGREEN = "\x1b[92m"
WARNING = '\033[93m'
FAIL = '\x1b[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class Person:
def __init__(self, hp, mp, atk, df, magic):
self.maxhp = hp
self.hp = hp
self.maxmp = mp
self.mp = mp
self.atkl = atk - 10
self.atkh = atk + 10
self.df = df
self.magic = magic
self.actions = ["Attack", "Magic"]
def generate_damage(self):
return random.randrange(self.atkl, self.atkh)
def generate_spell_damage(self, i):
mgl = self.magic[i]["dmg"] - 5
mgh = self.magic[i]["dmg"] + 5
return random.randrange(mgl, mgh)
def take_damage(self, dmg):
self.hp -= dmg
if self.hp < 0:
self.hp = 0
return self.hp
def get_hp(self):
return self.hp
def get_max_hp(self):
return self.maxhp
def get_mp(self):
return self.mp
def get_max_mp(self):
return self.maxmp
def reduce_mp(self, cost):
self.mp -= cost
def get_spell_name(self, i):
return self.magic[i]["name"]
def get_spell_mp_cost(self, i):
return self.magic[i]["cost"]
def choose_action(self):
i = 1
print(bcolors.OKBLUE + bcolors.BOLD + "Actions" + bcolors.ENDC)
for item in self.actions:
print(str(i) + ":", item)
i += 1
def choose_magic(self):
i = 1
print(bcolors.OKBLUE + bcolors.BOLD + "Magic" + bcolors.ENDC)
for spell in self.magic:
print(str(i) + ":", spell["name"], "(cost:", str(spell["cost"]) + ")")
i = 1
from classes.game import Person, bcolors
magic = [{"name": "Fire", "cost": 10, "dmg": 100},
{"name": "Thunder", "cost": 10, "dmg": 124},
{"name": "Blizzard", "cost": 10, "dmg": 100}]
player = Person(460, 65, 60, 34, magic)
enemy = Person(1200, 65, 45, 25, magic)
running = True
i = 0
print(bcolors.FAIL + bcolors.BOLD + "AN ENEMY ATTACKS!" + bcolors.ENDC)
while running:
print("======================")
player.choose_action()
choice = input("Choose action:")
index = int(choice) - 1
if index == 0:
dmg = player.generate_damage()
enemy.take_damage(dmg)
print("You attacked for", dmg, "points of damage.")
elif index == 1:
player.choose_magic()
magic_choice = int(input("Choose magic:")) - 1
magic_dmg = player.generate_spell_damage(magic_choice)
spell = player.get_spell_name(magic_choice)
cost = player.get_spell_mp_cost(magic_choice)
current_mp = player.get_mp()
if cost > current_mp:
print(bcolors.FAIL + "\nNot enough MP\n" + bcolors.ENDC)
continue
player.reduce_mp(cost)
enemy.take_damage(magic_dmg)
print(bcolors.OKBLUE + "\n" + spell + " deals", str(magic_dmg), "points of damage" + bcolors.ENDC)
enemy_choice = 1
enemy_dmg = enemy.generate_damage()
player.take_damage(enemy_dmg)
print("Enemy attacks for", enemy_dmg)
print("----------------------------")
print("Enemy HP:", bcolors.FAIL + str(enemy.get_hp()) + "/" + str(enemy.get_max_hp()) + bcolors.ENDC + "\n")
print("Your HP:", bcolors.OKGREEN + str(player.get_hp()) + "/" + str(player.get_max_hp()) + bcolors.ENDC)
print("Your MP:", bcolors.OKBLUE + str(player.get_mp()) + "/" + str(player.get_max_mp()) + bcolors.ENDC + "\n")
if enemy.get_hp() == 0:
print(bcolors.OKGREEN + "You Win!", + bcolors.ENDC)
running = False
elif player.get_hp() == 0:
print(bcolors.FAIL + "Your enemy has defeated you!" + bcolors.ENDC)
running = False
Your code would work well in Python 3, where print is a function:
>>> print("x", "y")
x y
It means "print the first argument, then the separator (which defaults to a space), then the second argument.
In Python 2, though:
>>> print("x", "y")
('x', 'y')
prints a representation of the tuple containing your strings.
So, you can either use Python 3, which has many advantages, or change your code like this:
print("Enemy HP:" + bcolors.FAIL + str(enemy.get_hp()) + "/" +
str(enemy.get_max_hp()) + bcolors.ENDC + "\n")
# note the + instead of ,
in order to print a single string.
does it work for your others print ?
You have a double quote "" instead off simple '' on OKGREEN in class bcolors maybe it comes from here

In Python, is it possible to skip a certain part of a for loop?

so I attempted to add some code to my working product(A triangle maker) where you can add some text to the middle of the triangle if the program allows so. So far I've added the text with the correct amount of x's and indents but the program still outputs the original middle line of x's. For example Triangle(3, "M") would output
x
xxx
xMx
xxxxx
instead of
x
xMx
xxxxx
which is what I would like. I have tried using break when x == textrow - 1 but that did not seem to work and I think what I would have to do is somehow break the loop, print the user's text with the x's skip the part where the computer would normally print the xxx's and keep going. But I have no idea on how to do that.
Here is my code, the only really relevant parts are under the "if x > 1" (I know that it is probably the most inefficient thing you have ever seen, but I'm a beginner and I would do what I understand.)
def Triangle(height, text):
text1 = str(text)
number_of_x2 = (height - len(text)) / 2
if height % 2 == 0:
print "Please enter a height that is odd"
else:
stringTriangle = "x"
HT = ""
for x in range(height + height - 1):
HT += "x"
length_of_HT = len(HT)
length_of_HT = int(length_of_HT)
length_of_HT = len(HT) / 2
length_of_HT = int(length_of_HT)
indent_text_length = length_of_HT / 2
for x in range(height): #should be height change later
if x == 1:
stringTriangle = " " * length_of_HT + stringTriangle
print stringTriangle
if x > 1:
textrow = height / 2
for x in range(height):
if stringTriangle == HT:
break
if len(text) == len(stringTriangle):
break
if x == textrow:
text = ""
text = " " * number_of_x2
for x in range(number_of_x2):
text+="x"
text = text + text1
for x in range(number_of_x2):
text+="x"
print text
stringTriangle += "xx"
stringTriangle = stringTriangle[1:]
print stringTriangle
Thank you!
I am not sure of how how your code works, but I tweaked it until it returned the result I expected. Also, I made small changes to parts that were a bit ugly. This should do what you want:
def Triangle(height, text):
number_of_x2 = (height - len(text)) / 2
if not height % 2:
print "Please enter a height that is odd"
else:
string_triangle = "x"
ht = "x" * (2 * height - 1)
length_of_ht = len(ht) / 2
indent_text_length = length_of_ht / 2
text_row = height / 2
# should be height change later
for x in range(height):
if x == 1:
string_triangle = " " * length_of_ht + string_triangle
print string_triangle
if x > 1:
for x in range(height):
if x == text_row - 1:
string_triangle += "xx"
string_triangle = string_triangle[1:]
continue
if x == textrow:
special_line = " " * (number_of_x2 + len(text) / 2) + "x" * number_of_x2 + text + "x" * number_of_x2
if not len(text) % 2:
special_line += "x"
print special_line
if string_triangle == ht or len(text) == len(string_triangle):
break
string_triangle += "xx"
string_triangle = string_triangle[1:]
print string_triangle

Categories

Resources