PySimpleGUI Checkbox - python-3.x

Idk why, but when i check a checkbox in the menu nothings, happens, but if i close the menu the cheat start. I think that i made some mistakes setting up the checkboxes, but im trying to fix this problem from 3 days now and i can't continue anymore. Can someone help?
import PySimpleGUI as sg
import threading
from globals import *
import math
import time
import keyboard
switch = True
rcsonoff = True
r = 255
g = 3
b = 3
def normalizeAngles(viewAngleX, viewAngleY):
if viewAngleX > 89:
viewAngleX -= 360
if viewAngleX < -89:
viewAngleX += 360
if viewAngleY > 180:
viewAngleY -= 360
if viewAngleY < -180:
viewAngleY += 360
return viewAngleX, viewAngleY
def checkangles(x, y):
if x > 89:
return False
elif x < -89:
return False
elif y > 360:
return False
elif y < -360:
return False
else:
return True
def nanchecker(first, second):
if math.isnan(first) or math.isnan(second):
return False
else:
return True
layout = [
# Use a modern font and color scheme
[sg.Text("External 2.3", font="Helvetica 20", text_color="#d80fc6")],
# Use tabs to organize the buttons into different categories
[sg.TabGroup([
# Tab for aim-related buttons
[sg.Tab("Aim", [[
sg.Column(
# Define the grid layout for the buttons
[
[sg.Checkbox("No Recoil", default=False, key="no_recoil_checkbox")],
[sg.Checkbox("TriggerBot", default=False, key="triggerbot_checkbox")]
],
# Set the number of rows and columns in the grid
)
]]),
# Tab for visual-related buttons
sg.Tab("Visuals", [[
sg.Column(
# Define the grid layout for the buttons
[
[sg.Checkbox("Glow", default=False, key="glow_checkbox")],
[sg.Checkbox("Chams", default=False, key="chams_checkbox")],
[sg.Checkbox("Fov", default=False, key="fov_checkbox")],
[sg.Text("Fov Value (MAX 140): "), sg.InputText(key="fov")],
[sg.Button("Set FOV Value", button_color=("magenta", "#a9a9a9"))]
],
# Set the number of rows and columns in the grid
)
]]),
sg.Tab("Misc", [[
sg.Column(
[
[sg.Checkbox("Bunny Hop", default=False, key="bunny_hop_checkbox")],
[sg.Checkbox("Radar Hack", default=False, key="radar_hack_checkbox")],
[sg.Checkbox("Show Rank", default=False, key="show_rank_checkbox")],
[sg.Checkbox("Third Person", default=False, key="3_person_checkbox")],
[sg.Checkbox("No Flash", default=False, key="no_flash_checkbox")]
],
)
]]),
sg.Tab("LocalPlayer", [[
sg.Column(
[
[sg.Text("Player Health:")],
[sg.Text(key="Health")],
[sg.Text("Armor:")],
[sg.Text(key="Armor")],
[sg.Text("Enter a new value:")],
[sg.InputText(key="NewArmor")],
[sg.Button("Update Armor")],
[sg.Text("Enter a new money value:")],
[sg.InputText(key="Money")],
[sg.Button("Update Money")]
],
)
]]),
# Tab for color-related buttons
sg.Tab("Color and Debug", [[
sg.Column(
# Define the grid layout for the sliders
[
[sg.Button("Debug", button_color=("magenta", "#a9a9a9"))],
[sg.Text("Enter the glow color values:")],
[sg.Text("Red:"), sg.InputText(key="Red")],
[sg.Text("Green:"), sg.InputText(key="Green")],
[sg.Text("Blue:"), sg.InputText(key="Blue")],
[sg.Button("Set Glow Color")]
],
# Set the number of rows and columns in the grid
)
]])
]])]
]
window = sg.Window("Buck3ts41", layout, element_justification="center")
def debug():
while True:
print("crossID ", crosshairID)
print("corssTeam ", crosshairTeam)
print("LocalPlayer ", player)
print("LocalTeam ", localTeam)
print("GlowManager ", glow_manager)
print("GetTeam ", getTeam)
time.sleep(2)
def esp():
while True:
try:
if glow == True:
for i in range(1, 32):
entity = pm.read_int(client + dwEntityList + i * 0x10)
if entity:
entity_hp = pm.read_uint(entity + m_iHealth)
entity_team_id = pm.read_uint(entity + m_iTeamNum)
entity_dormant = pm.read_uint(entity + m_bDormant)
entity_glow = pm.read_uint(entity + m_iGlowIndex)
if entity_team_id == 2 and localTeam != 2 and not entity_dormant: ###TERRORIST###
pm.write_float(glow_manager + entity_glow * 0x38 + 0x8, float(r)) # R
pm.write_float(glow_manager + entity_glow * 0x38 + 0xC, float(g)) # G
pm.write_float(glow_manager + entity_glow * 0x38 + 0x10, float(b)) # B
pm.write_float(glow_manager + entity_glow * 0x38 + 0x14, float(255)) # A
pm.write_int(glow_manager + entity_glow * 0x38 + 0x28, 1) # START
elif entity_team_id == 3 and localTeam != 3 and not entity_dormant: ###COUNTER###
pm.write_float(glow_manager + entity_glow * 0x38 + 0x8, float(r)) # R
pm.write_float(glow_manager + entity_glow * 0x38 + 0xC, float(g)) # G
pm.write_float(glow_manager + entity_glow * 0x38 + 0x10, float(b)) # B
pm.write_float(glow_manager + entity_glow * 0x38 + 0x14, float(255)) # A
pm.write_int(glow_manager + entity_glow * 0x38 + 0x28, 1) # START
except Exception as err:
pass
time.sleep(0.001)
def chamshack():
if chams:
rgbt = [255, 0, 0]
rgbc = [0, 0, 255]
while True:
try:
time.sleep(0.001)
for i in range(1, 32):
entity = pm.read_int(client + dwEntityList + i * 0x10)
if entity:
entity_team_id = pm.read_uint(entity + m_iTeamNum)
if entity_team_id == 2: # terrorist
pm.write_int(entity + m_clrRender, (rgbt[0])) # R
pm.write_int(entity + m_clrRender + 0x1, (rgbt[1])) # G
pm.write_int(entity + m_clrRender + 0x2, (rgbt[2])) # B
elif entity_team_id == 3: # counter
pm.write_int(entity + m_clrRender, (rgbc[0])) # R
pm.write_int(entity + m_clrRender + 0x1, (rgbc[1])) # G
pm.write_int(entity + m_clrRender + 0x2, (rgbc[2])) # B
else:
pass
except Exception as err:
pass
time.sleep(0.001)
def norcs():
if no_recoil:
oldpunchx = 0.0
oldpunchy = 0.0
while switch:
try:
time.sleep(0.01)
if rcsonoff:
rcslocalplayer = pm.read_uint(client + dwLocalPlayer)
rcsengine = pm.read_uint(engine + dwClientState)
if pm.read_int(rcslocalplayer + m_iShotsFired) > 1:
rcs_x = pm.read_float(rcsengine + dwClientState_ViewAngles)
rcs_y = pm.read_float(rcsengine + dwClientState_ViewAngles + 0x4)
punchx = pm.read_float(rcslocalplayer + m_aimPunchAngle)
punchy = pm.read_float(rcslocalplayer + m_aimPunchAngle + 0x4)
newrcsx = rcs_x - (punchx - oldpunchx) * 2.0
newrcsy = rcs_y - (punchy - oldpunchy) * 2.0
newrcs, newrcy = normalizeAngles(newrcsx, newrcsy)
oldpunchx = punchx
oldpunchy = punchy
if nanchecker(newrcsx, newrcsy) and checkangles(newrcsx, newrcsy):
pm.write_float(rcsengine + dwClientState_ViewAngles, newrcsx)
pm.write_float(rcsengine + dwClientState_ViewAngles + 0x4, newrcsy)
else:
oldpunchx = 0.0
oldpunchy = 0.0
newrcsx = 0.0
newrcsy = 0.0
except Exception as err:
pass
time.sleep(0.001)
def bhop():
if bunny_hop:
while True:
try:
if keyboard.is_pressed("space"):
force_jump = client + dwForceJump
player = pm.read_int(client + dwLocalPlayer)
on_ground = pm.read_int(player + m_fFlags)
if player and on_ground and on_ground == 257:
pm.write_int(force_jump, 5)
time.sleep(0.08)
pm.write_int(force_jump, 4)
except Exception as err:
pass
time.sleep(0.001)
def fovhack():
if fov:
while True:
try:
player = pm.read_int(client + dwEntityList)
pm.write_int(player + m_iDefaultFOV, Fov)
except Exception as err:
pass
time.sleep(0.001)
def r5():
if radar_hack:
while True:
try:
for i in range(1, 32):
entity = pm.read_int(client + dwEntityList + i * 0x10)
if entity:
pm.write_uchar(entity + m_bSpotted, 1)
except Exception as err:
pass
time.sleep(0.001)
def trigger():
if triggerbot:
while True:
try:
# If the crosshair is on an enemy, shoot
if crosshairID > 0 and crosshairID < 64 and crosshairTeam != localTeam:
keyboard.press("attack")
time.sleep(0.1)
keyboard.release("attack")
time.sleep(0.1)
except Exception as err:
pass
time.sleep(0.001)
def person():
if third_person:
switch = 0
while True:
try:
localplayer = pm.read_int(client + dwLocalPlayer)
if keyboard.is_pressed('z') and switch == 0:
pm.write_int(localplayer + m_iObserverMode, 1)
switch = 1
time.sleep(0.5)
if keyboard.is_pressed('z') and switch == 1:
pm.write_int(localplayer + m_iObserverMode, 0)
switch = 0
time.sleep(0.5)
except Exception as err:
pass
time.sleep(0.001)
def noflash():
if no_flash:
if player:
flash_value = player + m_flFlashMaxAlpha
if flash_value:
pm.write_float(flash_value, float(0))
else:
pass
def rank():
if show_rank:
ranks = ["Unranked",
"Silver I",
"Silver II",
"Silver III",
"Silver IV",
"Silver Elite",
"Silver Elite Master",
"Gold Nova I",
"Gold Nova II",
"Gold Nova III",
"Gold Nova Master",
"Master Guardian I",
"Master Guardian II",
"Master Guardian Elite",
"Distinguished Master Guardian",
"Legendary Eagle",
"Legendary Eagle Master",
"Supreme Master First Class",
"The Global Elite"]
for i in range(0, 32):
entity = pm.read_uint(client.lpBaseOfDll + dwEntityList + i * 0x10)
if entity:
entity_team_id = pm.read_uint(entity + m_iTeamNum)
if entity_team_id:
player_info = pm.read_uint(
(pm.read_uint(engine.lpBaseOfDll + dwClientState)) + dwClientState_PlayerInfo)
player_info_items = pm.read_uint(pm.read_uint(player_info + 0x40) + 0xC)
info = pm.read_uint(player_info_items + 0x28 + (i * 0x34))
playerres = pm.read_uint(client.lpBaseOfDll + dwPlayerResource)
rank = pm.read_uint(playerres + m_iCompetitiveRanking + (i * 4))
wins = pm.read_uint(playerres + m_iCompetitiveWins + i * 4)
if pm.read_string(info + 0x10) != 'GOTV':
print(rank)
print(pm.read_string(info + 0x10) + " --> " + ranks[rank])
print(wins)
global glow, chams, no_recoil, triggerbot, bunny_hop, radar_hack, fov, third_person, no_flash, show_rank
while True:
event, values = window.read(timeout=100)
if event == "exit" or event == sg.WIN_CLOSED:
break
if event == "__TIMEOUT__":
# Read the health value of the player
health = pm.read_uint(player + m_iHealth)
# Update the displayed health value
window["Health"].update(str(health))
if event == "Set Glow Color":
# Split the input string into a list of strings representing the red, green, and blue values
r = values["Red"]
g = values["Green"]
b = values["Blue"]
# Convert the strings to integers
r = int(r)
g = int(g)
b = int(b)
if event == "Update Money":
# Read the new money value from the textbox
new_money = values["Money"]
# Convert the new money value to an integer
new_money = int(new_money)
# Write the new money value to the game's memory
pm.write_int(player + m_iAccountID, new_money)
if event == "Update Armor":
# Read the new armor value from the textbox
new_armor = values["NewArmor"]
# Convert the new armor value to an integer
new_armor = int(new_armor)
# Update the armor value
pm.write_int(player + m_ArmorValue, new_armor)
# Update the displayed armor value
window["Armor"].update(str(new_armor))
if event == "Set FOV Value":
Fov = values["fov"]
Fov = int(Fov)
if values["glow_checkbox"] == True:
glow = True
else:
glow = False
if values["chams_checkbox"] == True:
chams = True
else:
chams = False
if values["bunny_hop_checkbox"] == True:
bunny_hop = True
else:
bunny_hop = False
if values["fov_checkbox"] == True:
fov = True
else:
fov = False
if values["radar_hack_checkbox"] == True:
radar_hack = True
else:
radar_hack = False
if values["triggerbot_checkbox"] == True:
triggerbot = True
else:
triggerbot = False
if values["3_person_checkbox"] == True:
third_person = True
else:
third_person = False
if values["no_flash_checkbox"] == True:
no_flash = True
else:
no_flash = False
if values["show_rank_checkbox"] == True:
show_rank = True
else:
show_rank = False
if values["no_recoil_checkbox"] == True:
no_recoil = True
else:
no_recoil = False
if event == "Debug":
debug()
def start_threads():
try:
threading.Thread(target=esp, name='esp').start()
threading.Thread(target=chamshack, name='chamshack').start()
threading.Thread(target=person, name='person').start()
threading.Thread(target=rank, name='rank').start()
threading.Thread(target=norcs, name='norcs').start()
threading.Thread(target=trigger, name='trigger').start()
threading.Thread(target=bhop, name='bhop').start()
threading.Thread(target=r5, name='r5').start()
threading.Thread(target=noflash, name='noflash').start()
threading.Thread(target=fovhack, name='fovhack').start()
except Exception as err:
print(f'Threads have been canceled! Exiting...\nReason: {err}\nExiting...')
exit(1)
start_threads()
window.close()
i really don't know what im i doing wrong, i have decent experience with python but pysimpleGUI is another thing...

