AutoIt: Find window under mouse pointer - autoit

I'm using AutoIt3 and I need a way for the user to select a window. The fastest method is, in my opinion, having them point to a window. So the question is, how do I see what window is under their mouse pointer?

I extrapolated this from some code I had laying around for selecting areas on the screen. This will just pop up the Window title thats under the mouse (hit Escape to exit the loop):
#include <WinAPI.au3>
#include <Misc.au3>
Func _WindowFromPoint($iX,$iY)
Local $stInt64,$aRet,$stPoint=DllStructCreate("long;long")
DllStructSetData($stPoint,1,$iX)
DllStructSetData($stPoint,2,$iY)
$stInt64=DllStructCreate("int64",DllStructGetPtr($stPoint))
$aRet=DllCall("user32.dll","hwnd","WindowFromPoint","int64",DllStructGetData($stInt64,1))
If #error Then Return SetError(2,#error,0)
If $aRet[0]=0 Then Return SetError(3,0,0)
Return $aRet[0]
EndFunc
Local $hControl, $hWin, $hOldWin, $aMousePos
$hOldWin = ""
While Not _IsPressed("1B")
$aMousePos = MouseGetPos()
$hControl=_WindowFromPoint($aMousePos[0],$aMousePos[1])
; Since _WindowFromPoint() can return 'sub' windows, or control handles, we should seek the owner window
$hWin=_WinAPI_GetAncestor($hControl,2)
If $hWin <> $hOldWin Then
TrayTip("Window Info","Window under mouse = " & WinGetTitle($hWin), 1)
$hOldWin = $hWin
EndIf
Sleep(10)
WEnd

