raw_input() equivalent in cocos2d for Python - python

I'm building a simple game in cocos2d-0.6.0, and can't figure out how to let the player enter text for a username or other preferences.
I've found only a few examples, like the one here, but it isn't quite what I'm looking for. My attempt is below; I used the handling_events.py to try update_text, but it just strings together a list of letters separated by commas.
The ultimate goal is to be able to use a label to pose a question ("What is your name?") and then have the user type a response that will get stored as a variable I can access later (to display on following scenes on a high-score list, for example). Let me know if I can clarify my question.
class Settings(cocos.layer.ColorLayer):
is_event_handler = True
def __init__(self):
super(Settings, self).__init__(0,0,0,255)
label = cocos.text.Label('Pick a name:',
font_name='Courier',
font_size=32,
anchor_x='center', anchor_y='center')
label.position = 320,650
self.add(label )
self.text = cocos.text.Label("", x=100, y=280)
self.keys_pressed = set()
self.update_text()
self.add(self.text)
Here is the problem. I don't want to just collect a list of letters and symbols like A,G,T,SEMICOLON.
def update_text(self):
key_names = [pyglet.window.key.symbol_string(k) for k in self.keys_pressed]
text = 'Keys: ' + ','.join(key_names)
# Update self.text
self.text.element.text = text
This is optional; it transitions the settings page onto the main gameplay page.
def on_key_press(self, k, m):
if k == key.ENTER:
director.replace(FadeTransition(
main_scene, 1))
else:
self.keys_pressed.add(k)
self.update_text()
if __name__ == "__main__":
cocos.director.director.init(height = 690, width = 640)
settings_scene = cocos.scene.Scene(settings)
cocos.director.director.run(settings_scene)

Perhaps you were looking for something like this. The only downside is that it's all caps right now:
import cocos
import pyglet
class Settings(cocos.layer.ColorLayer):
is_event_handler = True
def __init__(self):
super(Settings, self).__init__(0,0,0,255)
label = cocos.text.Label('Pick a name:',
font_name='Courier',
font_size=32,
anchor_x='center', anchor_y='center')
label.position = 320,650
self.add( label )
self.text = cocos.text.Label("", x=100, y=280)
self.keys_pressed = ""
self.update_text()
self.add(self.text)
def update_text(self):
# Update self.text
self.text.element.text = self.keys_pressed
def on_key_press(self, k, m):
if k == pyglet.window.key.ENTER:
print "You Entered: {}".format(self.keys_pressed)
# cocos.director.director.replace(FadeTransition(main_scene, 1)) # disabled for testing
cocos.director.director.scene.end() # added for testing
else:
kk = pyglet.window.key.symbol_string(k)
if kk == "SPACE":
kk = " "
if kk == "BACKSPACE":
self.keys_pressed = self.keys_pressed[:-1]
else:
# ignored_keys can obviously be expanded
ignored_keys = ("LSHIFT", "RSHIFT", "LCTRL", "RCTRL", "LCOMMAND",
"RCOMMAND", "LOPTION", "ROPTION")
if kk not in ignored_keys:
self.keys_pressed = self.keys_pressed + kk
self.update_text()
if __name__ == "__main__":
cocos.director.director.init(height = 690, width = 640)
settings_scene = cocos.scene.Scene(Settings())
cocos.director.director.run(settings_scene)

Related

tkinter sorting txt file for leaderboard

