OOP GUI Error: main.lua:4: attempt to index local (a boolean value)... Issue with modules - oop

Today, I was messing around with trying to make a gui class for game I'd like to start making in LOVE2D. I decided to try and use OOP to make creating new menus easier in the future. The OOP works great until I try and put it into it's own module, where it gives me the error above. I've double and triple checked my code against similar code and I can't find the problem. I've also looked it up and there are similar threads, but nothing that helps my problem. Here is the relevant code...
From the main.lua
local gui = {
x = 0, y = 0,
width = 0, height = 0,
popupSpeed = 300,
active = false,
color = {red = 0, blue = 0, green = 0, alpha = 0},
menuType = "",
--buttons = require "Game/buttons"
}
And from the gui.lua...
local newGUI = require "Game/gui"
local menus = {
playerInv = newGUI.new()
}
function love.load()
menus.playerInv:createDropDown("right" , _, 30, 100, love.graphics.getHeight() - 60, 50, 128, 50, 255)
end
function gui.new()
newMenu = {}
for k, v in pairs(gui) do
newMenu[k] = v
end
return newMenu
end
function gui:createDropDown(direction, x, y, width, height, red, blue, green, alpha)
self.red = red
self.blue = blue
self.green = green
self.alpha = alpha
if direction == "right" then
self.x = love.graphics.getWidth() - width
self.y = y
self.width = width
self.height = height
self.menuType = "rightDropDown"
elseif direction == "left" then
self.x = 0
self.y = y
self.widthMax = width
self.height = height
self.menuType = "leftDropDown"
elseif direction == "down" then
self.x = x
self.y = y
self.width = width
self.heightMax = height
self.menuType = "regDropDown"
end
end
function gui:drawGui()
if self.active == true then
love.graphics.setColor(self.red, self.blue, self.green, self.alpha)
love.graphics.rectangle("fill", self.x, self.y, self.width, self.height, 10, 10, 6)
end
end

I'm assuming the first snippet is Game/gui and that the second part is main.lua, if this is so, You are attempting to call .new() function which is clearly absent on your Game/gui file. You need to move all of gui's functions to it's own file as well, this includes gui.new(), gui:createDropDown and gui:drawGui() last but not least, you have to return gui at the end of it's own file.
Your main file should end up somewhat like this:
local newGUI = require "Game/gui"
local menus = {
playerInv = newGUI.new()
}
function love.load()
menus.playerInv:createDropDown("right" , _, 30, 100, love.graphics.getHeight() - 60, 50, 128, 50, 255)
end
and Game/gui somewhat like this:
local gui = {} -- With all the stuff inside
function gui.new()
-- With all the stuff it had inside
end
function gui:createDropDown()
-- With all the stuff it had inside
end
function gui:drawGui()
-- With all the stuff it had inside
end
return gui
You see, you forgot to move its functions to its own file, and return gui itself. Don't forget to replace what i omitted on Game/gui!

Related

How to draw rectangle in this embedded window in PyQt5?

