I'm making a video game in upbge (which for this aspect is basically python) but to send the info between sockets it needs to be in bytes but i only found a way to do it turning it into a string, (because the list get's created with the game (i have a script that once a new entity appears it get's added to the list in the form of (Player-entity|data) but i want the data to variate between entities and i ran out of symbols to use to split it into lists so i'm trying to send the data as a list to be able to simply check it's components, but as it's a list inside of a list (and sometimes more) the bytearray won't work (at least i can't figure out how to make it work)
I'm unsure of how to summarize the code, but this is the code that I have now to generate that info
import socket
mi_socket = socket.socket()
mi_socket.bind(('127.0.0.1',55555))
mi_socket.listen()
TP = 0 #Total players
AP = 0 #Actual player
PL = ["host"] #Player List
AE = 0 #Actual entity
TE = 0 #Total entities
EL = ["|PlayerEntity$[Data]|"] #Entity list
PI = [] #Player Intel (Player name, Total Players, Player Code) (apartado uno en las comunicaciones)
order = None #Variable reservada para guardar comandos u identificaciones (ej: nombre de la entidad) en las comunicaciones
content = None #Variable reservada para almacenar la información recibida
incoming = 0 #Variable reservada para analizar el mensaje recibido de entrada
def login():
global AP
global TP
global PL
PJ = str(incoming).split("$")[1] #incoming Player
if AP <= TP:
if PJ!=str(PL[int(AP)]): #Nombre jugador que se conecta
AP+=1
login()
pass
else:
identity()
pass
if AP > TP:
PL.append(str("Player" + str(AP))) #Agregar jugador a la lista
TP = int(AP)
def identity(): #identifica de qué se trata la orden para responder en consecuencia, si se trata de entidad anota tmb la entidad en la lista
global TE
global AE
global EL
global AP
global PL
PJ = str(incoming).split("$")[1] # incoming Player
PE = str(incoming).split("$")[2] # incoming entity
if AE <= TE:
# Si nombre de jugador|nombre de objeto no és EL[AE]([1]|[2])
if str(str(PL[AP])+"-"+str(PE)) != str(str(EL[AE]).split("|")[1]).split("$")[0]:
AE+=1
identity()
pass
else:
EL[AE] = "|"+PL[AP]+"-"+PE+"$"+str(incoming).split("$")[3]+"|"
if AE > TE:
EL.append("|"+PL[AP]+"-"+PE+"$"+str(incoming).split("$")[3]+"|")
TE = int(AE)
def main():
global AP
global AE
global TE
global incoming
conexion, ip = mi_socket.accept()
incoming = conexion.recv(1024)
login()
conexion.send(str("#"+str(PL[AP])+"#"+str(EL[1:TE+1])+"#").encode())
AP=0
AE=0
conexion.close()
while True:
main()
I have a problem with my code (trying to make the NIM game with a Tkinter GUI). Anyhow i cant get my functions (Munt1, Munt2) to subtract to my global (aantal_munten). And i dont know how to fix it. Can someone point me in the right direction? Also the TKinter gui is still a bit new for me so if you have any tips or tricks for me they are well appreciated!
import tkinter
import random
def toonStartscherm():
keuzescherm.pack_forget()
spelerscherm.pack_forget()
startscherm.pack()
def toonKeuzescherm():
keuzescherm.pack()
startscherm.pack_forget()
spelerscherm.pack_forget()
def spelOptie1():
keuzescherm.pack_forget()
startscherm.pack_forget()
spelerscherm.pack()
def randomSpeler():
beginnende_speler = random.choice(['1', '2'])
speler = beginnende_speler
if speler == '1':
speler = '2'
else:
speler = '1'
return str(speler)
def Munt1():
eenMunt = 1
aantal_munten -= eenMunt
def Munt2():
tweeMunt = 2
aantal_munten -= tweeMunt
nim_spel = tkinter.Tk()
global aantal_munten
aantal_munten = 7
startscherm = tkinter.Frame(master=nim_spel)
startscherm.pack()
start_welkom = tkinter.Label(startscherm, text= 'Welkom bij het NIM spel! \nHieronder volgende de spelregels.')
start_welkom.pack()
start_uitleg = tkinter.Label(startscherm, text= 'Het spel NIM start met 7 munten, elke speler mag één of twee munten pakken. \n De speler die de laatste munt pakt verliest!')
start_uitleg.pack() # zet uitleg automatisch in venster
doorgaan_knop = tkinter.Button(startscherm, text = 'Ik snap de regels!', fg = 'green', command = toonKeuzescherm) # maakt knop en laat stoppen
doorgaan_knop.pack(side = 'bottom')
keuzescherm = tkinter.Frame(master=nim_spel)
keuzescherm.pack()
keuze_opties = tkinter.Label(keuzescherm, text='Het NIM spel kan op twee manieren gespeeld worden. \n Optie 1: Tegen elkaar \n Optie 2: Tegen de computer')
keuze_opties.pack() # zet opties automatisch in venster
keuze_vraag = tkinter.Label(keuzescherm, text='Voor welke optie kies je?')
keuze_vraag.pack()
optie_1 = tkinter.Button(keuzescherm, text = 'Optie 1', fg = 'green', command = spelOptie1) # maakt knop en laat stoppen
optie_1.pack(side = 'left')
optie_2 = tkinter.Button(keuzescherm, text = 'Optie 2', fg = 'red', command = keuzescherm.quit) # maakt knop en laat stoppen
optie_2.pack(side = 'right')
spelerscherm = tkinter.Frame(master=nim_spel)
spelerscherm.pack()
beurt_speler = tkinter.Label(spelerscherm, text='Speler ' + (randomSpeler()) + ' is aan de beurt!')
beurt_speler.pack()
munten_over = tkinter.Label(spelerscherm, text='Er zijn nog ' + (str(aantal_munten)) + ' aantal munten over, hoeveel pak je er?')
munten_over.pack()
pak_1_munt = tkinter.Button(spelerscherm, text = '1 munt', fg = 'blue', command = Munt1)
pak_1_munt.pack(side = 'left')
pak_2_munt = tkinter.Button(spelerscherm, text = '2 munten', fg = 'blue', command = Munt2)
pak_2_munt.pack(side = 'right')
toonStartscherm()
nim_spel.mainloop()
def Munt1():
global aantal_munten
eenMunt = 1
aantal_munten -= eenMunt
def Munt2():
global aantal_munten
tweeMunt = 2
aantal_munten -= tweeMunt
I just added the global aantal_munten line and checked it, and it's working perfectly now.
I am implement a simple simulator of soccer with python using threads and lock, the app works fine but I have doubts in the way that implement the thread it seems to me that the first team has an advantage because is executing first.
def jugar(Equipo1, Equipo2):
# Busco las probabilidades de encajar por cada equipo
prob_encajar_eq1 = Equipo1.probabilidad_encajar()
prob_encajar_eq2 = Equipo2.probabilidad_encajar()
def jugar_equipo1(defensa_rival):
semaforo.acquire()
if Equipo1.hacer_pases():
Equipo1.shoot(defensa_rival)
semaforo.release()
def jugar_equipo2(defensa_rival):
semaforo.acquire()
if Equipo2.hacer_pases():
Equipo2.shoot(defensa_rival)
semaforo.release()
hilo_equipo1 = threading.Thread(name = 'hilo_eq1', target = jugar_equipo1, args = (prob_encajar_eq2,))
hilo_equipo2 = threading.Thread(name = 'hilo_eq2', target = jugar_equipo2, args = (prob_encajar_eq1,))
hilo_equipo1.start()
hilo_equipo2.start()
hilo_equipo1.join()
hilo_equipo2.join()
to make several attempts both teams, I do a cicle for a few seconds and inside the function jugar() which is the one that does the work with threads but here is were I have the doubts, because every time that jugar is executing the threads are declared again.
if __name__ == '__main__':
cargar_informacion()
eqA = Equipo(equipoA, ranking_eqA)
eqB = Equipo(equipoB, ranking_eqB)
probabilidades = porcenajes_ranking(ranking_eqA)
eqA.cargar_probabilidades(probabilidades)
probabilidades = porcenajes_ranking(ranking_eqB)
eqB.cargar_probabilidades(probabilidades)
starttime=time.time()
tiempo = 0
# creo la barra de progreso
bar = progressbar.ProgressBar(widgets=[
progressbar.Percentage(),
progressbar.Bar(),
], max_value=100).start()
# hacemos que el juego tarde aproximadamente 10seg en simularse.
while tiempo < 10:
time.sleep(0.3 - ((time.time() - starttime) % 0.3))
jugar(eqA,eqB)
tiempo = time.time() - starttime
bar += 2.8
bar.finish() # Para que finalice la barra de progreso
resultados_finales(eqA, eqB) # Mostramos el resultado final del partido.
I'm doing a simple compressor in Python for a school assignment, my problem here is that when you enter the name of the file, a little window has to appear with a button that will execute the tar command, I want that window to close after it does the command but I dont know why, here's my code
def crea_arxiu():
global aux
if v.get() is 1 or v.get() is 2 or v.get() is 3 or v.get() is 4:
f = open('fitxers.txt','w')
for i in range(llista2.size()):
f.write(llista2.get(i)+'\n')
f.close()
print 'Arxius a comprimir:',llista2.size()
obre_finestra()
if aux is 1:
print 'AUX IS TRUE'
subprocess.call(['rm','fitxers.txt'])
else:
print 'Escolleix una opcio'
#Aquest mètode crea i mostra la pantalla per guardar el nom
#i i la finestra amb la comanda que executara
def obre_finestra():
global aux
ruta_text = StringVar()
finestra2=Toplevel(finestra)
finestra2.minsize(0,0)
finestra2.title('Comanda a executar:')
ruta = Label(finestra2, width=60, relief=SUNKEN, textvariable=ruta_text)
ruta.pack(side=LEFT)
boto = Button(finestra2, text = 'Executar', command = lambda: executar_commanda(nom_arxiu, tipus_comp))
boto.pack(side = RIGHT)
nom_arxiu = tkFileDialog.asksaveasfilename(title='Guardar com')
if v.get() is 1:
tipus_comp = 'cf'
nom_arxiu = nom_arxiu+'.tar'
elif v.get() is 2:
tipus_comp = 'czf'
nom_arxiu = nom_arxiu+'.tgz'
elif v.get() is 3:
tipus_comp = 'cjf'
nom_arxiu = nom_arxiu+'.tbz'
elif v.get() is 4:
tipus_comp = 'cJf'
nom_arxiu = nom_arxiu+'.txz'
ruta_text.set('tar '+tipus_comp+' '+nom_arxiu+' '+'fitxers de la llista')
if aux is 1:
finestra2.destroy()
def executar_commanda(nom,tipus_comp):
global aux
aux = 1
subprocess.call(['tar',tipus_comp,nom,'-T','fitxers.txt'])
The order of the functions is: crea_arxiu -> obre_finestra (summons the asksaveasfilename and the little window) , and when i press 'Execute' does executar_commanda and then i want the window to be killed
Before entering the name of the file:
http://imgur.com/KOgxIe3
After the name is given:
http://imgur.com/zDB5Bbs
So at the end I just want the path window to be closed after it does de 'Executar' button, so much thank you guys and sry for my english not being so good ^^'
I'm trying to call these 3 class variables from another script, by importing the calls onto the new script. This is how it's suppose to work, when the logIn.py runs if you typed the correct user and password, they're saved in user and password variables. if you fail, 1 is added to the fail variable. At 1st I had the like this fail = 0, user = "", password = "" cause I was getting undefined errors. Everything worked, but when I create an object of that class, everything was again initialized to fail = 0, user = "", password = "". So I thought "maybe if I use StringVar and IntVar that'll fix the problem". But instead I get this error.
Traceback (most recent call last):
File "C:\Users\devilboy 4\Documents\Visual Studio 2013\Projects\mainPage3\mainPage3\logIn_screen.py", line 9, in <module>
class checkValidation:
File "C:\Users\devilboy 4\Documents\Visual Studio 2013\Projects\mainPage3\mainPage3\logIn_screen.py", line 11, in checkValidation
fail = IntVar()
File "C:\Python31\lib\tkinter\__init__.py", line 265, in __init__
Variable.__init__(self, master, value, name)
File "C:\Python31\lib\tkinter\__init__.py", line 174, in __init__
self._tk = master.tk
AttributeError: 'NoneType' object has no attribute 'tk'
I'm pretty sure it's related to the String,IntVar. If this works properly, on mainPage3 I'll generate a report and these 3 variables are some the ones I'll use.
logIn_screen.py:
from tkinter import *
import os
import tkinter.messagebox
#check si lo entrado es correcto
class checkValidation:
fail = IntVar()
user = StringVar()
password = StringVar()
#valida el user y el pass
def fullVali(self, name, passwd):
if name == "" or name == " ":
tkinter.messagebox.showinfo( "Error","Dejo el usuario en blanco")
self.fail+= 1
elif name != "UmetSeg":
tkinter.messagebox.showinfo( "Error","Usuario incorrecto")
self.fail+= 1
else :
self.user = name
tkinter.messagebox.showinfo( "ok","dude" + name)
if passwd == "" or passwd == " ":
tkinter.messagebox.showinfo( "Error","Dejo la password en blanco")
self.fail+= 1
elif passwd != "SegUmet":
tkinter.messagebox.showinfo( "Error","Password incorrecto")
self.fail+= 1
else :
self.password = passwd
tkinter.messagebox.showinfo( "ok","dude" + passwd)
form.destroy()
#open another py script
os.system("mainPage3.py 1")
return
# no deja pasar parametros por command en el boton a menos que se por lambda, so corre este metodo para
#correr el metodo de validar
def callVali(self):
user = usrIn.get()
self.fullVali(usrIn.get(), passIn.get())
return
def getUser(self):
return self.user
def getPass(self):
return self.password
#este if es para que corra esto si se corre el programa y no si se importa la clase
if __name__ == "__main__":
vali = checkValidation()
form = Tk()
form.title("LogIn")
form.geometry("300x320+300+200")
#User txtBox
usrIn = Entry(form, textvariable = None, width = 30)
usrIn.place(x = 60, y = 140)
user = usrIn.get()
#Passwd txtBox - show es para que se vea eso pero el texto sea lo que se escribe
passIn = Entry(form, show = "*", textvariable = None, width = 30)
passIn.place(x = 60, y = 200)
#Username Label
usrLblVal = StringVar()
usrLblVal.set("User name")
usrLbl = Label(form, textvariable = usrLblVal )
usrLbl.place(x = 120, y = 115)
#Passwrd label
passLblVal = StringVar()
passLblVal.set("Password")
passLbl = Label(form, textvariable = passLblVal )
passLbl.place(x = 120, y = 175)
#Login btn
btn = Button(form, text = "Entrar", width = 10, command = vali.callVali)
btn.place(x = 110, y = 250)
form.mainloop()
mainPage3.py(where I import class from logIn_screen.py):
from tkinter import *
from logIn_screen import checkValidation
import os
import time
import tkinter.messagebox
#stuff to do:
#seguir el formato hechoen writeFile.py
#bregar con lo de procesar imagenes
#cambiar los botones de help, reporte y logout por imagenes enves de texto
#ponerle un background image a todo para que se vea mas bonito
#Reporte shit:
#se genera un reporte cadavez que se hace un fail attempt a entrar en el login, cadavez que se abre esta pagina(con hora fecha y dia),
#cada vez que se presiona editar(sale el valor), cadavez que se captura y se presiona Si(sale el resultado) o No y cadavez que se presione logOut(sale fecha y hora) .
#seguir con el reporte.
#tiene todos los metodos que bregan con agregar widgets y quitarlos
class formManipulation:
# total default de parkings
tot = 200
# 0 = no 1 = yes
totChanged = 0
cv = checkValidation()
# 0 = no 1 = yes
imgAceptada = 1
#tiempo con formato 12
t1 = time.strftime("%I:%M%p")
#fecha
d1 = time.strftime("%d-%m-%Y")
# tiempo cuando se undio logOut
#t2 = ""
##fecha al undirse logOut
#d2 = ""
#corre cuando se unde actualizar y cambia el valor de parking en total
def changeTotal(self, txt):
self.totChanged = 1
if txt == "" or txt == " ":
tkinter.messagebox.showinfo( "Error","Dejo el total de estacionamientos en blanco")
else:
try:
self.tot = int(txt)
except:
tkinter.messagebox.showinfo( "Error","El valor debe ser numerico")
if self.tot < 1:
tkinter.messagebox.showinfo( "Error","El valor debe ser mayor a cero")
else:
self.tot = str(self.tot)
#se usa para llamar changeTotal(self, txt) por que esta mierda no se le pueden pasar parametros por el command del buton
def callChange(self):
self.changeTotal(txtBoxPark.get())
#el form peque~o(no puedo usar e~e ni que sale un error...) que sale despues de presionar capturar
def askForm(self):
self.imgAceptada = 1
#display new form
form2 = Tk()
form2.title("Cotego de imagen")
form2.geometry("300x100")
newBox = LabelFrame(form2, text = "La imagen es correcta?", height = "50", width = "250")
newBox.place(x = 30, y = 17)
#btn Si
btnY = Button(newBox, text = "Si", width = 3, command = self.changeDisTxt)
btnY.place( x = 50)
#btn No
btnN = Button(newBox, text = "No", width = 3, command = self.killImg)
btnN.place(x = 150)
#display la cantidad sobrante de parkings de acuerdo al total en el txtBox de estacionamientos
def changeDisTxt(self):
#puse esto aqui envez de en la classe de reporte por que pasar parametros
#por widgets de tkinter es una jodienda.
with open(self.d1 + ".txt", "a+") as f:
f.write("--Imagen capturada-- \r\n\r\n"+
"Correcta: Si\r\n\r\n" +
"Path de la imagen: \r\n\r\n" +
"Disponibilidad: 50/"+ self.tot + "\r\n\r\n" +
self.d1 + " " + self.t1 + "\n" +
"--------------------------------\r\n\r\n")
if self.imgAceptada > 0:
txtBoxDisp.insert(0, "50/" + self.tot)
txtBoxDisp.configure(state = "readonly")
else:
tkinter.messagebox.showinfo( "Error","Debe capturar una nueva imagen")
#desaprace la foto
def killImg(self):
#puse esto aqui envez de en la classe de reporte por que pasar parametros
#por widgets de tkinter es una jodienda.
with open(self.d1 + ".txt", "a+") as f:
f.write("--Imagen capturada-- \r\n\r\n"+
"Correcta: No\r\n\r\n" +
"Path de la imagen: \r\n\r\n" +
self.d1 + " " + self.t1 + "\n" +
"--------------------------------\r\n\r\n")
self.imgAceptada = 0
lblImg.pack_forget()
#display la foto
def displayImg(self):
lblImg.pack()
self.askForm()
#llama al script que desplega el howTo
def openHelp(self):
os.system("howTo.py 1")
#grava la fecha y tiempo que se presiono logOut y abre el script de logIn
def openLogIn(self):
#tiempo con formato 12
t2 = time.strftime("%I:%M%p")
#fecha
d2 = time.strftime("%d-%m-%Y")
failStr = str(self.cv.fail)
totStr = str(self.tot)
with open(self.d1 +".txt", "a") as f:
f.write("--Reporte Final-- \r\n\r\n"+
"Entrada: "+ self.d1 + " " + self.t1 +" \r\n" +
"Intentos fallados: " + failStr + " \r\n" +
"Usuario: " + self.cv.user + " \r\n" +
"Total de estacionamientos: " + totStr + " \r\n" +
"Promedio de estacionamientos libres: 50% \r\n" +
"Salida: " + d2 + " " + t2 +"\r\n" +
"--------------------\r\n\r\n"
)
form.destroy()
os.system("logIn_screen.py 1")
# clase que brega con todo lo que tenga que ver con el reporte
class ReportGen():
fm = formManipulation()
cv = checkValidation()
#mainLog = ""
#desplega el form del reporte y lee el file de reportes
def repForm(self):
#form
form3 = Tk()
form3.title("Parkaider")
form3.geometry("500x500")
with open(fm.d1 + ".txt") as f:
out = f.read()
repBox = LabelFrame(form3, text = "Reporte generado", height = 420, width = 260)
repBox.place( x = 30, y = 10)
scroll = Scrollbar(repBox)
scroll.pack( side = RIGHT, fill = Y)
txt = Text(repBox, text = None, yscrollcommand = scroll.set)
txt.insert(END, out)
txt.config( width = 50, height = 28)
txt.pack()
txt.config( state = DISABLED)
scroll.config(command = txt.yview)
#genera reporte cuando se actualiza el valor de estacionamientos
def totUpdateLog(self):
fm.callChange()
with open(fm.d1 + ".txt", "a+") as f:
f.write("--Total de parking actualizado-- \r\n\r\n"+
"Total de estacionamientos : "+ fm.tot +"\r\n\r\n" +
fm.d1 + " " + fm.t1 + "\n" +
"--------------------------------\r\n\r\n")
#llama al metodo de logout y genera el reporte final
def finRep():
fm.openLogIn()
#class PicProcessing:
#main form
fm = formManipulation()
rg = ReportGen()
global form
form = Tk()
form.title("Main Page")
form.geometry("600x700+100+0")
#box imagen capturada
#esta aqui por que sino sale undefined para lblImg
imgBox = LabelFrame(form, text = "Imagen capturada", height = "300", width = "260")
#path de foto
#esta aqui por que sino sale undefined para lblImg
img = PhotoImage(file = "parking.gif", height = "300", width = "260")
#foto
#es global para que la pueda reconocer la clase cuando corra killImg()
global lblImg
lblImg = Label(imgBox, image = img)
#big lbl PArkaider
lblTitleVal = StringVar()
lblTitleVal.set("Parkaider")
lblTitle = Label(form, textvariable = lblTitleVal, font=("Times", 30))
lblTitle.place( x = 220, y = 20)
#total de parking. Se convierte en string para usarse en el txtBox
strinTot = StringVar()
#conversion de totPark(int) a string
fm.tot = str(fm.tot)
#txtBox con el total de parking.
txtBoxPark = Entry(form, textvariable = None, width = 10)
txtBoxPark.insert(0,fm.tot)
txtBoxPark.place( x = 264, y = 135)
#lbl total de estacionamientos
lblParkingTotVal = StringVar()
lblParkingTotVal.set("Total de estacionamientos")
lblParkingTot = Label(form, textvariable = lblParkingTotVal, font = ("Times"))
lblParkingTot.place( x = 220, y = 100)
#btn edit,se usa si se fuera hacer update al algoritmo con el total nuevo de parking que no sea el default
btnEditTot = Button(form, text = "Actualizar", width = 8, command = rg.totUpdateLog)
btnEditTot.place( x = 263 , y = 170 )
#show el box de imagen capturada
imgBox.place(x = 170, y = 220)
#txtBox con la cantidad total despues que confirma que la imagen es correcta. Se supo que ahi se haga el algoritmo de object detection
txtBoxDisp = Entry(form, textvariable = None, width = 30)
txtBoxDisp.place( x = 210, y = 650)
#btn que captura una imagen con la camara
btnCap = Button(form, text = "Capturar" , width = 7, command = fm.displayImg)
btnCap.place( x = 270, y = 550)
#lbl disponibilidad
lblDisVal = StringVar()
lblDisVal.set("Disponibilidad")
lblDis = Label(form, textvariable = lblDisVal, font = "Times")
lblDis.place( x = 255, y = 620)
btnHelp = Button(form, text = "help", width = 4, command = fm.openHelp)
btnHelp.place(x = 20, y = 20)
btnLogout = Button(form, text = "Logout", width = 5, command = fm.openLogIn)
btnLogout.place(x = 540, y = 20)
btnRep = Button(form, text = "Reporte", width = 6, command = rg.repForm)
btnRep.place( x = 70, y = 20 )
#se necesita para que todo funcione en windows, en linux o mac, esto no hace falta
form.mainloop()
Ignore all of the Spanish comments and the Spanglish variables lol.
Thanks
You have to create a root window before you can create instances of StringVar or IntVar
Put form = Tk() befor class declaration and before imported class
global form
form = Tk()
from logIn_screen import checkValidation
class formManipulation:
# rest of code