What's wrong with this Groovy expression? - groovy

Running the following Groovy expression through the GroovyShell (interpreter):
if(fizz.subtype == null) {
if(fizz.color == 'RED') fizz.subtype = "DOG";
else if(fizz.color == 'BLUE') fizz.subtype = "CAT";
else if(fizz.color == 'GREEN') fizz.subtype = "SHEEP";
else if(fizz.color == 'ORANGE') fizz.subtype = "LION";
else if(fizz.color == 'YELLOW') fizz.subtype = "SNAIL";
else if(fizz.color == 'GRAY') fizz.subtype = "SHARK";
else if(fizz.color == 'PURPLE') fizz.subtype = "BAT";
else if(fizz.color == 'BLACK') fizz.subtype = "FOX";
}; fizz;
Gives me the following stack trace:
groovy.lang.MissingPropertyException: No such property: subtype for class: com.me.myapp.Fizz
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:50)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.getProperty(ScriptBytecodeAdapter.java:479)
at Script1.run(Script1.groovy:1)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:543)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:518)
at com.tms.evaluator.GroovyEvaluator._evaluate(GroovyEvaluator.java:51)
...rest of stacktrace omitted for brevity
Any ideas? Thanks in advance!

You are missing a semicolon after the closing bracket of the if expression:
fizz = [:]
if(fizz.subtype == null) {
if(fizz.color == 'RED') fizz.subtype = "DOG";
else if(fizz.color == 'BLUE') fizz.subtype = "CAT";
else if(fizz.color == 'GREEN') fizz.subtype = "SHEEP";
else if(fizz.color == 'ORANGE') fizz.subtype = "LION";
else if(fizz.color == 'YELLOW') fizz.subtype = "SNAIL";
else if(fizz.color == 'GRAY') fizz.subtype = "SHARK";
else if(fizz.color == 'PURPLE') fizz.subtype = "BAT";
else if(fizz.color == 'BLACK') fizz.subtype = "FOX";
}; fizz;
Also, may i suggest using a map for this kind of data matching?
fizz.color = 'ORANGE'
fizz.subtype = [
'RED' : 'DOG',
'BLUE' : "CAT",
'GREEN' : "SHEEP",
'ORANGE' : "LION",
'YELLOW' : "SNAIL",
'GRAY' : "SHARK",
'PURPLE' : "BAT",
'BLACK' : "FOX"
][fizz.color]
assert fizz.subtype == 'LION'
A case-match could also work, but it would be best suited if you had a more complex task:
fizz.color = 'BLUE'
fizz.subtype = fizz.color.case {
when 'RED' then 'DOG'
when 'BLUE' then "CAT"
when 'GREEN' then "SHEEP"
when 'ORANGE' then "LION"
when 'YELLOW' then "SNAIL"
when 'GRAY' then "SHARK"
when 'PURPLE' then "BAT"
when 'BLACK' then "FOX"
}
assert fizz.subtype == 'CAT'

Related

Onvalue of Checkbutton always = 0 python I also use get()