I make this GUI in python:
Note: Chinese-->English: 导入视频-->load video, 框选屏幕-->The ROI screen, 框选完成-->set ROI.
I use this open_video function to import video from a directory, and get the first frame from video to display in right screen in the above picture.
def open_video(self):
self.video_name = QFileDialog.getOpenFileName(self, '选择视频', r'G:\dataset', '*.mp4')
print(self.video_name[0])
self.cap = cv2.VideoCapture(self.video_name[0])
ret, self.first_frame = self.cap.read()
first_frame = cv2.cvtColor(self.first_frame, cv2.COLOR_BGR2RGB)
first_frame = cv2.resize(first_frame, (self.rpn_width, self.rpn_height))
self.rpn_window.setPixmap(QPixmap.fromImage(QImage(first_frame.data,
first_frame.shape[1], first_frame.shape[0],
QImage.Format_RGB888)))
Also, I write a function to select ROI from the first frame first_frame.
...
button2.clicked.connect(self.setROI_video)
...
def setROI_video(self):
self.rect = draw_rectangle(self.first_frame, self.rpn_width, self.rpn_height)
print(self.rect)
def draw_rectangle(first_frame, width, height):
window_name = "Select ROI, press 'q' to quit"
cv2.namedWindow(window_name)
color = (0, 0, 0) # black
start_point = (0, 0) # (xs, ys)
end_point = (0, 0) # (xe, ye)
thickness = 4
is_down = False # flag to check if left button was pressed before mouse move
first_frame = cv2.resize(first_frame, (width, height))
param = [first_frame, color, window_name, start_point, end_point, is_down, thickness]
cv2.setMouseCallback(window_name, mouse_callback, param)
cv2.imshow(window_name, first_frame)
while True:
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cv2.destroyAllWindows()
x1 = param[3][0]
y1 = param[3][1]
x2 = param[4][0]
y2 = param[4][1]
return [min(x1, x2), min(y1, y2), abs(x2 - x1), abs(y2 - y1)]
def mouse_callback(event, x, y, flags, param):
img = param[0].copy()
if event == cv2.EVENT_LBUTTONDOWN:
param[3] = (x, y)
param[5] = True
if event == cv2.EVENT_MOUSEMOVE:
if param[5]:
cv2.rectangle(img, param[3], (x, y), param[1], param[6])
if event == cv2.EVENT_LBUTTONUP:
param[4] = (x, y)
cv2.rectangle(img, param[3], param[4], param[1], param[6])
param[5] = False
if param[5]:
cv2.imshow(param[2], img)
But it will jump a new window from the QMainWindow, like this:
The question is :
How to select ROI from the embedded screen instead of jumping window. I want to draw rectangle from the embedded QLabel.
Thanks in advance! And I need your help please!

My code cant find a function in my module script Roblox

I'm writing a 2D game engine in Roblox for fun, but I have run into an issue.
It seems my code cant find the function I'm referencing.
My output says:
Players.SpookyDervish.PlayerGui.SpookyEngine.SpookyEngine:31: attempt to call a nil value
I have 3 module scripts and a main script.
Here is my explorer window:
The main script:
local gui = script.Parent
local spookyEngine = require(gui:WaitForChild("SpookyEngine"))
spookyEngine.Init()
spookyEngine:CreateObject("TestObject", Vector2.new(0, 0), Vector2.new(50, 50), "rbxassetid://183598555", Color3.fromRGB(85, 170, 255))
wait(2)
spookyEngine:Transform("test", Vector2.new(50, 50), Vector2.new(50, 50), 0)
My SpookyEngine module:
local object = require(script:WaitForChild("Object"))
local input = require(script:WaitForChild("Input"))
local gui = script.Parent
local spookyEngine = {}
function spookyEngine.Init()
spookyEngine.screen = Instance.new("Frame", gui)
spookyEngine.screen.Name = "Screen"
spookyEngine.screen.Position = UDim2.new(0.5, 0, 0.5, 0)
spookyEngine.screen.Size = UDim2.new(1.25, 0, 1.25, 0)
spookyEngine.screen.AnchorPoint = Vector2.new(0.5, 0.5)
spookyEngine.screen.BackgroundColor3 = Color3.fromRGB(0, 0, 0)
spookyEngine.screen.BorderSizePixel = 0
spookyEngine.screen.BorderColor3 = Color3.fromRGB(0, 0, 0)
object.Init()
spookyEngine.objects = object.objects
game.StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType.All, false)
print("INFO: Initialized SpookyEngine!")
end
function spookyEngine:CreateObject(name, pos, size, sprite, colour)
object.New(name, pos, size, sprite, colour)
end
function spookyEngine:Transform(object, pos, size, rotation)
object:Transform(nil, nil, nil, nil)
end
return spookyEngine
My object module:
local spookyEngine = script.Parent
local gui = spookyEngine.Parent
local Object = {}
Object.__index = Object
function Object.Init()
local Objects = Instance.new("Folder", gui.Screen)
Objects.Name = "Objects"
Object.objects = Objects
end
function Object.New(name, pos, size, sprite, colour)
local newObject = {}
setmetatable(newObject, Object)
local position = UDim2.new(0.5, pos.X, 0.5, pos.Y)
local objectSize = UDim2.new(0, size.X, 0, size.Y)
local newObjectInstance = Instance.new("Frame", Object.objects)
newObjectInstance.Name = name
newObjectInstance.Position = position
newObjectInstance.Size = objectSize
newObjectInstance.BackgroundColor3 = colour
newObjectInstance.AnchorPoint = Vector2.new(0.5, 0.5)
newObjectInstance.BorderSizePixel = 0
if sprite ~= nil then
local objectSprite = Instance.new("ImageLabel", newObjectInstance)
objectSprite.Size = UDim2.new(1, 0, 1, 0)
objectSprite.Name = "Sprite"
objectSprite.Image = sprite
objectSprite.BackgroundTransparency = 1
objectSprite.BackgroundColor3 = colour
newObjectInstance.BackgroundTransparency = 1
end
newObject.Name = name
newObject.Position = position
newObject.Size = objectSize
newObject.Sprite = sprite
newObject.Colour = colour
newObject.Instance = newObjectInstance
return newObject
end
function Object:Transform(object, pos, size, rotation)
object = tostring(object)
if Object.objects:FindFirstChild(object) then
else
warn("ERROR: Cant find object with name: '"..object.."'")
end
end
return Object
Any help would be appreciated!
Your error is pointing at this line :
function spookyEngine:Transform(object, pos, size, rotation)
object:Transform(nil, nil, nil, nil)
end
which is called by...
spookyEngine:Transform("test", Vector2.new(50, 50), Vector2.new(50, 50), 0)
Because you have a function argument named object, it shadows the object local variable that you used to define your module. So the string that you pass in is what gets used. So you are effectively trying to execute
string.Transform("test", nil, nil, nil, nil)
The lua string library does not have a function called Transform, so when you try to index the function, it comes back as nil. That is why you get the error attempt to call a nil value.
Since you intended to use the Object:Transform function from your module, the easy fix is to rename the function argument to avoid the name collision. Try something like :
function spookyEngine:Transform(obj, pos, size, rotation)
object:Transform(obj, pos, size, rotation)
end