I've been coding a multiplication game where you can practice multiplications. I'm trying to add in a leaderboard using an external txt file that would sort by the highest percentage but have been stuck for quite a while now. It's able to append the new data and show the results. The txt file is laid out as name, age, score (Jackie Welles, 16, 70%)
from tkinter import *
import random
from tkinter import messagebox
class Timestable:
def __init__(self, parent):
Timestable.f1 = Frame(parent)
Timestable.f1.grid()
Timestable.f2 = Frame(parent)
Timestable.f2.grid()
Timestable.f2.grid_forget()
Timestable.f3 = Frame(parent)
Timestable.f3.grid()
Timestable.f3.grid_forget()
#frame 1 ========================================================
Label(self.f1,text="Multiplication Practice").grid()
Label(self.f1,text="Name:").grid()
Timestable.name = Entry (self.f1)
Timestable.name.grid()
Label(self.f1,text="Age").grid()
Timestable.age = Entry (self.f1)
Timestable.age.grid()
Timestable.incorrect=[]
Timestable.user = []
Timestable.checked1 = IntVar()
Timestable.checked2 = IntVar()
self.c1 = Checkbutton(self.f1, text='1',variable=Timestable.checked1,onvalue=1,offvalue=0,command=lambda:data.save(self))
self.c1.grid()
self.c2 = Checkbutton(self.f1, text='2', variable=Timestable.checked2,onvalue=1,offvalue=0,command=lambda:data.save(self))
self.c2.grid()
Timestable.w = Spinbox(self.f1, from_=1, to=5)
Timestable.w.grid()
Button(self.f1,text="Start", command=lambda: data.start(self)).grid()
#frame 2 ========================================================
Label(self.f2,text="Frame 2 ").grid()
self.x=0
self.correct=0
sub = lambda: data.Submit(self)
Button(self.f2,text="submit", command=sub).grid()
Timestable.entryWidget = Entry (self.f2)
Timestable.entryWidget.grid()
#frame 3 ========================================================
Label(self.f3,text="Frame 3 ").grid()
Timestable.congrats=Label(Timestable.f3,text="")
Timestable.congrats.grid()
Timestable.incdisplay = Label(Timestable.f3,text = Timestable.incorrect)
Timestable.incdisplay.grid()
Timestable.my_text=Text(self.f3,width=40,height=10)
Timestable.my_text.grid()
class data:
def openleader(self):
file=open('Leaderboard.txt',"a")
file.write(Timestable.name.get()+", "+Timestable.age.get()+", "+str(data.percent)+"%""\n")
file.close
file=open("Leaderboard.txt","r")
idk=file.readlines()
Timestable.my_text.insert(END,idk)
def save(self):
if Timestable.checked1.get() == 1:
Timestable.user.append(1)
if Timestable.checked2.get() == 1:
Timestable.user.append(2)
def clear_text(self):
Timestable.entryWidget.delete(0, 'end')
def Questions(self):
number1 = random.choice(Timestable.user)
number2 = random.randrange(1,12)
self.answer = number1 * number2
self.prompt = (str(number1) + " X " + str(number2))
quest = Label(Timestable.f2, text=self.prompt, width=len(self.prompt))
quest.grid()
return self.answer
def start(self):
Timestable.f1.grid_forget()
Timestable.f2.grid()
data.Questions(self)
def results(self):
Timestable.f2.grid_forget()
Timestable.f3.grid()
def Submit(self):
if Timestable.entryWidget.get() == "":
messagebox.showerror("Error", "Please enter a number.")
else:
if self.answer != int(Timestable.entryWidget.get().strip()):
messagebox.showinfo("Answer", "INCORRECT! Answer: " + str(self.answer))
Timestable.incorrect.append(self.prompt)
else:
messagebox.showinfo("Answer", "CORRECT!")
self.correct = self.correct +1
self.x=self.x+1
if self.x < int(Timestable.w.get()):
data.Questions(self)
data.clear_text(self)
else:
data.results(self)
data.percent = round(self.correct/self.x*100)
Timestable.congrats.configure(text="Congrats, you got "+ str(data.percent) +"% of the questions correct")
Timestable.incdisplay.configure(text=Timestable.incorrect)
data.openleader(self)
root = Tk()
root.geometry("300x300")
Timestable(root)
data()
root.mainloop()
That can be added fairly easily. We can also clean up the way it is diplayed as well. Since you are already essentially storing the data in csv format we can stick to that structure when presenting the output data.
def openleader(self):
file=open('Leaderboard.txt',"a")
file.write(Timestable.name.get()+", "+Timestable.age.get()+", "+str(data.percent)+"%""\n")
file.close
file=open("Leaderboard.txt","r").read()
headers = " ".join(["Name", "Age", "Score"])
output = [i.split(",") for i in file.split("\n") if i]
out_sort = sorted(output, key=lambda x: int(x[2][:-1]), reverse=True)
final = '\n'.join([headers, "-"*len(headers),*(" ".join(i) for i in out_sort)])
Timestable.my_text.insert(END, final)