Here's a complete example of a full screen GUI, displaying the actual screen and a border around the window that's topmost under the mouse pointer. This function is used to write the Title of the window to console.
#include <Misc.au3>
#include <Array.au3>
#include <GDIPlus.au3>
#include <ScreenCapture.au3>
#include <WindowsConstants.au3>
HotKeySet("{Esc}", "_Exit")
Func _Exit()
Exit 0
EndFunc
Global $xPosReminder, $yPosReminder
$dll = DllOpen("user32.dll")
$allWindows = WinList()
; exclude invisible windows from winlist
Dim $windows[1]
$windows[0] = 0
For $i = 1 to $allWindows[0][0]
; only fetches visible windows
If BitAnd(WinGetState($allWindows[$i][1]), 2) Then;AND $allWindows[$i][0] <> "" Then
ReDim $windows[$windows[UBound($windows) - 1] + 2]
$windows[UBound($windows) - 1] = $windows[UBound($windows) - 2] + 1
$windows[UBound($windows) - 2] = $allWindows[$i][1]
EndIf
Next
ReDim $windows[$windows[UBound($windows) - 1]]
_ArrayReverse($windows)
; capture screen without cursor
$pos = MouseGetPos()
MouseMove(#DesktopWidth, #DesktopHeight, 0)
$hBitmap = _ScreenCapture_Capture ("")
MouseMove($pos[0], $pos[1], 0)
; create and show new fullscreen gui
$hGUI = GUICreate("", #DesktopWidth, #DesktopHeight, 0, 0, $WS_POPUP)
GUISetState(#SW_SHOW)
; Initialize GDI+ library
_GDIPlus_StartUp()
$hImage = _GDIPlus_BitmapCreateFromHBITMAP ($hBitmap)
$hGraphics = _GDIPlus_GraphicsCreateFromHWND ($hGUI)
$hPen = _GDIPlus_PenCreate(0xFFFF0000, 3, 2)
$iX = _GDIPlus_ImageGetWidth($hImage)
$iY = _GDIPlus_ImageGetHeight($hImage)
_GDIPlus_GraphicsDrawImage($hGraphics, $hImage, 0, 0)
Global $oldWindow = 0
; Wait for Click
While True
If _IsPressed("01", $dll) Then ; left mouse button
$xPos = MouseGetPos(0)
$yPos = MouseGetPos(1)
ExitLoop
EndIf
If __MouseMoved() Then
; Erzeugt eine Kopie einer 24 bit Bitmap
$hClone = _GDIPlus_BitmapCloneArea($hImage, 0, 0, $iX, $iY, $GDIP_PXF24RGB)
$currentWindow = __GetWindowByMousePosition($windows, MouseGetPos(0), MouseGetPos(1))
If $currentWindow <> $oldWindow Then
$windowPosition = WinGetPos($currentWindow)
; reduce position and size to desktop space
$windowPosition[0] = _Iif($windowPosition[0] < 0, 0, $windowPosition[0])
$windowPosition[1] = _Iif($windowPosition[1] < 0, 0, $windowPosition[1])
$windowPosition[2] = _Iif($windowPosition[2] > #DesktopWidth, #DesktopWidth, $windowPosition[2])
$windowPosition[3] = _Iif($windowPosition[3] > #DesktopHeight, #DesktopHeight, $windowPosition[3])
_GDIPlus_GraphicsDrawImage($hGraphics, $hClone, 0, 0)
_GDIPlus_GraphicsDrawRect($hGraphics, $windowPosition[0], $windowPosition[1], $windowPosition[2], $windowPosition[3], $hPen)
$oldWindow = $currentWindow
EndIf
EndIf
Sleep(1)
WEnd
; Free Ressources
_GDIPlus_PenDispose($hPen)
_GDIPlus_BitmapDispose($hImage)
_GDIPlus_GraphicsDispose($hGraphics)
_WinAPI_DeleteObject($hBitmap)
_GDIPlus_ShutDown()
DllClose($dll)
GUISetState(#SW_HIDE)
Func __GetWindowByMousePosition($windows, $xPos, $yPos)
Local $currentWindow = 0
For $i = 0 to UBound($windows) - 1
$pos = WinGetPos($windows[$i])
If $xPos >= $pos[0] AND $xPos <= $pos[0] + $pos[2] AND $yPos >= $pos[1] AND $yPos <= $pos[1] + $pos[3] Then
$currentWindow = $windows[$i]
EndIf
Next
Return $currentWindow
EndFunc
Func __MouseMoved()
Local $actualPos = MouseGetPos()
If $xPosReminder <> $actualPos[0] OR $yPosReminder <> $actualPos[1] Then
$xPosReminder = $actualPos[0]
$yPosReminder = $actualPos[1]
Return True
Else
Return False
EndIf
EndFunc
ConsoleWrite(WinGetTitle(__GetWindowByMousePosition($windows, $xPos, $yPos)) & #CR)

Related

How to find a smallest value without trying all posibilities

I am trying to write a program (in Lua, but I guess this is more of a mathematical problem) that calculates the total distance between a set of numbers and there are two or three different possibilities for some of these numbers. 
For example a set of numbers is: 2, 5, 0, 1. The sum of distances in this case is 9. (5-2 + 5-0 + 1-0)
The first row with alternatives is: 5, -, 3, 2.
The second row with alternatives is: 3, -, -, 3
The combination between the two rows with the smallest sum of distances is: 5, 5, 3, 3 with a sum of distances of 2.
My first attempt was to write a program that tries all possible iterations, but with a set of about 40 numbers, there are so many possibilities that my computer crashed...
Here is the code for that version, it first creates all the different possibilities and then calculates the differences and places them in column 0. Afterwards I can find the smallest value easily and see also the combination of numbers which results in that value.
local table1 = {2, 5, 0 ,1}
local table2 = {5, nil, 3, 2}
local imax = 1
local solution = {}
local answer = table1[1]
for x = 1,#table1 do
solution[x]={}
for i= 1, (2^imax)/2 do
solution[x][i] = table1[x]
end
if table2[x] ~= nil then -- there is an alternative number
for y = 1, x-1 do -- copy all the previous table entries except the last one
for j = ((2^imax)/2)+1, 2^imax do -- the number of new rows increases exponentially
solution[y][j] = solution[y][j-imax]
end
end
for j = ((2^imax)/2)+1, 2^imax do -- create the new table entry with the alternative number
solution[x][j] = table2[x]
end
imax = imax + 1 -- this number is to remind how many alternative numbers where found
end
end
solution[0]={}
for x = 1, #table1 do
for i = 1, (2^imax)/2 do
if x < #table1 then answer = math.sqrt((solution[x+1][i]-solution[x][i])^2) else answer = 0 end
if solution[0][i] == nil then solution[0][i] = answer else solution[0][i] = solution[0][i] + answer end
end
end
After reading about dynamic programming, I wrote a new version of this program. It calculates the smallest sum of differences, but I also want to know the path (the combination of numbers) to that sum... Still work to do...
local table1 = {2, 5, 0 ,1}
local table2 = {5, nil, 3, 2}
local solution = {}
local smallestsolution = {}
solution[1]={}
solution[2]={}
solution[3]={}
solution[4]={}
for i = 1, (#table1-1) do
solution[1][i] = math.sqrt((table1[i+1]-table1[i])^2)
if table2[i] ~= nil then solution[2][i] = math.sqrt((table1[i+1]-table2[i])^2) end
if table2[i+1] ~= nil then solution[3][i] = math.sqrt((table2[i+1]-table1[i])^2) end
if table2[i] ~= nil and table2[i+1] ~= nil then solution[4][i] = math.sqrt((table2[i+1]-table2[i])^2) end
end
for i = 1, (#table1-1) do
smallestsolution[i]=100000
for j = 1, 4 do
if solution[j][i] ~= nil and solution[j][i] < smallestsolution[i] then smallestsolution[i]=solution[j][i] end
end
end
local smallestsum = 0
for i = 1, (#table1-1) do
smallestsum = smallestsum + smallestsolution[i]
end
Thanks,
Emile
I managed to solve it myself! The hint to dynamic programming by #EgorSkriptunoff did the trick!
local table1 = {2, 5, 0 ,1}
local table2 = {5, nil, 3, 2}
local solution = {}
local smallestsolution = {}
solution[1]={}
solution[2]={}
solution[3]={}
solution[4]={}
local path = {}
local temp = {}
for i = 1, (#table1-1) do
solution[1][i] = math.sqrt((table1[i+1]-table1[i])^2)
if table2[i] ~= nil then solution[2][i] = math.sqrt((table1[i+1]-table2[i])^2) end
if table2[i+1] ~= nil then solution[3][i] = math.sqrt((table2[i+1]-table1[i])^2) end
if table2[i] ~= nil and table2[i+1] ~= nil then solution[4][i] = math.sqrt((table2[i+1]-table2[i])^2) end
end
for i = 1, (#table1-1) do
smallestsolution[i]=100000
temp[i] = 0
for j = 1, 4 do
if solution[j][i] ~= nil and solution[j][i] < smallestsolution[i] then smallestsolution[i]=solution[j][i] temp[i] = j end
end
end
local smallestsum = 0
for i = 1, (#table1-1) do
smallestsum = smallestsum + smallestsolution[i]
end
for i = 1, (#table1) do -- find the path belonging to the smallest sum of differences
if temp[i] == 1 then path[i] = table1[i] end
if temp[i] == 2 then path[i] = table2[i] end
if temp[i] == 3 then path[i] = table1[i] end
if temp[i] == 4 then path[i] = table2[i] end
if i == (#table1) then
if temp[i-1] == 1 then path[i] = table1[i] end
if temp[i-1] == 2 then path[i] = table1[i] end
if temp[i-1] == 3 then path[i] = table2[i] end
if temp[i-1] == 4 then path[i] = table2[i] end
end
end

I have written a path tracer using julia programming language but i think it is slow

I have changed my post and posted the whole of my code! Could someone tell me how can I optimize it?
import Base: *, +, -, /, ^
using Images
const Π = convert(Float64, π)
#define vector
mutable struct Vec3
x::Float64
y::Float64
z::Float64
end
function +(u::Vec3, v::Vec3)
Vec3(u.x+v.x, u.y+v.y, u.z+v.z)
end
function -(u::Vec3, v::Vec3)
Vec3(u.x-v.x, u.y-v.y, u.z-v.z)
end
function /(u::Vec3, v::Float64)
Vec3(u.x/v, u.y/v, u.z/v)
end
function *(u, v::Vec3)
if typeof(u) == Float64
Vec3(u*v.x, u*v.y, u*v.z)
elseif typeof(u) == Vec3
Vec3(u.x*v.x, u.y*v.y, u.z*v.z)
end
end
function ^(u::Vec3, v::Float64)
Vec3(u.x^v, u.y^v, u.z^v)
end
function dot(u::Vec3, v::Vec3)
u.x*v.x + u.y*v.y + u.z*v.z
end
function normalize(u::Vec3)
u/sqrt(dot(u,u))
end
function cross(u::Vec3, v::Vec3)
Vec3(u.y*v.z - v.y*u.z, u.z*v.x - v.z*u.x, u.x*v.y - v.x*u.y)
end
function gamma(u::Vec3)
Vec3(u.x^(1/2.2), u.y^(1/2.2), u.z^(1/2.2))
end
function clamp(u::Vec3)
u.x = u.x <= 1 ? u.x : 1
u.y = u.y <= 1 ? u.y : 1
u.z = u.z <= 1 ? u.z : 1
u
end
#define ray
struct Ray
s::Vec3
d::Vec3
end
#define planes
struct xyRect
z; x1; x2; y1; y2::Float64
normal; emittance; reflectance::Vec3
isLight::Bool
end
struct xzRect
y; x1; x2; z1; z2::Float64
normal; emittance; reflectance::Vec3
isLight::Bool
end
struct yzRect
x; y1; y2; z1; z2::Float64
normal; emittance; reflectance::Vec3
isLight::Bool
end
#define sphere
mutable struct Sphere
radius::Float64
center; normal; emittance; reflectance::Vec3
isLight::Bool
end
#define empty object
struct Empty
normal; emittance; reflectance::Vec3
end
#define surfaces
Surfaces = Union{xyRect, xzRect, yzRect, Sphere}
#define intersection function
function intersect(surface::Surfaces, ray::Ray)
if typeof(surface) == xyRect
t = (surface.z - ray.s.z)/ray.d.z
if surface.x1 < ray.s.x + t*ray.d.x < surface.x2 && surface.y1 < ray.s.y + t*ray.d.y < surface.y2 && t > 0
t
else
Inf
end
elseif typeof(surface) == xzRect
t = (surface.y - ray.s.y)/ray.d.y
if surface.x1 < ray.s.x + t*ray.d.x < surface.x2 && surface.z1 < ray.s.z + t*ray.d.z < surface.z2 && t > 0
t
else
Inf
end
elseif typeof(surface) == yzRect
t = (surface.x - ray.s.x)/ray.d.x
if surface.y1 < ray.s.y + t*ray.d.y < surface.y2 && surface.z1 < ray.s.z + t*ray.d.z < surface.z2 && t > 0
t
else
Inf
end
elseif typeof(surface) == Sphere
a = dot(ray.d, ray.d)
b = 2dot(ray.d, ray.s - surface.center)
c = dot(ray.s - surface.center, ray.s - surface.center) - surface.radius*surface.radius
Δ = b*b - 4*a*c
if Δ > 0
Δ = sqrt(Δ)
t1 = 0.5(-b-Δ)/a
t2 = 0.5(-b+Δ)/a
if t1 > 0
surface.normal = normalize(ray.s + t1*ray.d - surface.center)
t1
elseif t2 > 0
surface.normal = normalize(ray.s + t2*ray.d - surface.center)
t2
else
Inf
end
else
Inf
end
end
end
#define nearest function
function nearest(surfaces::Array{Surfaces, 1}, ray::Ray, tMin::Float64)
hitSurface = Empty(Vec3(0,0,0), Vec3(0,0,0), Vec3(0,0,0))
for surface in surfaces
t = intersect(surface, ray)
if t < tMin
tMin = t
hitSurface = surface
end
end
tMin, hitSurface
end
#cosine weighted sampling of hemisphere
function hemiRand(n::Vec3)
ξ1 = rand()
ξ2 = rand()
x = cos(2π*ξ2)*sqrt(ξ1)
y = sin(2π*ξ2)*sqrt(ξ1)
z = sqrt(1-ξ1)
r = normalize(Vec3(2rand()-1, 2rand()-1, 2rand()-1))
b = cross(n,r)
t = cross(n,b)
Vec3(x*t.x + y*b.x + z*n.x, x*t.y + y*b.y + z*n.y, x*t.z + y*b.z + z*n.z)
end
#trace the path
function trace(surfaces::Array{Surfaces, 1}, ray::Ray, depth::Int64, maxDepth::Int64)
if depth >= maxDepth
return Vec3(0,0,0)
end
t, material = nearest(surfaces, ray, Inf)
if typeof(material) == Empty
return Vec3(0,0,0)
end
if material.isLight == true
return material.emittance
end
ρ = material.reflectance
BRDF = ρ/Π
n = material.normal
R = hemiRand(n)
In = trace(surfaces, Ray(ray.s + t*ray.d, R), depth+1, maxDepth)
return Π*BRDF*In
end
#define camera
struct Camera
eye; v_up; N::Vec3
fov; aspect; distance::Float64
end
#render function
function render(surfaces::Array{Surfaces,1},camera::Camera,xRes::Int64,yRes::Int64,numSamples::Int64,maxDepth::Int64)
n = normalize(camera.N)
e = camera.eye
c = e - camera.distance*n
θ = camera.fov*(π/180)
H = 2*camera.distance*tan(θ/2)
W = H*camera.aspect
u = normalize(cross(camera.v_up,n))
v = cross(n,u)
img = zeros(3, xRes, yRes)
pixHeight = H/yRes
pixWidth = W/xRes
L = c - 0.5*W*u - 0.5*H*v
for i=1:xRes
for j=1:yRes
cl = Vec3(0,0,0)
for s=1:numSamples
pt = L + (i-rand())*pixWidth*u + (yRes-j+rand())*pixHeight*v
cl = cl + trace(surfaces, Ray(e, pt-e), 0, maxDepth)
end
cl = gamma(clamp(cl/convert(Float64, numSamples)))
img[:,j,i] = [cl.x, cl.y, cl.z]
end
end
img
end
#the scene
p1 = xzRect(1.,0.,1.,-1.,0.,Vec3(0,-1,0),Vec3(0,0,0),Vec3(0.75,0.75,0.75),false)
p2 = xzRect(0.,0.,1.,-1.,0.,Vec3(0,1,0),Vec3(0,0,0),Vec3(0.75,0.75,0.75),false)
p3 = xyRect(-1.,0.,1.,0.,1.,Vec3(0,0,1),Vec3(0,0,0),Vec3(0.75,0.75,0.75),false)
p4 = yzRect(0.,0.,1.,-1.,0.,Vec3(1,0,0),Vec3(0,0,0),Vec3(0.75,0.25,0.25),false)
p5 = yzRect(1.,0.,1.,-1.,0.,Vec3(-1,0,0),Vec3(0,0,0),Vec3(0.25,0.25,0.75),false)
p6 = xzRect(0.999,0.35,0.65,-0.65,-0.35,Vec3(0,-1,0),Vec3(18,18,18),Vec3(0,0,0),true)
s1 = Sphere(0.15,Vec3(0.3,0.15,-0.6),Vec3(0,0,0),Vec3(0,0,0),Vec3(0.75,0.75,0.75),false)
surfs = Surfaces[p1,p2,p3,p4,p5,p6,s1]
cam = Camera(Vec3(0.5,0.5,2),Vec3(0,1,0),Vec3(0,0,1),28.07,1,2)
#time image = render(surfs, cam, 400, 400, 1, 4);
colorview(RGB, image)
I need to know why my code is bad and slow. I am a beginner programmer and I don't have enough experience. My path tracer scene contains 7 objects, its maximum depth is 4, and it takes more than 2 seconds to generate an image of size 400*400. I think It shouldn't be that slow because my cpu is core i7 4770.
Sorry for changing my post.
To start with,
struct yzRect
x; y1; y2; z1; z2::Float64
normal; emittance; reflectance::Vec3
isLight::Bool
end
ends up only applying the type to the last variable for each line:
julia> fieldtypes(yzRect)
(Any, Any, Any, Any, Float64, Any, Any, Vec3, Bool)
so Julia will basically not know about any types in your structs which slows things down.
Also, your Vec3 should really be immutable and you then just create new instances of it when you want to "modify" the Vector.
There might be many more issues but those are two standing out.
Reading through https://docs.julialang.org/en/v1/manual/performance-tips/index.html and applying the guidelines in there is strongly recommended when analyzing performance.

Crash in Intel MPI_COMM_SPAWN_MULTIPLE

I getting a crash inside MPI_COMM_SPAWN_MULTIPLE when using the Intel MPI implementation and compiling the code with ifort. The same code works without a problem using OpenMPI and compiling with gfortran. The relevant code is posted below.
ALLOCATE(commands(num_processes - 1))
ALLOCATE(args(num_processes - 1,2))
ALLOCATE(info(num_processes - 1))
ALLOCATE(max_procs(num_processes - 1))
ALLOCATE(error_array(num_processes - 1))
commands = TRIM(context%cl_parser%command)
args(:,1) = temp_string
IF (num_threads .lt. 0) THEN
args(:,2) = '-para=-1'
ELSE IF (num_threads .lt. 10) THEN
WRITE (temp_string, 1001) num_threads
args(:,2) = TRIM(temp_string)
ELSE
WRITE (temp_string, 1002) num_threads
args(:,2) = TRIM(temp_string)
END IF
max_procs = 1
DO i = 2, num_processes
CALL MPI_INFO_CREATE(info(i - 1), error)
CALL MPI_INFO_SET(info(i - 1), "wdir", process_dir(i), &
& error)
END DO
CALL MPI_COMM_SPAWN_MULTIPLE(num_processes - 1, commands, args, &
& max_procs, info, 0, &
& MPI_COMM_WORLD, child_comm, &
& error_array, error)
CALL MPI_INTERCOMM_MERGE(child_comm, .false., &
& context%intra_comm, error)
DO i = 1, num_processes - 1
CALL MPI_INFO_FREE(info(i), error)
END DO
DEALLOCATE(info)
DEALLOCATE(max_procs)
DEALLOCATE(args)
DEALLOCATE(commands)
DEALLOCATE(error_array)

Autoit get CPU temp and put it into a graph

This is the code i have so far:
#RequireAdmin
#include <GUIConstants.au3>
$wbemFlagReturnImmediately = 0x10
$wbemFlagForwardOnly = 0x20
$strComputer = "."
$objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\wmi")
$Instances = $objWMIService.InstancesOf("MSAcpi_ThermalZoneTemperature")
For $Item in $Instances
$temp=($Item.CurrentTemperature - 2732) / 10
Next
Opt("GUIOnEventMode", 1)
GUICreate("", 340, 330)
GUISetOnEvent($GUI_EVENT_CLOSE,"close")
$GraphWidth = 273
$GraphHeight = 273
$graph = GUICtrlCreateGraphic(48, 15, $GraphWidth, $GraphHeight)
GUICtrlSetBkColor(-1,0xFFFFFF)
GUICtrlSetColor(-1,0x000000)
$yMax = 100
$yMin = 0
$xMax = 100
$xMin = 0
GUICtrlCreateLabel($yMax,15,10,20,15,$SS_RIGHT)
GUICtrlCreateLabel($yMin,15,280,20,15,$SS_RIGHT)
GUICtrlCreateLabel($xMax,307,295,20,15,$SS_CENTER)
GUICtrlCreateLabel($xMin,38,295,20,15,$SS_CENTER)
GUICtrlCreateLabel("TEMP",10,120)
$tmp=GUICtrlCreateLabel($temp,20,140)
GUISetState()
while 1
sleep(10000)
$wbemFlagReturnImmediately = 0x10
$wbemFlagForwardOnly = 0x20
$strComputer = "."
$objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\wmi")
$Instances = $objWMIService.InstancesOf("MSAcpi_ThermalZoneTemperature")
For $Item in $Instances
$temp=($Item.CurrentTemperature - 2732) / 10
Next
GUICtrlSetData($tmp, $temp)
WEnd
func close()
Exit
EndFunc
The code gets the CPU temperature and makes a graph. My questions is how do i put the temperature in to the graph and make it update every 10 seconds. Thanks for any help.
I have made this script using parts of your code, the getting of the temperature and creating and setting the event of it.
I have added the use of the library GraphGDIPlus.au3 which can be downloaded and put into your program files -> autoit -> include; link to GraphGDIPlus.
Here is the script (commented for understanding):
#RequireAdmin
#include <GraphGDIPlus.au3>
#include <GUIConstants.au3>
AdlibRegister("findTemp", 9000)
AdlibRegister("_Draw_Graph", 10000)
Local $hGUI, $hGraph, $temp, $Counter = 1, $iCheck, $msg, $xVal = 1
$hGUI = GUICreate("", 600, 350) ; create the GUI window
$iCheck = GUICtrlCreateCheckbox("Reset on next interval", 462, 1)
GUISetState() ; show the window
CreateGraph() ; create the graph
findTemp() ; find the temp
_Draw_Graph() ; draw the graph
While 1
$msg = GUIGetMsg()
Switch $msg
Case $GUI_EVENT_CLOSE
Quit()
EndSwitch
WEnd
Func CreateGraph()
If IsArray($hGraph) = 0 Then
$hGraph = _GraphGDIPlus_Create($hGUI, 37, 24, 545, 300, 0xFF000000, 0xFF88B3DD) ; create the graph
EndIf
If $Counter > 24 Then
_GraphGDIPlus_Set_RangeX($hGraph, $xVal, $Counter, 24)
$xVal += 1
Else
_GraphGDIPlus_Set_RangeX($hGraph, 0, 24, 24) ; set the x range from 0 - 24 putting all 24 ticks on screen
_GraphGDIPlus_Set_RangeY($hGraph, 0, 125, 5) ; set the y range from 0 - 125 only putting 5 ticks on screen
_GraphGDIPlus_Set_GridX($hGraph, 1, 0xFF6993BE) ; set the x grid
_GraphGDIPlus_Set_GridY($hGraph, 1, 0xFF6993BE) ; set the y grid
EndIf
EndFunc ;==>CreateGraph
Func _Draw_Graph()
Local $rCheckbox
$rCheckbox = GUICtrlRead($iCheck)
If $rCheckbox = 1 Then
ControlClick($hGUI, "Reset on next interval", $iCheck)
_GraphGDIPlus_Delete($hGUI, $hGraph) ; delete the graph
$Counter = 1 ; reset the counter
$xVal = 1 ; reset the x range counter
CreateGraph() ; and create the graph again
EndIf
If $Counter > 24 Then ; if we've reached the end
CreateGraph() ; and create the graph again
EndIf
_GraphGDIPlus_Set_PenColor($hGraph, 0xFF325D87) ; set the color of the line
_GraphGDIPlus_Set_PenSize($hGraph, 2) ; set the size of the line
_GraphGDIPlus_Plot_Start($hGraph, $Counter, 0) ; set the start on the graph plot
_GraphGDIPlus_Plot_Line($hGraph, $Counter, $temp) ; set the line ending
_GraphGDIPlus_Refresh($hGraph) ; draw it to the screen
$Counter += 1 ; add one to our counter
EndFunc ;==>_Draw_Graph
Func findTemp()
$wbemFlagReturnImmediately = 0x10
$wbemFlagForwardOnly = 0x20
$strComputer = "."
$objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\wmi")
$Instances = $objWMIService.InstancesOf("MSAcpi_ThermalZoneTemperature")
For $Item In $Instances
$temp = ($Item.CurrentTemperature - 2732) / 10 ; set the temp
Next
EndFunc ;==>findTemp
Func Quit()
_GraphGDIPlus_Delete($hGUI, $hGraph) ; delete the graph
Exit ; get us out
EndFunc ;==>Quit

Pygame,shooting bullets using vectors

Ok so all night me and 5 other guys have been working on a project for our pygame module.Our lecturer hasn't given us any programs to reference from he has just throw a bunch of code at us (without commenting) and expecting us to understand it.We only started python since the start of september.We really need some help.
So we have one human player which is controlled by W A S & D and 15 random dots moving around the screen.We need to use vectors(which we have never used) to shoot at the random dots.
Please someone help.
edit code added~
import pygame
class Terminator(pygame.sprite.Sprite):
def __init__(self, screen):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((20, 20))
self.image.fill((0, 0, 0))
pygame.draw.circle(self.image, (255, 0, 0), (10, 10), 10, 0)
self.rect = self.image.get_rect()
self.dx = screen.get_width()/2
self.dy = screen.get_height()/2
self.rect.center = (self.dx, self.dy)
self.speed = 5
self.screen = screen
def update(self):
self.rect.center = (self.dx, self.dy)
def MoveLeft(self):
if self.rect.left < 0:
self.dx += 0
else:
self.dx -= self.speed
def MoveRight(self):
if self.rect.right > self.screen.get_width():
self.dx += 0
else:
self.dx += self.speed
def MoveUp(self):
if self.rect.top <0:
self.dy += 0
else:
self.dy -= self.speed
def MoveDown(self):
if self.rect.bottom > self.screen.get_height():
self.dy += 0
else:
self.dy += self.speed
<code>
humansprite.py
<pre>
import pygame
import random
import math
class Humans(pygame.sprite.Sprite):
def __init__(self, screen):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((16, 16))
self.image.fill((0, 0, 0))
pygame.draw.circle(self.image, (0, 0, 255), (8, 8), 8, 0)
self.rect = self.image.get_rect()
self.dx = random.randrange(0, screen.get_height())
self.dy = random.randrange(0, screen.get_width())
self.screen = screen
self.speed = 1
self.alive = True
def update(self):
self.rect.centerx -= self.dx
self.rect.centery -= self.dy
if self.rect.right < 0:
self.reset()
def reset(self):
self.rect.left = self.screen.get_width()
self.rect.centery = random.randrange(0, self.screen.get_height())
self.dy = random.randrange(-2, 2)
self.dx = random.randrange(1, 4)
<code>
seekandDestory.py
<pre>
import pygame
from TerminatorSprite import Terminator
from humansSprite import Humans
pygame.init()
def checkKeys(myData):
(event, ship) = myData
if event.key == pygame.K_LEFT:
print 'LEFT'
ship.MoveLeft()
if event.key == pygame.K_RIGHT:
print 'RIGHT'
ship.MoveRight()
if event.key == pygame.K_UP:
print 'UP'
ship.MoveUp()
if event.key == pygame.K_DOWN:
print 'DOWN'
ship.MoveDown()
def main():
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Seek and Destroy")
background = pygame.Surface(screen.get_size())
clock = pygame.time.Clock()
screen.blit(background, (0, 0))
terminator = Terminator(screen)
humans = []
for people in range(15):
people = Humans(screen)
humans.append(people)
terminatorGroup = pygame.sprite.Group(terminator)
humanGroup = pygame.sprite.Group(humans)
clock = pygame.time.Clock()
keepGoing = True
pygame.key.set_repeat(10, 10)
while keepGoing:
clock.tick(60)
pygame.mouse.set_visible(False)
for event in pygame.event.get():
if event.type == pygame.QUIT:
keepGoing = False
if event.type == pygame.KEYDOWN:
myData = (event, terminator)
checkKeys(myData)
#if pygame.sprite.spritecollide(terminator, humanGroup, False):
terminatorGroup.clear(screen, background)
terminatorGroup.update()
terminatorGroup.draw(screen)
humanGroup.clear(screen, background)
humanGroup.update()
humanGroup.draw(screen)
pygame.display.flip()
pygame.mouse.set_visible(True)
if __name__ == "__main__":
main()
<code>
I just finished up this set of examples last night! Check out the Lunar Lander example, especially the way I'm handling vectors in lunarlander.py - it provides a class, V, for vector management.
What you'll probably need is a sprite for your guy with a vector representing his speed (moment-to-moment, probably 0) and angle, then a sprite for each random dot with a similar vector and angle. When you shoot, create a new sprite with a vector whose angle matches the current angle your guy is facing and magnitude matches the speed of the bullet. Then, in the update() method, move each sprite (bullet, random-dot). Very similar to what I'm doing in lunarlander.py.
Good luck! If you've just started Python, that's a tough assignment. Happy coding!

Resources