I'm making a code with pygame in oop and I'm having trouble making one of my methods work

Basically, I am making a code that uses oop and pygame together. It draws 4 rectangles in the corners of the screen and gives each rectangle a name. I have to ask the user the name of one of the rectangles and change that rectangles color randomly.
Code:
import random
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((500,500))
pygame.display.set_caption("BOOGABOOGA")
blue = (0,0,255)
red = (255,0,0)
green = (0,255,0)
white = (255,255,255)
random = [blue,red,green,white]
class Rectangle:
def __init__(self,name,color,x,y,width,height,thickness):
self.name = name
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.thickness = thickness
def coolboymethoddraw(self):
pygame.draw.rect(screen,self.color,(self.x,self.y,self.width,self.height),self.thickness)
recty1 = Rectangle("YOYO",blue,50,50,50,50,0)
recty2 = Rectangle("BABYBOOGA",blue,450,450,50,50,0)
recty3 = Rectangle("ChotaBEAM",blue,0,450,50,50,0)
recty4 = Rectangle("CHOTAJAGGU",blue,450,0,50,50,0)
jaggu = [recty1,recty2,recty3,recty4]
recty3.coolboymethoddraw()
recty1.coolboymethoddraw()
recty4.coolboymethoddraw()
recty2.coolboymethoddraw()
def change_color(self):
print("Give me the name of 1 of the 4 rectangles!")
x = input()
for chota in jaggu:
if x == chota.name:
l = random.choice(random)
chota.color = l
recty1.change_color()
recty2.changecolor()
recty3.change_color()
recty4.change_color()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
pygame.display.update()
I would appreciate an answer and why it wasn't working. Thanks!
First of all move your method change_color inside the class Rectangle.
class Rectangle:
def __init__(self,name,color,x,y,width,height,thickness):
self.name = name
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.thickness = thickness
def coolboymethoddraw(self):
pygame.draw.rect(screen,self.color,(self.x,self.y,self.width,self.height),self.thickness)
def change_color(self):
print("Give me the name of 1 of the 4 rectangles!")
x = input()
for chota in jaggu:
if x == chota.name:
l = random.choice(random)
chota.color = l
Then you need to move the draw methods inside the main loop, otherwise the rectangles will not be drawn.
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
recty3.coolboymethoddraw()
recty1.coolboymethoddraw()
recty4.coolboymethoddraw()
recty2.coolboymethoddraw()
pygame.display.update()
Dont name your list of colors random because you import a package called random. Name the list something like colors_list
You dont need to call the change_color method for all 4 rectangles because inside of this method you go through a list of your 4 rectangles already.
There is also a problem in the change_color method. You need to call the method inside the main loop as well, but because of the print statement and the input it will end in an ifinite loop.