Related

Electric Vehicle Routing Path Simulation Giving Wrong Output

My electric vehicle charging algorithm aims at returning the shortest path length by a charging drone. The drone will meet the electric vehicle at a rendezvous point and charge the vehicle. The vehicle selection is done based on the charging urgency of the vehicles. The total path length is calculated when all vehicles are charged based on their urgency. The pseudocode is:
EDF(List_Req)
SunchrgEV = List_Req
Pathlen = 0
Nchgreq = 0
while(SunchrgEV = 0):
U obtains the updated location of all ei element of SunchrgEV via message exchange
S'gcs = set of GCS element of Sgcs
Gr = min {Eucleadian distance between Loc(ei) and Loc(Gj)} //The closest GCS
ex = min [{Eucleadian distance between Loc(ei) and Loc(Gr)}/ResidDist(ei)] // most urgent EV
if SoC(U)<RqB2D(ex) // then U(the drone) itself needs charge and it reports its termination to the server
// the server dispatches another U(drone) to charge the remaining EVs (ei)
Gr = min {Eucleadian distance between Loc(U) and Loc(Gj)} //The closest GCS to U where U goes to full charge
end if
t = tcurrent
// Finding rendezvous point where ex and U meets
RdvLoc = FindRdvLoc(ex, Loc(ex), Loc(U),t)
if RdvLoc is out of service area of U then
Report2server(ex,'Outofservicearea')
continue
end if
Pathlen += Dist2(Loc(U),RdvLoc)
U sends RdvLoc to ex and flies to RdvLoc
if U reaches ex in ChgRng(U) then
{Pathlen += Charge(ex, RdvLoc)
Nchgreq ++
}
else
Report2server(ex, 'Outofservicearea')
endif
SunchrgEV -= ex
do
Update (Loc(U))
Gr = min {Eucleadian distance between Loc(U) and Loc(Gj)} //U returns to Gr
Pathlen += Dist2(Loc(U), Loc(Gr))
return Pathlen and Nchgreq
//Compute the expected location where U meets e on Map(e)
def FindRdvLoc(e,Le,Lu,t):
Compute X = (x,y) on Rte(e,t) so that {Dist(e,X)/Speed(e,t)} = {Dist(U, X-ChgRng(U))/Speed(U)}
return X
def Charge(ei, RdvLoc):
U starts to charge ei and follows Rte(ei,t)
eLoc = FindLoc(Map(ei), Loc(ei), ChgTime(ei), Speed(ei,t))
return DistM(Map(ei), RdvLoc, eLoc)
The code that I have written so far gives the same output regardless of the input. The code is:
import math
import sys
from typing import List, Any
class Location:
x = 0
y = 0
def __init__(self, x, y):
self.x = x
self.y = y
class Result:
path_len: int = 0
n_charge_request: int = 0
def __init__(self, path_len, n_charge_request):
self.path_len = path_len
self.n_charge_request = n_charge_request
def to_string(self):
return "path len : " + str(self.path_len) + ", n_charge_request : " + str(self.n_charge_request)
def print(self):
print(self.to_string())
#SGCs
class ChargingStation:
def __init__(self, location: Location, fuel):
self.location = location
self.fuel = fuel
#EVs(ex)
class Vehicle:
location = Location(0, 0)
fuel = 1
isNeedEmergencyFuel = False
per_fuel_distance_travel = 2
def __init__(self, id, location, fuel):
self.id = id
self.location = location
self.fuel = fuel
# Resid (U)
def residual_distance(self):
return self.fuel * self.per_fuel_distance_travel # assuming each watt or kw fuel will yield to 2 killos or milies
# RqB2D
def requested_amount_of_charge(self, nearest_charge_station_location: Location) -> int:
distance = get_distance(self.location, nearest_charge_station_location)
cover = self.fuel * self.per_fuel_distance_travel
diff = math.fabs(distance - cover)
if diff > 0:
needed_fuel = diff / self.per_fuel_distance_travel + 2
return needed_fuel
return 0
# U(i)
class Drone:
location = Location(0, 0)
fuel = 0
isFlying = False
isSendForEvCharge = False
per_fuel_distance_travel = 20
serving_radius = 15
G = [
ChargingStation(Location(20, 10), 50),
ChargingStation(Location(50, 80), 40),
ChargingStation(Location(30, 30), 60)
]
def __init__(self, location, fuel):
self.location = location
self.fuel = fuel
# Resid (U)
def residual_distance(self):
return self.fuel * self.per_fuel_distance_travel # assuming each unit of fuel will yield to 2 kilos or miles
def is_out_of_service_zone(self, vehicle_location: Location): # ----->
distance = get_distance(self.location, vehicle_location)
return distance > self.serving_radius
#staticmethod
def get_distance(from_location, to_location):
x_dis = to_location.x - from_location.x
y_dis = to_location.y - from_location.y
x_dis_sqr = math.pow(x_dis, 2)
y_dis_sqr = math.pow(y_dis, 2)
final_dis_sum = x_dis_sqr + y_dis_sqr
final = math.sqrt(final_dis_sum)
return final
class EDFGenerator:
min_fuel = 50
charging_stations_for_drones = [ChargingStation(Location(2, 10), 80), ChargingStation(Location(2, 10), 50),
ChargingStation(Location(2, 10), 100)]
list_waiting_drones = [Drone(Location(5, 10), 50), Drone(Location(2, 10), 50), Drone(Location(2, 10), 50)]
list_sent_drones = []
list_charging_drones = []
def __init__(self):
pass
def rdv_loc(self, ei: Vehicle, drone_location: Location, t: int) -> Location | None:
needed_fuel = ei.requested_amount_of_charge(drone_location)
nearest_charge_station = self.get_nearest_charge_station(ei.location, self.charging_stations_for_drones)
needed_fuel_at_nearest_station = needed_fuel / ei.per_fuel_distance_travel
if nearest_charge_station.fuel < needed_fuel_at_nearest_station:
return None
else:
return nearest_charge_station.location
#staticmethod
def get_nearest_charge_station(from_location: Location, list_of_stations: List[ChargingStation]) -> ChargingStation:
nearest = list_of_stations[0]
min_distance = get_distance(from_location, nearest.location)
for station in list_of_stations:
dis = get_distance(from_location, station.location)
if min_distance > dis:
min_distance = dis
nearest = station
return nearest
def NChgReq(self) -> int:
charging_requesters = 0
for drone in self.list_waiting_drones:
if drone.isNeedEmergencyFuel:
charging_requesters += 1
return charging_requesters
def send_drone_to_charge(self, drone: Drone): # ----->
if drone.fuel < self.min_fuel:
nearest_station = self.get_nearest_charge_station(
drone.location,
self.charging_stations_for_drones)
self.list_sent_drones.append(drone)
self.list_waiting_drones.remove(drone)
drone.isSendForEvCharge = True
# send the drone to the charging station here
print(f"Drone {drone} sent to charging station at {nearest_station}")
def check_fuel_and_send_to_charge(self): # ----->
for drone in self.list_waiting_drones:
self.send_drone_to_charge(drone)
def get_drone(self, max_try=4) -> Drone:
if max_try <= 0:
print("max try failed for get_drone")
return None
# take one time from list_waiting_drones ------->
# add to list_sent_drones
# send or return the taken item
if len(self.list_waiting_drones) == 0:
return None
else:
# lastOne = self.list_waiting_drones.pop()
self.last_one = self.list_waiting_drones.pop()
if self.last_one.fuel < self.min_fuel:
print("low fuel failed to get_drone, retry")
self.list_waiting_drones.insert(0, self.last_one)
return max_try - 1
self.list_sent_drones.append(self.last_one)
return self.last_one
def get_closest_location_from_sending_server_to_e_vehicle(self, current_vechicle_location):
min_distance = sys.maxsize
for current_server in self.charging_stations_for_drones:
distance = get_distance(current_vechicle_location, current_server.location)
if min_distance > distance:
min_distance = distance
return min_distance
def get_most_urgent_electric_vehicle(self, closest_distance_between_server_ev: int,
all_uncharged_electric_vehicles: List[Vehicle]) -> Vehicle:
final_ev = None
min_distance = sys.maxsize
for ev in all_uncharged_electric_vehicles:
g_r = self.get_closest_location_from_sending_server_to_e_vehicle(ev.location)
residual_distance = ev.residual_distance()
eq = g_r / residual_distance
if min_distance > eq:
min_distance = eq
final_ev = ev
return final_ev
def reports_termination_to_server(self, drone: Drone):
self.list_charging_drones.append(drone)
self.charge_all_waiting_drones()
def charge_all_waiting_drones(self):
# assuming the environment is not async but synchronous
for drone in self.list_charging_drones:
drone.fuel = 100
self.list_waiting_drones.insert(0, drone)
self.list_charging_drones.clear()
#staticmethod
def report_to_server(ev: Vehicle, message):
print(ev.id + " - " + message)
def get_edf(self, list_req: List[Vehicle]) -> Result:
s_uncharged_electric_vehicles = list_req
path_len = 0
n_charge_req = 0
while len(s_uncharged_electric_vehicles) > 0:
print("uncharged_ev : " + str(len(s_uncharged_electric_vehicles)))
current_uncharged_ev = s_uncharged_electric_vehicles[0]
u = self.get_drone()
if u is None:
print("no drones from any station or with min charge")
return Result(path_len, n_charge_req)
# current_uncharged_ev.location aka e----->
e = current_uncharged_ev.location
# confusion SGCS what would be the SET
g_r: int = self.get_closest_location_from_sending_server_to_e_vehicle(
e) # closest vehicle from sending location
# confusion regarding dis (loc(e), g_r) , g_r already contains the distance
e_x = self.get_most_urgent_electric_vehicle(g_r, s_uncharged_electric_vehicles)
drone_residual_distance = u.residual_distance() # Resid (U)
ev_requested_amount_of_charge = e_x.requested_amount_of_charge(u.location) # RqB2D
if drone_residual_distance < ev_requested_amount_of_charge:
self.reports_termination_to_server(u)
u = self.get_drone()
g_r_2 = self.get_closest_location_from_sending_server_to_e_vehicle(
u.location) # closest vehicle from sending location
self.reports_termination_to_server(u) # sends back the drone for charging
# ?? t is something confusing, how to include t into the equation??
rdv_loc = self.rdv_loc(e_x, u.location, 0) # t should be random
if rdv_loc is None:
self.report_to_server(e_x, "rdv location generate failed")
continue
if u.is_out_of_service_zone(rdv_loc):
self.report_to_server(e_x, "Out of Service")
continue
path_len += get_distance(u.location, rdv_loc)
u.location = rdv_loc
e_x.location = rdv_loc
# list_1 = filter(lambda x: x[3] <= 0.3 and x[2] < 5, list_1)
s_uncharged_electric_vehicles.remove(e_x)
n_charge_req = n_charge_req + 1
return Result(path_len, n_charge_req)
if __name__ == '__main__':
edf_runner = EDFGenerator()
un_charged_vehicles = [
Vehicle(1, Location(1, 1), 2),
Vehicle(2, Location(5, 10), 16),
Vehicle(3, Location(6, 10), 13),
Vehicle(4, Location(8, 11), 22),
Vehicle(5, Location(5, 6), 35),
]
edf_result = edf_runner.get_edf(un_charged_vehicles)
print("first_path_len - edf : ")
edf_result.print()
Where am I wrong? What needs fix?