Method within Class not activating

Here is my code, my issue is as the title above states, the input text does not appear and neither does the print below. I am new to Python so sorry for a simple mistake
class Horse:
colour = ''
height = ''
speed = 0
def __init__(self):
self.speed = input("Enter an integer: ")
if(self.speed != 0):
self.gallop = (3 * self.speed)
print(self.gallop)
You need to make an instance of your object by initiating it. Here is the full program:
class Horse:
colour = ''
height = ''
speed = 0
def __init__(self):
self.speed = input("Enter an integer: ")
if(self.speed != 0):
self.gallop = (3 * self.speed)
print(self.gallop)
if __name__ == '__main__':
x = Horse()
You have to create an instance of the class... because so your code in the constructor is invoked
if __name__ == '__main__':
a = Horse()
You did not create an horse instance. Add the code below.
def create_horse():
new_horse = Horse() # this will ask for an integer
if __name__ == '__main__':
create_horse()

How to update tkinter labels that are stored in a list, using a button?

I need to update a list of labels that could be any size. All questions I've found already dealt in single labels instead of lists. I tried to extrapolate those answers to my problem and have not been successful.
I tried associating the list of labels with a list of StringVars and was not successful.
import nation
import game_time
def main():
Ven = nation.Nation("Venice", 1500000, 60, 5)
Mil = nation.Nation("Milan", 1250000, 10, 5)
Flo = nation.Nation("Florence", 7500000, 90, 5)
game_time.pass_time(1)
print ("test")
for n in nation.Nation._registry:
print (n.get_pop_stats())
if __name__ == '__main__':
main()
#NATION
name = ""
population = 0
econ_value = 0
owned_land = 0
GROWTH = .002
MONTH_GROWTH = .002/12
current_growth = 0
expected_growth = 0;
class Nation:
_registry = []
def __init__(self, name = "dummy", population = -1, econ_value = -1, owned_land = -1):
self.name = name
self.population = population
self.econ_value= econ_value
self.owned_land = owned_land
self._registry.append(self)
def get_pop_stats(self):
return "Nation: " + self.name + " Population: " + str(self.population) + " Current Growth: " + str(self.current_growth) + " Expected Growth: " + str(self.expected_growth) + "\n"
#TIME
import nation
GROWTH = .002
MONTH_GROWTH = .002/12
def pass_time(x):
while x > 0:
for p in nation.Nation._registry:
temp = p.population
p.population += p.population*(p.econ_value/100)*MONTH_GROWTH
p.current_growth = p.population - temp
p.expected_growth = p.population*(p.econ_value/100)*MONTH_GROWTH
x -= 1;
#ERROR
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.do_labels()
ran = 0
def do_labels(self):
pop_text = []
pop_stats = []
time = tk.Button(self, text="PASS TIME", fg="red", command= lambda: self.press())
time.pack(side="bottom")
i = 0
for n in nation.Nation._registry:
pop_text.append(tk.StringVar(value = n.get_pop_stats()))
pop_stats.append(tk.Label(self, textvariable = pop_text[i], command = print("initializing label")))
pop_stats[i].pack(side="top")
i+=1
self.ran = 1
self.pack()
root.update()
def press(self):
print("this works")
game_time.pass_time(1)
root = tk.Tk()
app = Application(master=root)
app.mainloop()
My bad, Here is the nation class, required to run the code.
Expected: Numbers in the labels update.
Actual: Nothing happens in the window, but the button successfully prints in the console.