Can this PyGame code run 60fps for >40 critters?

In my other question, some of the posters asked to see the code and suggested I make a new question. As requested, here is most of the code I'm using. I've removed the Vector class, simply because it's a lot of code. It's well-understood math that I got from someone else (https://gist.github.com/mcleonard/5351452), and cProfile didn't have much to say about any of the functions there. I've provided a link in the code, if you want to make this run-able.
This code should run, if you paste the the vector class where indicated in the code.
The problem is, once I get above 20 critters, the framerate drops rapidly from 60fps to 11fps around 50 critters.
Please excuse the spaghetti-code. Much of this is diagnostic kludging or pre-code that I intend to either remove, or turn into a behavior (instead of a hard-coded value).
This app is basically composed of 4 objects.
A Vector object provides abstracted vector operations.
A Heat Block is able to track it's own "heat" level, increase it and decrease it. It can also draw itself.
A Heat Map is composed of heat blocks which are tiled across the screen. When given coordinates, it can choose the block that those coordinates fall within.
A Critter has many features that make it able to wander around the screen, bump off of the walls and other critters, choose a new random direction, and die.
The main loop iterates through each critter in the "flock" and updates its "condition" (whether or not it's "dying"), its location, its orientation, and the heat block on which it is currently standing. The loop also iterates over each heat block to let it "cool down."
Then the main loop asks the heat map to draw itself, and then each critter in the flock to draw itself.
import pygame
from pygame import gfxdraw
import pygame.locals
import os
import math
import random
import time
(I got a nice vector class from someone else. It's large, and mostly likely not the problem.)
(INSERT CONTENTS OF VECTOR.PY FROM https://gist.github.com/mcleonard/5351452 HERE)
pygame.init()
#some global constants
BLUE = (0, 0, 255)
WHITE = (255,255,255)
diagnostic = False
SPAWN_TIME = 1 #number of seconds between creating new critters
FLOCK_LIMIT = 30 #number of critters at which the flock begins being culled
GUIDs = [0] #list of guaranteed unique IDs for identifying each critter
# Set the position of the OS window
position = (30, 30)
os.environ['SDL_VIDEO_WINDOW_POS'] = str(position[0]) + "," + str(position[1])
# Set the position, width and height of the screen [width, height]
size_x = 1000
size_y = 500
size = (size_x, size_y)
FRAMERATE = 60
SECS_FOR_DYING = 1
screen = pygame.display.set_mode(size)
screen.set_alpha(None)
pygame.display.set_caption("My Game")
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
def random_float(lower, upper):
num = random.randint(lower*1000, upper*1000)
return num/1000
def new_GUID():
num = GUIDs[-1]
num = num + 1
while num in GUIDs:
num += 1
GUIDs.append(num)
return num
class HeatBlock:
def __init__(self,_tlx,_tly,h,w):
self.tlx = int(_tlx)
self.tly = int(_tly)
self.height = int(h)+1
self.width = int(w)
self.heat = 255.0
self.registered = False
def register_tresspasser(self):
self.registered = True
self.heat = max(self.heat - 1, 0)
def cool_down(self):
if not self.registered:
self.heat = min(self.heat + 0.1, 255)
self.registered = False
def hb_draw_self(self):
screen.fill((255,int(self.heat),int(self.heat)), [self.tlx, self.tly, self.width, self.height])
class HeatMap:
def __init__(self, _h, _v):
self.h_freq = _h #horizontal frequency
self.h_rez = size_x/self.h_freq #horizontal resolution
self.v_freq = _v #vertical frequency
self.v_rez = size_y/self.v_freq #vertical resolution
self.blocks = []
def make_map(self):
h_size = size_x/self.h_freq
v_size = size_y/self.v_freq
for h_count in range(0, self.h_freq):
TLx = h_count * h_size #TopLeft corner, x
col = []
for v_count in range(0, self.v_freq):
TLy = v_count * v_size #TopLeft corner, y
col.append(HeatBlock(TLx,TLy,v_size,h_size))
self.blocks.append(col)
def hm_draw_self(self):
for col in self.blocks:
for block in col:
block.cool_down()
block.hb_draw_self()
def register(self, x, y):
#convert the given coordinates of the trespasser into a col/row block index
col = max(int(math.floor(x / self.h_rez)),0)
row = max(int(math.floor(y / self.v_rez)),0)
self.blocks[col][row].register_tresspasser()
class Critter:
def __init__(self):
self.color = (random.randint(1, 200), random.randint(1, 200), random.randint(1, 200))
self.linear_speed = random_float(20, 100)
self.radius = int(round(10 * (100/self.linear_speed)))
self.angular_speed = random_float(0.1, 2)
self.x = int(random.randint(self.radius*2, size_x - (self.radius*2)))
self.y = int(random.randint(self.radius*2, size_y - (self.radius*2)))
self.orientation = Vector(0, 1).rotate(random.randint(-180, 180))
self.sensor = Vector(0, 20)
self.sensor_length = 20
self.new_orientation = self.orientation
self.draw_bounds = False
self.GUID = new_GUID()
self.condition = 0 #0 = alive, [1-fps] = dying, >fps = dead
self.delete_me = False
def c_draw_self(self):
#if we're alive and not dying, draw our normal self
if self.condition == 0:
#diagnostic
if self.draw_bounds:
pygame.gfxdraw.rectangle(screen, [int(self.x), int(self.y), 1, 1], BLUE)
temp = self.orientation * (self.linear_speed * 20)
pygame.gfxdraw.line(screen, int(self.x), int(self.y), int(self.x + temp[0]), int(self.y + temp[1]), BLUE)
#if there's a new orientation, match it gradually
temp = self.new_orientation * self.linear_speed
#draw my body
pygame.gfxdraw.aacircle(screen, int(self.x), int(self.y), self.radius, self.color)
#draw a line indicating my new direction
pygame.gfxdraw.line(screen, int(self.x), int(self.y), int(self.x + temp[0]), int(self.y + temp[1]), BLUE)
#draw my sensor (a line pointing forward)
self.sensor = self.orientation.normalize() * self.sensor_length
pygame.gfxdraw.line(screen, int(self.x), int(self.y), int(self.x + self.sensor[0]), int(self.y + self.sensor[1]), BLUE)
#otherwise we're dying, draw our dying animation
elif 1 <= self.condition <= FRAMERATE*SECS_FOR_DYING:
#draw some lines in a spinningi circle
for num in range(0,10):
line = Vector(0, 1).rotate((num*(360/10))+(self.condition*23))
line = line*self.radius
pygame.gfxdraw.line(screen, int(self.x), int(self.y), int(self.x+line[0]), int(self.y+line[1]), self.color)
def print_self(self):
#diagnostic
print("==============")
print("radius:", self.radius)
print("color:", self.color)
print("linear_speed:", self.linear_speed)
print("angular_speed:", self.angular_speed)
print("x:", self.x)
print("y:", int(self.y))
print("orientation:", self.orientation)
def avoid_others(self, _flock):
for _critter in _flock:
#if the critter isn't ME...
if _critter.GUID is not self.GUID and _critter.condition == 0:
#and it's touching me...
if self.x - _critter.x <= self.radius + _critter.radius:
me = Vector(self.x, int(self.y))
other_guy = Vector(_critter.x, _critter.y)
distance = me - other_guy
#give me new orientation that's away from the other guy
if distance.norm() <= ((self.radius) + (_critter.radius)):
new_direction = me - other_guy
self.orientation = self.new_orientation = new_direction.normalize()
def update_location(self, elapsed):
boundary = '?'
while boundary != 'X':
boundary = self.out_of_bounds()
if boundary == 'N':
self.orientation = self.new_orientation = Vector(0, 1).rotate(random.randint(-20, 20))
self.y = (self.radius) + 2
elif boundary == 'S':
self.orientation = self.new_orientation = Vector(0,-1).rotate(random.randint(-20, 20))
self.y = (size_y - (self.radius)) - 2
elif boundary == 'E':
self.orientation = self.new_orientation = Vector(-1,0).rotate(random.randint(-20, 20))
self.x = (size_x - (self.radius)) - 2
elif boundary == 'W':
self.orientation = self.new_orientation = Vector(1,0).rotate(random.randint(-20, 20))
self.x = (self.radius) + 2
point = Vector(self.x, self.y)
self.x, self.y = (point + (self.orientation * (self.linear_speed*(elapsed/1000))))
boundary = self.out_of_bounds()
def update_orientation(self, elapsed):
#randomly choose a new direction, from time to time
if random.randint(0, 100) > 98:
self.choose_new_orientation()
difference = self.orientation.argument() - self.new_orientation.argument()
self.orientation = self.orientation.rotate((difference * (self.angular_speed*(elapsed/1000))))
def still_alive(self, elapsed):
return_value = True #I am still alive
if self.condition == 0:
return_value = True
elif self.condition <= FRAMERATE*SECS_FOR_DYING:
self.condition = self.condition + (elapsed/17)
return_value = True
if self.condition > FRAMERATE*SECS_FOR_DYING:
return_value = False
return return_value
def choose_new_orientation(self):
if self.new_orientation:
if (self.orientation.argument() - self.new_orientation.argument()) < 5:
rotation = random.randint(-300, 300)
self.new_orientation = self.orientation.rotate(rotation)
def out_of_bounds(self):
if self.x >= (size_x - (self.radius)):
return 'E'
elif self.y >= (size_y - (self.radius)):
return 'S'
elif self.x <= (0 + (self.radius)):
return 'W'
elif self.y <= (0 + (self.radius)):
return 'N'
else:
return 'X'
# -------- Main Program Loop -----------
# generate critters
flock = [Critter()]
# generate heat map
heatMap = HeatMap(60, 40)
heatMap.make_map()
# set some settings
last_spawn = time.clock()
run_time = time.perf_counter()
frame_count = 0
max_time = 0
ms_elapsed = 1
avg_fps = [1]
# Loop until the user clicks the close button.
done = False
while not done:
# --- Main event loop only processes one event
frame_count = frame_count + 1
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# --- Game logic should go here
#check if it's time to make another critter
if time.clock() - last_spawn > SPAWN_TIME:
flock.append(Critter())
last_spawn = time.clock()
if len(flock) >= FLOCK_LIMIT:
#if we're over the flock limit, cull the herd
counter = FLOCK_LIMIT
for critter in flock[0:len(flock)-FLOCK_LIMIT]:
#this code allows a critter to be "dying" for a while, to play an animation
if critter.condition == 0:
critter.condition = 1
elif not critter.still_alive(ms_elapsed):
critter.delete_me = True
counter = 0
#delete all the critters that have finished dying
while counter < len(flock):
if flock[counter].delete_me:
del flock[counter]
else:
counter = counter+1
#----loop on all critters once, doing all functions for each critter
for critter in flock:
if critter.condition == 0:
critter.avoid_others(flock)
if critter.condition == 0:
heatMap.register(critter.x, critter.y)
critter.update_location(ms_elapsed)
critter.update_orientation(ms_elapsed)
if diagnostic:
critter.print_self()
#----alternately, loop for each function. Speed seems to be similar either way
#for critter in flock:
# if critter.condition == 0:
# critter.update_location(ms_elapsed)
#for critter in flock:
# if critter.condition == 0:
# critter.update_orientation(ms_elapsed)
# --- Screen-clearing code goes here
# Here, we clear the screen to white. Don't put other drawing commands
screen.fill(WHITE)
# --- Drawing code should go here
#draw the heat_map
heatMap.hm_draw_self()
for critter in flock:
critter.c_draw_self()
#draw the framerate
myfont = pygame.font.SysFont("monospace", 15)
#average the framerate over 60 frames
temp = sum(avg_fps)/float(len(avg_fps))
text = str(round(((1/temp)*1000),0))+"FPS | "+str(len(flock))+" Critters"
label = myfont.render(text, 1, (0, 0, 0))
screen.blit(label, (5, 5))
# --- Go ahead and update the screen with what we've drawn.
pygame.display.update()
# --- Limit to 60 frames per second
#only run for 30 seconds
if time.perf_counter()-run_time >= 30:
done = True
#limit to 60fps
#add this frame's time to the list
avg_fps.append(ms_elapsed)
#remove any old frames
while len(avg_fps) > 60:
del avg_fps[0]
ms_elapsed = clock.tick(FRAMERATE)
#track longest frame
if ms_elapsed > max_time:
max_time = ms_elapsed
#print some stats once the program is finished
print("Count:", frame_count)
print("Max time since last flip:", str(max_time)+"ms")
print("Total Time:", str(int(time.perf_counter()-run_time))+"s")
print("Average time for a flip:", str(int(((time.perf_counter()-run_time)/frame_count)*1000))+"ms")
# Close the window and quit.
pygame.quit()
One thing you can already do to improve the performance is to use pygame.math.Vector2 instead of your Vector class, because it's implemented in C and therefore faster. Before I switched to pygame's vector class, I could have ~50 critters on the screen before the frame rate dropped below 60, and after the change up to ~100.
pygame.math.Vector2 doesn't have that argument method, so you need to extract it from the class and turn it into a function:
def argument(vec):
""" Returns the argument of the vector, the angle clockwise from +y."""
arg_in_rad = math.acos(Vector(0,1)*vec/vec.length())
arg_in_deg = math.degrees(arg_in_rad)
if vec.x < 0:
return 360 - arg_in_deg
else:
return arg_in_deg
And change .norm() to .length() everywhere in the program.
Also, define the font object (myfont) before the while loop. That's only a minor improvement, but every frame counts.
Another change that made a significant improvement was to streamline my collision-detection algorithm.
Formerly, I had been looping through every critter in the flock, and measuring the distance between it and every other critter in the flock. If that distance was small enough, I do something. That's n^2 checks, which is not awesome.
I'd thought about using a quadtree, but it didn't seem efficient to rebalance the whole tree every frame, because it will change every time a critter moves.
Well, I finally actually tried it, and it turns out that building a brand-new quadtree at the beginning of each frame is actually plenty fast. Once I have the tree, I pass it to the avoidance function where I just extract an intersection of any of the critters in that tree within a bounding box I care about. Then I just iterate on those neighbors to measure distances and update directions and whatnot.
Now I'm up to 150 or so critters before I start dropping frames (up from 40).
So the moral of the story is, trust evidence instead of intuition.

R EVMIX convert pdf to uniform marginals

I'm trying to convert a distribution into a pseudo-uniform distribution. Using the spd R package, it is easy and it works as expected.
library(spd)
x <- c(rnorm(100,-1,0.7),rnorm(100,3,1))
fit<-spdfit(x,upper=0.9,lower=0.1,tailfit="GPD", kernelfit="epanech")
uniformX = pspd(x,fit)
I want to generalize extreme value modeling to include threshold uncertainity. So I used the evmix package.
library(evmix)
x <- c(rnorm(100,-1,0.7),rnorm(100,3,1))
fit = fgkg(x, phiul = FALSE, phiur = FALSE, std.err = FALSE)
pgkg(x,fit$lambda, fit$ul, fit$sigmaul, fit$xil, fit$phiul, fit$ur,
fit$sigmaur, fit$xir, fit$phiur)
Im messing up somewhere.
Please check out the help for pgkg function:
help(pgkg)
which gives the syntax:
pgkg(q, kerncentres, lambda = NULL, ul = as.vector(quantile(kerncentres,
0.1)), sigmaul = sqrt(6 * var(kerncentres))/pi, xil = 0, phiul = TRUE,
ur = as.vector(quantile(kerncentres, 0.9)), sigmaur = sqrt(6 *
var(kerncentres))/pi, xir = 0, phiur = TRUE, bw = NULL,
kernel = "gaussian", lower.tail = TRUE)
You have missed the kernel centres (the data), which is always needed for kernel density estimators. Here is the corrected code:
library(evmix)
x <- c(rnorm(100,-1,0.7),rnorm(100,3,1))
fit = fgkg(x, phiul = FALSE, phiur = FALSE, std.err = FALSE)
prob = pgkg(x, x, fit$lambda, fit$ul, fit$sigmaul, fit$xil, fit$phiul,
fit$ur, fit$sigmaur, fit$xir, fit$phiur)
hist(prob) % now uniform as expected