How to pass values from one thread to another thread Python?

I begin to code the python and I am not have more experience in syntax of python
I want to send a value from the RFID reader. If it saves successfully, the PIR Motion Sensor will be disabled in a moment. and reworking within the specified time.
If the temperature is measured And send the value to the function RFID Reader to record the temperature and the PIR Motion Sensor stops working as well.
class Security:
global dbHost
global dbUser
global dbPass
global dbNameEmp
global dbNameSecure
dbHost = 'localhost'
dbUser = 'root'
dbPass = 'iTdev#2020'
dbNameEmp = 'empinfo'
dbNameSecure = 'secureinfo'
def __init__(self):
self.msg=""
def Temperature(self):
while True:
GPIO.output(TRIG, False)
time.sleep(0.5)
GPIO.output(TRIG, True)
time.sleep(0.01)
GPIO.output(TRIG, False)
while GPIO.input(ECHO) == 0 :
pulse_start = time.time()
while GPIO.input(ECHO) == 1 :
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 11150
distance = round(distance,2)
if distance > 0 and distance < 3 :
buzzer.on()
time.sleep(0.1)
buzzer.off()
print ("Distance: %scm" % (distance))
#print "Ambient Temperature :", sensor.get_ambient()
print ("Temperature: %.1fc" % (sensor.get_object_1()))
msgTemp = ("%.1f" % (sensor.get_object_1()))
w, h = textsize(msgTemp, font=proportional(CP437_FONT))
if w <= device.width:
x = round((device.width - w) / 2)
with canvas(device) as draw:
text(draw, (x, 0), msgTemp, fill="white", font=proportional(CP437_FONT))
else:
show_message(device, msgTemp, fill="white", font=proportional(CP437_FONT),scroll_delay=0.04)
time.sleep(1)
device.clear()
def rfid_callback(self, state, dev):
rfid_presented = ""
keys = "X^1234567890XXXXqwertzuiopXXXXasdfghjklXXXXXyxcvbnmXXXXXXXXXXXXXXXXXXXXXXX"
while True:
r,w,x = select([dev], [], [])
for event in dev.read():
if event.type==1 and event.value==1:
if event.code==28:
rfid_presented = rfid_presented.replace("X", "")
travel = state.replace("Thread-", "")
dbConnEmp = mysql.connect(host=dbHost, user=dbUser, passwd=dbPass, db=dbNameEmp)
curEmp = dbConnEmp.cursor()
curEmp.execute("Select RFidEmp FROM RFidMaster WHERE (RFidStatus = 1) AND RFidNumber = '%s'" % (rfid_presented))
resultRFid = curEmp.fetchone()
if curEmp.rowcount != 1:
# print("Access Denied." + travel)
with canvas(device) as draw:
text(draw, (0, 0), "None", fill="white", font=proportional(CP437_FONT))
time.sleep(0.5)
device.clear()
else:
# print("Unlocking Door." + travel)
dbConnSecure = mysql.connect(host=dbHost, user=dbUser, passwd=dbPass, db=dbNameSecure)
curSecure = dbConnSecure.cursor()
curSecure.execute("SELECT EntraId,DATE_FORMAT(CreateDate, '%Y%m%d') AS CreateDate FROM entranlog ORDER BY EntraId DESC, CreateDate DESC LIMIT 1")
resultKey = curSecure.fetchone()
KeyDate = time.strftime("%Y%m%d")
if curSecure.rowcount != 1:
KeyId = KeyDate+"0001"
else:
if resultKey[1] == KeyDate:
iSum = int(resultKey[0])
def sum(x, y):
return x + y
KeyId = ('%d' % sum(iSum, 1))
else:
KeyId = KeyDate+"0001"
create_date = time.strftime('%Y-%m-%d %H:%M:%S')
insertSecure = "INSERT INTO entranlog (EntraId,EntraAction,EntraStatus,CreateBy,CreateDate) VALUES (%s,%s,%s,%s,%s)"
valSecure = (KeyId,travel,1,resultRFid[0],create_date)
curSecure.execute(insertSecure, valSecure)
dbConnSecure.commit()
# print("Welcome: " + resultRFid[0])
with canvas(device) as draw:
text(draw, (0, 0), "Hello", fill="white", font=proportional(CP437_FONT))
print(curSecure.rowcount, "record inserted.")
time.sleep(0.8)
device.clear()
rfid_presented = ""
else:
rfid_presented += keys[ event.code ]
def PirSensor(self):
while True:
led_blue.on()
time.sleep(0.1)
current_state = GPIO.input(pir_sensor)
if current_state == 1:
print("GPIO pin %s is %s" % (pir_sensor, current_state))
GPIO.output(relay_alarm,True)
led_blue.off()
led_red.blink(0.1, 0.2)
# buzzer.beep(0.5, 0.5, 3)
time.sleep(5)
GPIO.output(relay_alarm,False)
led_red.off()
led_yellow.blink(0.5, 0.5)
time.sleep(5)
led_yellow.off()
def main(self):
devIn = threading.Thread(target=self.rfid_callback, args=['1', InputDevice('/dev/input/event0')])
devIn.start()
devOut = threading.Thread(target=self.rfid_callback, args=['2', InputDevice('/dev/input/event1')])
devOut.start()
Pir = threading.Thread(target=self.PirSensor)
Pir.start()
Temp = threading.Thread(target=self.Temperature)
Temp.start()
if __name__ == "__main__":
g=Security()
g.main()