Can't get my self.button to work! Writing interactive function in Python.

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()

update_idletasks difficulty in python tkinter

I'm having trouble calling .update_idletasks() to redraw my canvas ( at the end of the .set_up() Class-method ).
If I use self.canv.update_idletasks( self ), the canvas draws the objects I want but gives the error
TypeError: update_idletasks() takes exactly 1 argument (2 given)
If I use self.canv.update_idletasks(), the canvas remains blank but doesn't produce any errors.
from Tkinter import *
class Animation(Frame):
def __init__(self,parent=None):
Frame.__init__(self,parent)
self.pack()
self.generation = 1
self.epoch = 1
self.set_up()
def set_up(self):
greeting_text = 'Generation ' + str(self.generation) + ', Epoch ' + str(self.epoch)
header = Label(self,text=greeting_text)
header.pack()
anframe = Frame(self,relief=SUNKEN)
anframe.pack(side='left',padx=10,pady=10)
self.canv = Canvas(anframe,width=800, height=800, bg='white') # 0,0 is top left corner
self.canv.pack(expand=YES, fill=BOTH,side='left')
buframe = Frame(self,relief=RAISED)
buframe.pack(side='right',fill=X,padx=10,pady=5)
start = Button(buframe,text='START',width=10,command=self.animate)
start.pack(expand=YES,fill=BOTH,side='top')
back = Button(buframe,text='Back',width=10)
back.pack(expand=YES,fill=BOTH,side='bottom')
nextgo= Button(buframe,text='Next',width=10)
nextgo.pack(expand=YES,fill=BOTH,side='bottom')
path = 'C:/Desktop/LearnNet/' + str(self.generation) + '_' + str(self.epoch) + '.txt'
data = open(path,'r')
lines = data.readlines()
food,moves = [],[]
for item in lines:
if item.strip() == 'f':
dat_type = 1
continue
elif item.strip() == 'a':
dat_type = 2
continue
if dat_type == 1:
temp = item.strip()
temp = item.split()
food.append([int(temp[0]),int(temp[1])])
if dat_type == 2:
temp = item.strip()
temp = item.split()
moves.append([int(temp[0]),int(temp[1]),int(temp[2])])
photos = []
for i in xrange(len(food)):
temp=PhotoImage(file='C:/Desktop/LearnNet/Food.gif')
photos.append(temp)
self.canv.create_image(food[i][0]*20,food[i][1]*20,image=photos[i],anchor=NW)
start_pos = moves[0]
picpath = self.orientation(start_pos[2])
animal = PhotoImage(file=picpath)
self.canv.create_image(moves[0][0]*20,moves[0][1]*20,image=animal,anchor=NW)
self.canv.update_idletasks(self)
def animate(self):
return 1
def orientation(self,angle):
if angle == 0:
picpath = 'C:/Desktop/LearnNet/PEast.gif'
elif angle == 90:
picpath = 'C:/Desktop/LearnNet/PNorth.gif'
elif angle == 180:
picpath = 'C:/Desktop/LearnNet/PWest.gif'
else:
picpath = 'C:/Desktop/LearnNet/PSouth.gif'
return picpath
if __name__ == '__main__': Animation().mainloop()
self in python is actually syntactic sugar.
In other words, when you say self.animate(), python translates it to Animation.animate(self). That's why you define the class methods with that "self" argument -- it's passed implicitly.
self.canv.update_idletasks(self) is evaluating to something like Canvas.update_idletasks(self.canv, self).
I found a solution by looking at some similar code. self.canv.get_tk_widgets().update_idletasks() does the trick, thought I am not quite sure WHY this works, If anyone could explain or point me to some reading. Thanks

Categories

Resources