I had two codes, since I combined them, chechbox always = 0
(When I run the code separately, it works fine)
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
from convert_number2text import convert_ordinary
from pyperclip import copy, paste
import csv
from jdatetime import datetime, date
from show_factor import show_factors
from os import listdir
class Program:
def __init__(self):
self.root = Tk()
self.root.title("Accounting")
self.root.minsize(800, 600)
Button(self.root, text="فاکتور نوشتن", font=("",20),bg="red", command=self.factor_new).pack()
Button(self.root, text="فاکتور های ثبت شده", font=("",20),bg="red", command=show_factors).pack()
Button(self.root, text="افزودن کارت", font=("",20),bg="red").pack()
self.root.mainloop()
def show_factors():
win_show_factor = Tk()
win_show_factor.title("show factors")
win_show_factor.minsize(940, 600)
Label(win_show_factor, text="کد فاکتور", font=("",16)).place(x=760 ,y=10)
entry_code_factor = Entry(win_show_factor, font=("", 16), width=7)
entry_code_factor.place(x=755, y=40)
Label(win_show_factor, text="نام مشتری", font=("",16)).place(x=760, y=80)
entry_name_factor = Entry(win_show_factor, font=("", 16))
entry_name_factor.place(x=670, y=110)
Label(win_show_factor, text="اطلاعات فاکتور", font=("",16)).place(x=240, y=10)
entry_info_factor = Text(win_show_factor, font=("", 13), width=30, height=7)
entry_info_factor.place(x=160, y=40)
Label(win_show_factor, text="سال", font=("", 16)).place(x=540,y=5)
combo_y= ttk.Combobox(win_show_factor, values=["1400"])
for i in range(1401, 1420):
combo_y['values'] += (i,)
combo_y.set("1400")
combo_y.place(x=480,y=35)
Label(win_show_factor, text="ماه", font=("", 16)).place(x=540, y=60)
combo_m= ttk.Combobox(win_show_factor, values=["1"])
for i in range(2, 13):
combo_m['values'] += (i,)
combo_m.set("1")
combo_m.place(x=480, y=90)
Label(win_show_factor, text="روز", font=("", 16)).place(x=530, y=115)
combo_d= ttk.Combobox(win_show_factor, values=["1"])
for i in range(2, 32):
combo_d['values'] += (i,)
combo_d.set("1")
combo_d.place(x=480, y=150)
list_box_find = ttk.Treeview(win_show_factor, column=("c1", "c2", "c3", "c4", "c5"), show='headings')
list_box_find.column("# 1", anchor=CENTER,width=220)
list_box_find.heading("# 1", text="نام مشتری")
list_box_find.column("# 2", anchor=CENTER, width=60)
list_box_find.heading("# 2", text="کد فاکتور")
list_box_find.column("# 3", anchor=CENTER, width=150)
list_box_find.heading("# 3", text="تاریخ")
list_box_find.column("# 4", anchor=CENTER, width=100)
list_box_find.heading("# 4", text="مبلغ فاکتور")
list_box_find.column("# 5", anchor=CENTER, width=400)
list_box_find.heading("# 5", text="اطلاعات بیشتر")
list_box_find.place(x=3, y=200)
by_name = IntVar()
r1 = Checkbutton(win_show_factor, text="جستجو با نام مشتری", variable=by_name)
by_code = IntVar()
r1.place(x=10,y=10)
r2 = Checkbutton(win_show_factor, text="جستجو با کد فاکتور", variable=by_code)
by_date = IntVar()
r2.place(x=10, y=40)
r3 = Checkbutton(win_show_factor, text="جستجو با تاریخ", variable=by_date)
r3.place(x=10, y=70)
by_info = IntVar()
r4 = Checkbutton(win_show_factor, text="جستجو با اطلاعات", variable=by_info)
r4.place(x=10, y=100)
def search():
for item in list_box_find.get_children():
list_box_find.delete(item)
list_items = []
list_file = listdir(r"G:\check file\python\Accounting\factors")
for j in list_file:
file_csv = "G:/check file/python/Accounting/factors/{}".format(j)
with open(file_csv, encoding="utf-8") as Rfile_csv:
read_csv = csv.reader(Rfile_csv)
x = 0
for i in read_csv:
if x == 0:
name_moshtari = i[0]
Purchase_code = i[1]
tarikhe_buy = i[2]
price_all = i[3]
elif x == 1:
more_info = i[0]
poole_naghd = i[1]
poole_kart = i[2]
poole_nasiye = i[3]
else:
list_items.insert(len(list_items), i)
x +=1
name_check = name_moshtari.strip().find(entry_name_factor.get().strip())
info_check = -1
for i in more_info.split():
if i.find(entry_info_factor.get("1.0", END).strip()) != -1:
info_check = 0
code_check = Purchase_code.strip().find(entry_code_factor.get().strip())
date_check = -1
date_factor = tarikhe_buy[:tarikhe_buy.find(" ")]
date_find = date(int(combo_y.get()), int(combo_m.get()), int(combo_d.get()))
if str(date_find) == date_factor :
date_check = 0
d=1
c=1
n=1
f=1
print(by_code.get(),by_date.get(),by_info.get(),by_name.get())
if by_date.get():
d = 2
if by_code.get():
c = 3
if by_name.get():
n = 4
if by_info.get():
f = 5
j = d * c * n * f
if (j == 5) and (info_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 4) and (name_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 3) and (code_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 2) and (date_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 6) and (date_check != -1) and (code_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 8) and (date_check != -1) and (name_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 10) and (info_check != -1) and (date_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 12) and (name_check != -1) and (code_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 15) and (info_check != -1) and (code_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 20) and (info_check != -1) and (name_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 24) and (date_check != -1) and (code_check != -1) and (name_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 30) and (date_check != -1) and (code_check != -1) and (info_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 40) and (date_check != -1) and (name_check != -1) and (info_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 60) and (code_check != -1) and (name_check != -1) and (info_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
if (j == 120) and (date_check != -1) and (name_check != -1) and (info_check != -1) and (code_check != -1):
list_box_find.insert("",END, values=([name_moshtari, Purchase_code, tarikhe_buy, price_all, more_info]))
Button(win_show_factor, text="search", font=("",16), command=search).place(x=30,y=130)
win_show_factor.mainloop()
def setting_app(self, x):
with open("setting.csv", encoding="utf-8") as setting_file:
read_setting = csv.reader(setting_file)
for i in read_setting:
print(i)
if x == 0:
return i[1]
elif x == 1:
if i[0] == "code_buy_end":
return i[1]
def code_buy(self):
now_code = self.setting_app(1)
code = int(now_code) + 1
with open("setting.csv", "w", encoding="utf-8", newline='') as setting_file:
write_setting = csv.writer(setting_file)
write_setting.writerows([["version", "1.0"],["code_buy_end", code]])
return code
def factor_new(self):
self.win_factor = Tk()
self.win_factor.title("factor")
self.win_factor.minsize(1000, 600)
Label(self.win_factor, text="نام مشتری", font=("",16)).place(x=820, y=8)
self.text_name_moshtari_input = Entry(self.win_factor, font=("",13), width=30)
self.text_name_moshtari_input.place(x=540, y=10)
Label(self.win_factor, font=("",14), text="نام محصول").place(x=230, y=30)
self.text_name_item_input = Entry(self.win_factor, font=("",13), width=23)
self.text_name_item_input.place(x=160, y=60)
Label(self.win_factor, font=("",14), text="تعداد/متر").place(x=380, y=30)
self.text_count_item_input = Entry(self.win_factor, font=("",13), width=5)
self.text_count_item_input.place(x=390, y=60)
Label(self.win_factor, font=("",14), text="قیمت واحد").place(x=465, y=30)
self.text_price_item_input = Entry(self.win_factor, font=("",13), width=10)
self.text_price_item_input.place(x=458, y=60)
self.text_price_item_input.insert(0, "0")
self.text_price_item = Label(self.win_factor, text= "", font=("",10))
self.text_price_item.place(x=428, y=85)
Label(self.win_factor, text="اطلاعات بیشتر فاکتور", font=("",16)).place(x=790,y=130)
self.text_info_more = Text(self.win_factor, width=25, height=18, font=("", 13))
self.text_info_more.place(x=750, y=175)
tree = ttk.Treeview(self.win_factor, column=("c1", "c2", "c3","c4"), show='headings', height=19)
tree.column("# 1", anchor=CENTER,width=220)
tree.heading("# 1", text="نام محصول")
tree.column("# 2", anchor=CENTER, width=70)
tree.heading("# 2", text="تعداد/متر")
tree.column("# 3", anchor=CENTER, width=110)
tree.heading("# 3", text="قیمت واحد")
tree.column("# 4", anchor=CENTER, width=150)
tree.heading("# 4", text="مجموع قیمت محصول")
tree.place(x=160, y=120)
self.my_list = Listbox(self.win_factor, height=23)
self.my_list.place(x=20, y=50)
self.text_name_item_total = Label(self.win_factor, text= "مجموع :", font=("",20))
self.text_name_item_total.place(x=150, y=535)
Label(self.win_factor, text=":", font=("",20)).place(x=380, y=527)
self.text_count_item_total = Label(self.win_factor, text= "0", font=("",16))
self.text_count_item_total.place(x=390, y=535)
self.text_price_item_total = Label(self.win_factor, text= "0", font=("",16))
self.text_price_item_total.place(x=615, y=535)
Label(self.win_factor, text=":", font=("",20)).place(x=565, y=527)
self.text_price_item_total_text = Label(self.win_factor, text= "", font=("",13))
self.text_price_item_total_text.place(x=460, y=560)
self.price_total = 0
self.count_total = 0
self.list_item =[]
def update(dete):
try:
self.text_price_item.configure(text=convert_ordinary(int(self.text_price_item_input.get())))
except:
self.text_price_item.configure(text="")
self.my_list.delete(0,END)
for item in dete:
self.my_list.insert(0, item)
def fillout(e):
self.text_name_item_input.delete(0, END)
self.text_name_item_input.insert(0, self.my_list.get(ACTIVE))
def check(e):
typed= self.text_name_item_input.get()
if typed == "":
dete = toppings
else:
dete= []
for item in toppings:
if typed.lower() in item.lower():
dete.append(item)
update(dete)
toppings = ["زانو سفید", "زانو سفید 2.5", "زانو سفید 3", "سراه سفید", "سراه سفید 2.5", "سراه سفید 3"]
update(toppings)
self.my_list.bind("<<ListboxSelect>>", fillout)
self.text_name_item_input.bind("<KeyRelease>", check)
self.text_price_item_input.bind("<KeyRelease>", check)
def delete_item():
tree.delete(tree.selection()[0])
self.list_item = []
for child in tree.get_children():
self.list_item.insert(0, tree.item(child)["values"])
print(self.list_item)
self.price_total = 0
self.count_total = 0
for i in range(0, len(self.list_item)):
self.count_total =self.count_total+ float(self.list_item[i][1])
self.price_total = self.price_total+ int(float(self.list_item[i][3]))
self.text_count_item_total.configure(text=self.count_total)
self.text_price_item_total.configure(text=self.price_total)
self.text_price_item_total_text.configure(text=convert_ordinary(self.price_total))
def edit_item():
xitem = tree.selection()[0]
h_info = tree.item(xitem,["values"].pop())
win_edit = Toplevel()
win_edit.title("تغییر {} به تعداد {} و مبلغ {}".format(h_info[0], h_info[1], h_info[2]))
win_edit.minsize(400, 250)
def ok_edit():
tree.item(xitem, values=(entry_name_item.get(), entry_count_item.get(), entry_price_item.get(), float(entry_count_item.get())* int(entry_price_item.get())))
self.list_item = []
for child in tree.get_children():
self.list_item.insert(0, tree.item(child)["values"])
self.price_total = 0
self.count_total = 0
for i in range(0, len(self.list_item)):
self.count_total =self.count_total+ float(self.list_item[i][1])
self.price_total = self.price_total+ int(float(self.list_item[i][3]))
self.text_count_item_total.configure(text=self.count_total)
self.text_price_item_total.configure(text=self.price_total)
self.text_price_item_total_text.configure(text=convert_ordinary(self.price_total))
win_edit.destroy()
Label(win_edit, text="نام محصول", font=("", 16)).place(x=80, y=10)
entry_name_item = Entry(win_edit, font=("", 16))
entry_name_item.place(x=20, y=40)
Label(win_edit, text="تعداد/متر", font=("", 16)).place(x=80, y=90)
entry_count_item = Entry(win_edit, font=("", 16))
entry_count_item.place(x=20, y=120)
Label(win_edit, text="قیمت واحد", font=("", 16)).place(x=80, y=160)
entry_price_item = Entry(win_edit, font=("", 16))
Button(win_edit, text="تایید", font=("",20), command=ok_edit, width=5).place(x=290, y=100)
entry_price_item.place(x=20, y=190)
win_edit.mainloop()
def add_item2list(event=None):
self.price_total = 0
self.count_total = 0
try:
price_all = int(self.text_price_item_input.get())*float(self.text_count_item_input.get())
tree.insert("", len(self.list_item), values=(self.text_name_item_input.get(), self.text_count_item_input.get(), self.text_price_item_input.get(),int(price_all)))
self.list_item.insert(len(self.list_item), (self.text_name_item_input.get(), self.text_count_item_input.get(), self.text_price_item_input.get(), int(price_all)))
self.text_price_item.configure(text=convert_ordinary(int(self.text_price_item_input.get())))
print(self.list_item)
for i in range(0, len(self.list_item)):
self.count_total =self.count_total+ float(self.list_item[i][1])
self.price_total = self.price_total+ int(float(self.list_item[i][3]))
self.text_count_item_total.configure(text=self.count_total)
self.text_price_item_total.configure(text=self.price_total)
self.text_price_item_total_text.configure(text=convert_ordinary(self.price_total))
self.text_name_item_input.delete(0,END)
self.text_name_item_input.focus()
if self.price_total != 0:
self.btn_accept_item_end.configure(state="active")
except:
messagebox.showerror("Error", "لطفا ورودی ها را صحیح وارد کنید")
self.price_naghd_end= 0
self.price_nasiye_end= 0
self.price_kart_end = 0
def accept_end():
win_factor_end = Toplevel(self.win_factor)
win_factor_end.title("Pay")
win_factor_end.minsize(600, 300)
win_factor_end.maxsize(600, 300)
self.amount_paid = self.price_total
def chortke(event=None):
if input_naghd.get() == "":
input_naghd.insert(0,"0")
elif input_naghd.cget("state")== "normal":
print("01",input_naghd.cget("state"))
self.price_naghd_end = int(input_naghd.get()) + self.price_naghd_end
input_naghd.configure(state="disabled")
self.amount_paid = self.amount_paid - self.price_naghd_end
if input_kart.get() == "":
input_kart.insert(0,"0")
elif input_kart.cget("state")== "normal":
print("02",input_kart.cget("state"))
self.price_kart_end = int(input_kart.get())+ self.price_kart_end
input_kart.configure(state="disabled")
self.amount_paid = self.amount_paid - self.price_kart_end
if input_nasiye.get() == "":
input_nasiye.insert(0,"0")
elif input_nasiye.cget("state")== "normal":
print("03",input_nasiye.cget("state"))
self.price_nasiye_end = int(input_nasiye.get()) + self.price_nasiye_end
input_nasiye.configure(state="disabled")
self.amount_paid = self.amount_paid - self.price_nasiye_end
text_price_end.configure(text=self.amount_paid)
text_price_end_tx.configure(text=convert_ordinary(int(self.amount_paid)))
if text_naghd.cget("text") == "":
text_naghd.configure(text=convert_ordinary(int(input_naghd.get())))
if text_kart.cget("text") == "":
text_kart.configure(text=convert_ordinary(int(input_kart.get())))
if text_nasiye.cget("text") == "":
text_nasiye.configure(text=convert_ordinary(int(input_nasiye.get())))
input_nasiye.delete(0,END)
input_kart.delete(0,END)
input_naghd.delete(0,END)
if self.amount_paid == 0:
btn_taeed.configure(state="active")
def space(event= None):
copy(self.amount_paid)
input_naghd.focus_get().insert(0, paste())
def save_factor():
try:
self.tarikh = datetime.now()
print(self.tarikh)
code = self.code_buy()
with open("factors/factor_{}.csv".format(code), "w", encoding="utf-8",newline='') as csv_save:
csv_write = csv.writer(csv_save)
csv_write.writerow([self.text_name_moshtari_input.get(), code, self.tarikh, self.price_total])
csv_write.writerow([ self.text_info_more.get("1.0", END), self.price_naghd_end, self.price_kart_end, self.price_nasiye_end])
for child in tree.get_children():
print(tree.item(child)["values"])
csv_write.writerow(tree.item(child)["values"])
messagebox.showinfo("save_compelect", "فاکتور با کد {} ذخیره شد".format(code))
win_factor_end.destroy()
self.win_factor.destroy()
except:
messagebox.showerror("Error", "!!مشکلی رخ داد فاکتور ذخیره نشد")
win_factor_end.bind("<Return>",chortke)
win_factor_end.bind("<space>",space)
btn_taeed = Button(win_factor_end, text="اوکی", font=("",13), state="disabled", command=save_factor)
btn_taeed.place(x=380, y=60)
text_price_end = Label(win_factor_end, text=self.price_total, font=("", 16))
text_price_end.place(x=110, y=220)
text_price_end_tx = Label(win_factor_end, text=convert_ordinary(int(self.price_total)), font=("", 16))
text_price_end_tx.place(x=110, y=260)
Label(win_factor_end, text="دریافت شود:", font=("", 16)).place(x=10, y=220)
btn_naghd = Button(win_factor_end, text="نقدی", font=("",16), command=chortke)
btn_naghd.place(x=40, y=20)
input_naghd = Entry(win_factor_end, font=("",16), width=10)
input_naghd.place(x=110,y=25)
text_naghd = Label(win_factor_end, text="", font=("",13))
text_naghd.place(x=240, y=26)
btn_kart = Button(win_factor_end, text="کارتخوان", font=("",16), command=chortke)
btn_kart.place(x=10, y=80)
input_kart = Entry(win_factor_end, font=("",16), width=10)
input_kart.place(x=110,y=85)
text_kart = Label(win_factor_end, text="", font=("",13))
text_kart.place(x=240, y=86)
btn_nasiye = Button(win_factor_end, text="نسیه", font=("",16), command=chortke)
btn_nasiye.place(x=45, y=140)
input_nasiye = Entry(win_factor_end, font=("",16), width=10)
input_nasiye.place(x=110,y=145)
text_nasiye = Label(win_factor_end, text="", font=("",13))
text_nasiye.place(x=240, y=146)
win_factor_end.mainloop()
self.btn_accept_item = Button(self.win_factor, text="تایید", font=("",16), command=add_item2list, width=10)
self.btn_accept_item.place(x=760, y=50)
self.win_factor.bind("<Return>", add_item2list)
self.btn_delete_item = Button(self.win_factor, text="delete", font=("",16), command=delete_item, width=10)
self.btn_delete_item.place(x=15, y=430)
self.btn_delete_item = Button(self.win_factor, text="edit", font=("",16), command=edit_item, width=10)
self.btn_delete_item.place(x=15, y=480)
self.btn_accept_item_end = Button(self.win_factor, text="تایید نهایی", font=("",16), state="disabled", command=accept_end, width=10)
self.btn_accept_item_end.place(x=810, y=540)
self.win_factor.mainloop()
run=Program()

elif in list comprehension using python conditionals

for example
for p in list(extracted_data):
if (p >= 80):
print ('orange')
elif(80 > p >= 60):
print ('red')
else:
print('yellow')
Is there any list comprehension for the same.
you can do like this
x = [ 'orange' if p>=80 else 'red' if 80>p >=60 else 'yellow' for p in list(extacted_data)]
Readability and reusability ?
Chances are your business logic will need to be used in more than one place. Why not create a function that determines the color, then use list comprehension to create your list?
def colors(x):
retval = 'yellow'
if (x >= 80):
retval = 'orange'
elif(80 > x >= 60):
retval = 'red'
return retval
print([colors(x) for x in extracted_data])
Output
['orange', 'orange', 'red', 'yellow']

How to draw with mouse and save as 1s and 0s

I have implemented a custom level code on my main game. But i need a Level editor to make it easier to make custom levels. I have use buttons to cover the screen and when clicked, it will place a block (print down below is a test, it'll help me greatly if you combine the code with my main problem. Weirdly, It not printing and lagging so i need code to draw and export as the format i need (Format in Code).
import sys
pygame.init()
screen = pygame.display.set_mode((1280, 720))
white = (255,255,255)
grey = (128,128,128)
class button():
def __init__(self, color, x,y,width,height, text=''):
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
def draw(self,win, outline=None):
#Call this method to draw the button on the screen
pygame.draw.rect(win, self.color, (self.x,self.y,self.width,self.height),0)
if self.text != '':
font = pygame.font.SysFont('comicsans', 60)
text = font.render(self.text, 1, (0,0,0))
screen.blit(text, (round(self.x) + (round(self.width/2) - round(text.get_width()/2)), round(self.y) + (round(self.height/2) - round(text.get_height()/2))))
def isOver(self, pos):
#Pos is the mouse position or a tuple of (x,y) coordinates
if pos[0] > self.x and pos[0] < self.x + self.width:
if pos[1] > self.y and pos[1] < self.y + self.height:
return True
return False
WIDTH = 64
HEIGHT = 36
TILESIZE = 20
clock = pygame.time.Clock()
#the format i need it in
tm = [
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
]
buttonD = button((0,255,0), 640, 360, 20, 20, ' ')
while True:
pygame.display.update()
screen.fill(white)
for row in range(HEIGHT):
for column in range(WIDTH):
if tm[row][column] == 1:
pygame.draw.rect(screen, grey, [column*TILESIZE, row*TILESIZE, TILESIZE, TILESIZE])
wallRect = pygame.Rect(column*TILESIZE, row*TILESIZE, TILESIZE, TILESIZE)
if tm[row][column] == 0:
buttonD = button((255,255,255), column*TILESIZE, row*TILESIZE, TILESIZE, TILESIZE, ' ')
buttonD.draw(screen, (0,0,0))
for event in pygame.event.get():
pos = pygame.mouse.get_pos()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if buttonD.isOver(pos):
print('Hi')
clock.tick(60)
I Expect it to print Hi but it doesn't print and freeze
Why do you need a button?
Calculate the index of the cell when the mouse is pressed:
column = event.pos[0] // TILESIZE
row = event.pos[1] // TILESIZE
And switch the state of the cell
tm[row][column] = 1 if tm[row][column] == 0 else 0
e.g.:
while True:
for event in pygame.event.get():
pos = pygame.mouse.get_pos()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
column = event.pos[0] // TILESIZE
row = event.pos[1] // TILESIZE
if row < len(tm) and column < len(tm[row]):
tm[row][column] = 1 if tm[row][column] == 0 else 0
screen.fill(white)
for row in range(HEIGHT):
for column in range(WIDTH):
c = grey if tm[row][column] == 1 else (255,255,255)
pygame.draw.rect(screen, c, [column*TILESIZE, row*TILESIZE, TILESIZE, TILESIZE])
pygame.display.update()
clock.tick(60)
Additionally you can highlight" the cell where the mouse is on and draw a text which contains the row and column of the cell:
class button():
def __init__(self, color, x,y,width,height, text=''):
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.font = font = pygame.font.SysFont('comicsans', 20)
def draw(self, win, x, y):
pygame.draw.rect(win, self.color, (self.x,self.y,self.width,self.height),0)
text = self.font.render(str(x) + " / " + str(y), 1, (0,0,0))
screen.blit(text, (round(self.x) + (round(self.width/2) - round(text.get_width()/2)), round(self.y) + (round(self.height/2) - round(text.get_height()/2))))
buttonD = button((0,255,0), 640, 360, 20, 20, ' ')
while True:
for event in pygame.event.get():
pos = pygame.mouse.get_pos()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
column, row = event.pos[0] // TILESIZE, event.pos[1] // TILESIZE
if row < len(tm) and column < len(tm[row]):
tm[row][column] = 1 if tm[row][column] == 0 else 0
mouse_pos = pygame.mouse.get_pos()
mcol, mrow = mouse_pos[0] // TILESIZE, mouse_pos[1] // TILESIZE
buttonD.x, buttonD.y = mcol*TILESIZE, mrow*TILESIZE
screen.fill(white)
for row in range(HEIGHT):
for column in range(WIDTH):
c = grey if tm[row][column] == 1 else (255,255,255)
pygame.draw.rect(screen, c, [column*TILESIZE, row*TILESIZE, TILESIZE, TILESIZE])
buttonD.draw(screen, mcol, mrow)
pygame.display.update()
clock.tick(60)

Python Pygame Personal Module Error

So I was cleaning up my code by adding in classes, in order to put certain tools that I will be using in my game, into other files. SO as I was kinda learning and implementing, I stumbled upon an easy error that I can't find out for the life of me.
So I have my core.py and pyWMouse.py in the same folder. My pyWMouse.py just has my mouse tools that I created. I keep getting this error:
Traceback (most recent call last):
File "G:/Python/pygameDevelopment/core.py", line 115, in <module>
game_Loop()
File "G:/Python/pygameDevelopment/core.py", line 100, in game_Loop
if userMouse.MouseLeftClickDown and userMouse.MouseDrag:
AttributeError: type object 'MouseTools' has no attribute 'MouseLeftClickDown'
Here is the class in pyWMouse.py
import pygame
COLOR_RED = (255, 0, 0)
class MouseTools:
def __init__(self):
self.MouseInitXY = (0, 0)
self.MouseFinalXY = (0, 0)
self.MouseLeftClickDown = False
self.MouseRightClickDown = False
self.MouseDrag = False
self.CharacterSelected = False
self.CharacterMove = False
self.CharacterMoveTo = (0, 0)
def selection(self, screen, unitX, unitY):
# Draw lines #
pygame.draw.lines(screen, COLOR_RED, True, ((self.MouseInitXY[0], self.MouseInitXY[1]),
(self.MouseFinalXY[0], self.MouseInitXY[1]),
(self.MouseFinalXY[0], self.MouseFinalXY[1]),
(self.MouseInitXY[0], self.MouseFinalXY[1])), 3)
# Check if anything is inside the selection area from any direction the mouse highlights #
if unitX >= self.MouseInitXY[0] and unitX <= self.MouseFinalXY[0] and unitY >= \
self.MouseInitXY[1] and unitY <= self.MouseFinalXY[1]:
return True
elif unitX <= self.MouseInitXY[0] and unitX >= self.MouseFinalXY[0] and unitY <= \
self.MouseInitXY[1] and unitY >= self.MouseFinalXY[1]:
return True
elif unitX >= self.MouseInitXY[0] and unitX <= self.MouseFinalXY[0] and unitY <= \
self.MouseInitXY[1] and unitY >= self.MouseFinalXY[1]:
return True
elif unitX <= self.MouseInitXY[0] and unitX >= self.MouseFinalXY[0] and unitY >= \
self.MouseInitXY[1] and unitY <= self.MouseFinalXY[1]:
return True
else:
return False
And finally my core.py
import pygame
import pyWMouse
pygame.init()
pygame.display.set_caption('PyWorld')
DISPLAY_WIDTH = 1080
DISPLAY_HEIGHT = 920
COLOR_BLACK = (0, 0, 0)
COLOR_BROWN = (100, 50, 0)
COLOR_GREEN = (0, 102, 0)
COLOR_RED = (255, 0, 0)
COLOR_WHITE = (255, 255, 255)
screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
fpsClock = pygame.time.Clock()
class Character:
def __init__(self, XPos, YPos): # Always called when object is created, always have self variable #
self.X = XPos
self.Y = YPos
self.ImageUnselected = pygame.image.load('mainChar.png')
self.ImageSelected = pygame.image.load('mainCharSelected.png')
self.Speed = 2.5
self.YChange = 0
self.XChange = 0
def render_Unselected(self):
screen.blit(self.ImageUnselected, (self.X, self.Y))
def render_Selected(self):
screen.blit(self.ImageSelected, (self.X, self.Y))
class Worker:
def __init__(self, XPos, YPos):
self.X = XPos
self.Y = YPos
self.ImageUnselected = pygame.image.load('worker.png')
self.ImageSelected = pygame.image.load('workerSelected.png')
def worker_Unselected(self):
screen.blit(self.ImageUnselected, (self.X, self.Y))
def worker_Selected(self):
screen.blit(self.ImageSelected, (self.X, self.Y))
character = Character(DISPLAY_WIDTH/2, DISPLAY_HEIGHT/2)
userMouse = pyWMouse.MouseTools
def game_Loop():
gameExit = False
while not gameExit:
screen.fill(COLOR_BROWN)
# Keyboard Handling #
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_w]:
character.YChange = -character.Speed
if keys_pressed[pygame.K_a]:
character.XChange = -character.Speed
if keys_pressed[pygame.K_s]:
character.YChange = character.Speed
if keys_pressed[pygame.K_d]:
character.XChange = character.Speed
if keys_pressed[pygame.K_w] and keys_pressed[pygame.K_a]:
character.XChange = (-character.Speed/1.5)
character.YChange = (-character.Speed/1.5)
if keys_pressed[pygame.K_a] and keys_pressed[pygame.K_s]:
character.XChange = (-character.Speed / 1.5)
character.YChange = (character.Speed / 1.5)
if keys_pressed[pygame.K_s] and keys_pressed[pygame.K_d]:
character.XChange = (character.Speed / 1.5)
character.YChange = (character.Speed / 1.5)
if keys_pressed[pygame.K_d] and keys_pressed[pygame.K_w]:
character.XChange = (character.Speed / 1.5)
character.YChange = (-character.Speed / 1.5)
# Event handling #
for event in pygame.event.get():
if event.type == pygame.KEYUP:
if event.key != pygame.K_a or event.key != pygame.K_d:
character.XChange = 0
if event.key != pygame.K_w or event.key != pygame.K_s:
character.YChange = 0
# Mouse Handling #
if event.type == pygame.MOUSEBUTTONDOWN:
if userMouse.CharacterSelected:
userMouse.CharacterSelected = False
if event.button == 1:
userMouse.MouseLeftClickDown = True
userMouse.MouseInitXY = pygame.mouse.get_pos()
if event.button == 2:
userMouse.MouseRightClickDown = True
userMouse.CharacterMoveTo = pygame.mouse.get_pos()
if event.type == pygame.MOUSEMOTION:
userMouse.MouseDrag = True
if event.type == pygame.MOUSEBUTTONUP:
if userMouse.MouseLeftClickDown:
userMouse.MouseLeftClickDown = False
userMouse.MouseDrag = False
if event.type == pygame.QUIT:
pygame.quit()
quit()
# Mouse Tools #
if userMouse.MouseLeftClickDown and userMouse.MouseDrag:
userMouse.MouseFinalXY = pygame.mouse.get_pos()
# Check if user's character is inside selection tool #
if userMouse.selection(screen, character.X, character.Y):
character.render_Selected()
else:
character.render_Unselected()
else:
character.render_Unselected()
# Update Display and next frame variables #
character.X += character.XChange
character.Y += character.YChange
pygame.display.update()
fpsClock.tick(144)
game_Loop()
pygame.quit()
quit()
Thanks for your time everyone. Much appreciated.
I believe the problem can be found in core.py. Try changing :
userMouse = pyWMouse.MouseTools
to the following:
userMouse = pyWMouse.MouseTools()
Adding the missing parentheses should do the trick.

Constantly changing the background color in swift

Hi there im finishing my game but i want to add some detail and one of them is looping trough a color cycle i have tried SKActions, that worked fine but it overlapped everything else.
then i made this in the update function but it doesn't do anything
if BGRed == 1 {RedBoolIs1 = true}
else {RedBoolIs1 = false}
if BGGreen == 1 {GreenBoolIs1 = true}
else {GreenBoolIs1 = false}
if BGBlue == 1 {BlueBoolIs1 = true}
else {BlueBoolIs1 = false}
//red only
if RedBoolIs1 == true && GreenBoolIs1 == false && BlueBoolIs1 == false {
BGGreen = BGGreen + 0.01 }
//red and green
if RedBoolIs1 == true && GreenBoolIs1 == true && BlueBoolIs1 == false {
BGRed = BGRed - 0.01 }
//green only
if RedBoolIs1 == false && GreenBoolIs1 == true && BlueBoolIs1 == false {
BGBlue = BGBlue + 0.01 }
//green and blue
if RedBoolIs1 == false && GreenBoolIs1 == true && BlueBoolIs1 == true {
BGGreen = BGGreen - 0.01 }
//blue only
if RedBoolIs1 == false && GreenBoolIs1 == false && BlueBoolIs1 == true {
BGRed = BGRed + 0.01 }
//blue and red
if RedBoolIs1 == true && GreenBoolIs1 == false && BlueBoolIs1 == true {
BGBlue = BGBlue - 0.01 }
self.backgroundColor = SKColor(red: CGFloat(BGRed), green: CGFloat(BGGreen), blue: CGFloat(BGBlue), alpha: 1)
also is it possible to make labels readable on all colors ? my solution now is placing 2 labels on each other the first one is white and 45 big and the one above that is black and 40 big but it doesn't look always good
thanks
First we initialise the color variables like this:
var BGRed: Float = 1
var BGGreen: Float = 0
var BGBlue: Float = 0
The reason nothing happens is that adding 0.1 10 times does not equal 1.0. This is because of floating point number accuracy. I myself asked the same type of SO question.
To fix this, remove comparisons like this:
if BGGreen == 1
And replace with:
if round(BGGreen * 100) / 100.0 == 1.0
It will solve this particular problem, but the better approach is to start using decimal floating point
For the second issue, there is no easy answer but there are multiple answers on SO like this one.

Resources