Tkinter convert entry.get() to integer problem

I am coding a program with Tkinter to calculate wind values. It takes Rwy Heading, Wind Direction and Wind Speed to calculate the wind whether headwind, tailwind or crosswind with the calculated relevant wind speed.
I get this error:
Traceback (most recent call last):
File "C:\Users\altug\Desktop\PROJECTS\ÇALIŞMA.py", line 40, in <module>
rwy_var= int(rwy)
ValueError: invalid literal for int() with base 10: ''
I both tried IntVar() and int(str) method to convert string into integer but it didn't sort out the problem.
Below you can find my code:
ent1 = Entry(root)
ent1.grid(row = 0, column = 1)
ent2 = Entry(root)
ent2.grid(row = 1, column = 1)
ent3 = Entry(root)
ent3.grid(row = 2, column = 1)
rwy = ent1.get()
wind_direction = ent2.get()
wind_speed = ent3.get()
rwy_var= IntVar()
wind_direction_var= IntVar()
wind_speed_var = IntVar()
rwy_var= int(rwy)
wind_direction_var= int(wind_direction)
wind_speed_var = int(wind_speed)
x = rwy_var - wind_direction_var
radx = math.radians(x)
sinx = math.sin(radx)
cosx = math.cos(radx)
def htwind():
txt.delete(0.0, "end")
b = rwy_var + 90
a = rwy_var - 90
if b > 360:
b -= 360
elif a <0:
a+= 360
if x == abs(90):
result = 0
txt.insert(0.0, result +'\n')
elif a <= wind_direction_var or wind_direction_var<= b :
sh = wind_speed_var * cosx
result = "Headwind"+ " " + round(abs(sh))+ " " + "kt"
txt.insert(0.0, result +'\n')
elif a >= wind_direction_var or wind_direction_var >= b :
st = wind_speed_var * cosx
result = "Tailwind"+ " " + round(abs(st))+ " " + "kt"
txt.insert(0.0, result +'\n')
return ""
def xwind():
txt.delete(0.0, "end")
c=rwy_var-180
d= rwy_var + 180
if d > 360:
d -= 360
elif c<0:
c+= 360
if x == 0 or x == abs(180) or y == 0 or y == abs(180):
print("0")
elif c< wind_direction_var:
sxwl = wind_speed_var * sinx
rslt = "L"+""+round(abs(sxwl))+""+"kt"
txt.insert(0.0, rslt +'\n')
elif wind_direction_var<d:
sxwr = wind_speed_var * sinx
rslt = "R"+""+round(abs(sxwr))+""+"kt"
txt.insert(0.0, rslt +'\n')
return ""
txt = Text(root, width=6, height=2, wrap =WORD)
txt.grid(row =1, column = 1)
button_1 =Button(root, text = "search", command=lambda:[htwind(),xwind()])
button_1.grid(row =0, column = 5)
What is my mistake ?
Thanks in advance.
The IntVar is special in that it can't be directly converted to an int. To get its int value, do
rwy_var = rwy.get()

List in object gets overwritten

After some work I finished my first algorithm for a maze generator and now I am trying to make it visual in Pygame. I first let the algorithm generate a maze and then I make a visual representation of it.
Here I get into multiple problems, but I think they are all linked to the same thing which is that the first cell of the maze gets overwritten in some way. Because of this, what I get is totally not a maze at all but just some lines everywhere.
I tried putting the removal of walls in a seperate method, but that does not seem to work also. I looked if the remove walls method gets called at the first cell and it says it is true, but in some way the values of that cell gets overwritten.
Code:
import pygame
import random
WIDTH = 300
HEIGHT = 300
CellSize = 30
Rows = int(WIDTH/30)
Columns = int(HEIGHT/30)
current = None
grid = []
visited = []
DISPLAY = pygame.display.set_mode((WIDTH, HEIGHT))
class Cell:
def __init__(self, r, c):
self.r = r
self.c = c
self.x = CellSize * c
self.y = CellSize * r
self.sides = [True, True, True, True] # Top, Bottom, Left, Right
self.visited = False
self.neighbours = []
self.NTop = None
self.NBottom = None
self.NRight = None
self.NLeft = None
self.NTopIndex = None
self.NBottomIndex = None
self.NRightIndex = None
self.NLeftIndex = None
self.nr = None
self.nc = None
self.random = None
self.neighbour = None
def index(self, nr, nc):
self.nr = nr
self.nc = nc
if self.nr < 0 or self.nc < 0 or self.nr > Rows-1 or self.nc > Columns-1:
return -1
return self.nr + self.nc * Columns
def neighbour_check(self):
# Get neighbour positions in Grid
self.NTopIndex = self.index(self.r, self.c - 1)
self.NBottomIndex = self.index(self.r, self.c + 1)
self.NRightIndex = self.index(self.r + 1, self.c)
self.NLeftIndex = self.index(self.r - 1, self.c)
# Look if they are truly neighbours and then append to neighbour list
if self.NTopIndex >= 0:
self.NTop = grid[self.NTopIndex]
if not self.NTop.visited:
self.neighbours.append(self.NTop)
if self.NBottomIndex >= 0:
self.NBottom = grid[self.NBottomIndex]
if not self.NBottom.visited:
self.neighbours.append(self.NBottom)
if self.NRightIndex >= 0:
self.NRight = grid[self.NRightIndex]
if not self.NRight.visited:
self.neighbours.append(self.NRight)
if self.NLeftIndex >= 0:
self.NLeft = grid[self.NLeftIndex]
if not self.NLeft.visited:
self.neighbours.append(self.NLeft)
# Choose random neighbour
if len(self.neighbours) > 0:
self.random = random.randint(0, len(self.neighbours) - 1)
self.neighbour = self.neighbours[self.random]
# Remove the wall between self and neighbour
if self.neighbour == self.NTop:
if self == grid[0]:
print('TOP')
self.sides[0] = False
self.NTop.sides[1] = False
elif self.neighbour == self.NBottom:
if self == grid[0]:
print('BOTTOM')
self.sides[1] = False
self.NBottom.sides[0] = False
elif self.neighbour == self.NLeft:
if self == grid[0]:
print('LEFT')
self.sides[2] = False
self.NLeft.sides[3] = False
elif self.neighbour == self.NRight:
if self == grid[0]:
print('RIGHT')
self.sides[3] = False
self.NRight.sides[2] = False
else:
print('SIDES ERROR')
return self.neighbours[self.random]
else:
return -1
def draw(self):
global DISPLAY, CellSize
# Top
if self.sides[0]:
pygame.draw.line(DISPLAY, (0, 0, 0), (self.x, self.y), (self.x + CellSize, self.y))
# Bottom
if self.sides[1]:
pygame.draw.line(DISPLAY, (0, 0, 0), (self.x, self.y + CellSize), (self.x + CellSize, self.y + CellSize))
# Left
if self.sides[2]:
pygame.draw.line(DISPLAY, (0, 0, 0), (self.x, self.y), (self.x, self.y + CellSize))
# Right
if self.sides[3]:
pygame.draw.line(DISPLAY, (0, 0, 0), (self.x + CellSize, self.y), (self.x + CellSize, self.y + CellSize))
class Maze:
def __init__(self):
global current
self.next = None
self.running = True
self.DISPLAY = None
self.display_running = True
def init_cells(self):
# Make grid and make cell 0 the begin of the algorithm
global current
for i in range(0, Columns):
for j in range(0, Rows):
cell = Cell(j, i)
grid.append(cell)
current = grid[0]
def init_maze(self):
global current, visited
print(grid[0].sides)
# Start Algorithm
while self.running:
# Check if the current cell is visited, if not make it visited and choose new neighbour
if not current.visited:
current.visited = True
visited.append(current)
self.next = current.neighbour_check()
if not self.next == -1:
# If it finds a neighbour then make it the new current cell
# self.next.visited = True
current = self.next
elif self.next == -1 and len(visited) > 0:
# If it doesn't then look trough the path and backtrack trough it to find a possible neighbour
if len(visited) > 1:
del visited[-1]
current = visited[-1]
# If the last cell of the visited list is Cell 0 then remove it
elif len(visited) <= 1:
del visited[-1]
elif len(visited) <= 0:
# Stop the Algorithm
self.running = False
print('Done')
def draw(self):
DISPLAY.fill((255, 255, 255))
# Get the maze made by the algorithm and draw it on the screen
for i in range(0, len(grid)):
grid[i].draw()
pygame.display.update()
while self.display_running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.display_running = False
maze = Maze()
maze.init_cells()
maze.init_maze()
maze.draw()
I put some print methods in it for debugging purposes.
And am still a beginner in programming, I know it could probably be way cleaner or that some naming of methods could be better.
What I want to happen is that in def init_maze the maze blueprints gets written out and that in def draw the blueprint gets drawn on the screen.

Basket contact isn't restarting

I'm trying to make a game called Egg Catcher currently, for personal reasons (just for fun) and I'm a little bit stuck on my code. I want my egg to reset each time it either gets caught by the basket or it reaches the bottom, but it only checks for contact once and then it stops checking.. Please help.
import pygame
import random
caught_egg = False
a = 0
egg_radius = 15
x_egg = 0
y_egg = 5 + egg_radius
x_star = []
y_star = []
x_pos = 200
y_pos = 650
x_speed = 5
x_size = 100
y_size = 70
red = [255, 0, 0]
white = [255, 255, 255]
black = [0,0,0]
yellow = [255, 255, 0]
cyan = [0, 255, 255]
magenta = [255, 0, 255]
beige = [245,245,220]
wheat = [245,222,179]
egg_color_choices = [beige,wheat]
WINDOW_HEIGHT = 800
WINDOW_WIDTH = 500
pygame.init() # initializes the graphics module
window = pygame.display.set_mode((WINDOW_WIDTH,WINDOW_HEIGHT)) # define window size
pygame.display.set_caption('Egg Catcher') # title of program that
# appears on window
# frame
def InitSky(amount):
for i in range (0, amount):
x_star.append(random.randint(2, 495))
y_star.append(random.randint(2, 795))
def DrawSky(amount):
for i in range(0, amount):
pygame.draw.circle(window, white, (x_star[i], y_star[i]), 2, )
y_star[i] = y_star[i] + 1
if y_star[i] > WINDOW_HEIGHT:
y_star[i] = 0
def InitEgg():
x_egg = random.randint(1 + egg_radius, WINDOW_WIDTH - egg_radius)
return(x_egg)
def EggColor():
egg_color = random.choice(egg_color_choices)
return(egg_color)
def DrawEgg():
pygame.draw.circle(window, egg_color, (x_egg, y_egg), egg_radius,)
x_egg = InitEgg()
egg_color = EggColor()
# your code that draws to the window goes here
clock = pygame.time.Clock() # used to track time within the game (FPS)
quit = False
pygame.key.set_repeat(1)
while not quit: # main program loop
for event in pygame.event.get(): # check if there were any events
if event.type == pygame.QUIT: # check if user clicked the upper
quit = True # right quit button
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
x_pos = x_pos + x_speed
if event.key == pygame.K_LEFT:
x_pos = x_pos - x_speed
if x_pos <= 0:
x_pos = x_pos + x_speed
if x_pos + x_size >= 500:
x_pos = x_pos - x_speed
if event.key == pygame.K_KP_MINUS:
x_speed = x_speed - 1
if event.key == pygame.K_KP_PLUS:
x_speed = x_speed + 1
if x_speed >= 8:
x_speed = x_speed - 1
if x_speed <= 4:
x_speed = x_speed + 1
window.fill(black)
InitSky(500)
DrawSky(500)
caught_egg = False
if caught_egg == False:
DrawEgg()
if y_egg - egg_radius <= WINDOW_HEIGHT and caught_egg == False:
y_egg = y_egg + 3
else:
y_egg = 0
x_egg = InitEgg()
if x_egg + egg_radius > x_pos and x_egg + egg_radius < x_pos + x_size and y_egg - egg_radius == y_pos:
caught_egg = True
y_egg = 0
x_egg = InitEgg()
print(y_egg)
pygame.draw.rect(window, magenta, (x_pos, y_pos, x_size, y_size))
pygame.display.update() # refresh your display
clock.tick(60) # wait a certain amount of time that
# ensures a frame rate of 60 fps
pygame.quit() # shutdown module
It's because of this condition: y_egg - egg_radius == y_pos. You start from 20 the first time (5 + egg_radius) so when you hit 665 that condition triggers. But then you reset y_egg to 0 instead of 20 so you never align on the exact condition again.
You could just replace the two y_egg = 0 resets by y_egg = 5 + egg_radius, but a better fix would be to detect if the egg geometry is contained in the bucket in the y-dimension as you do for the x:
if x_egg + egg_radius > x_pos and \
x_egg + egg_radius < x_pos + x_size and \
y_egg - egg_radius >= y_pos and \
y_egg + egg_radius <= y_pos + y_size:
caught_egg = True
y_egg = 0
x_egg = InitEgg()
Actually your x logic is only checking if the right edge is inside the bucket but I'll leave that for you to fix.

Resources