[not well english, sorry;]
i m want mouse drag
if delete in source code 'win32gui.SendMessage(hwndcontrol, win32con.WM_MOUSEMOVE, 1, lparam2)' = works well(drag - move = click, click to well work)
why not drag? and What should I do?
def drag_func(x1, y1, x2, y2):
hwnd = win32gui.FindWindow(None, name)
hwndcontrol = win32gui.FindWindowEx(hwnd, None, "RenderWindow", "TheRender")
lparam1 = (y1-34) << 16 | x1
lparam2 = (y2-34) << 16 | x2
win32gui.SendMessage(hwndcontrol, win32con.WM_SETCURSOR, MK_LBUTTON, lparam1)
win32gui.SendMessage(hwndcontrol, win32con.WM_LBUTTONDOWN, MK_LBUTTON, lparam1)
#time.sleep(0.1)
win32gui.SendMessage(hwndcontrol, win32con.WM_MOUSEMOVE, 1, lparam2)
#time.sleep(0.1)
win32gui.SendMessage(hwndcontrol, win32con.WM_LBUTTONUP, 1, lparam2)
I use this as example. but im a noob i "fake" click the widow and send the key stroke i dont even know how to click the mouse with python so osrs sees it
import time
import random
from time import sleep
import win32api, win32gui, win32con
def drawmouselocation(x,y,posss):
dc = win32gui.GetDC(0)
red = win32api.RGB(255, 0, 0)
for ii in range(10):
win32gui.SetPixel(dc, x+posss[0], y+posss[1], red)
for ofsy in range(10):
for ofsx in range(10):
win32gui.SetPixel(dc, x+posss[0]+ofsx, y+posss[1]+ ofsy, red)
time.sleep(0.01)
posss = [0,0]
num = 0
def callback(handle, param):
global num
global poss
posss = [580+random.randint(0,10),310+random.randint(0,10)]
s = win32gui.GetClassName(handle)
try:
if num == 0: #edit tis number for the right window
print(f'Current window: {handle}, {s}')
rect = win32gui.GetWindowRect(handle)
x = rect[0]
y = rect[1]
w = rect[2] - x
h = rect[3] - y
print("\tLocation: (%d, %d)" % (x, y))
print("\t Size: (%d, %d)" % (w, h))
print("\t mouse click: (%d, %d)" % (posss[0],posss[1]))
drawmouselocation(x,y,posss)
tmp = win32api.MAKELONG(posss[0],posss[1])
win32gui.SendMessage(handle, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)
win32api.SendMessage(handle, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, tmp)
time.sleep(0.1)
win32gui.SendMessage(handle, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)
win32api.SendMessage(handle, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, tmp)
time.sleep(0.001)
tmp = win32api.MAKELONG(posss[0]+1,posss[1]+1)
win32api.SendMessage(handle, win32con.WM_MOUSEMOVE, win32con.MK_LBUTTON, tmp)
time.sleep(0.1)
win32api.SendMessage(handle, win32con.WM_MOUSEMOVE, win32con.MK_LBUTTON, tmp)
tmp = win32api.MAKELONG(posss[0]+2,posss[1]+2)
win32api.SendMessage(handle, win32con.WM_MOUSEMOVE,0, tmp)
time.sleep(0.1)
win32api.SendMessage(handle, win32con.WM_MOUSEMOVE, 0, tmp)
time.sleep(0.1)
win32api.SendMessage(handle, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, tmp)
time.sleep(0.1)
win32api.SendMessage(handle, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, tmp)
win32gui.SendMessage(handle, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)
win32gui.PostMessage(handle, win32con.WM_KEYDOWN, win32con.VK_RETURN, int('0x1C0001',0))
win32gui.SendMessage(handle, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)
win32gui.PostMessage(handle, win32con.WM_KEYUP, win32con.VK_RETURN, int('0xC0000001',0))
except Exception:
print('Exception sending to {handle}, {s}')
num = num + 1
def send_the_keys(handle):
num = 0
win32gui.EnumChildWindows(handle, callback, 0)
def winEnumHandler( hwnd, ctx ):
if win32gui.IsWindowVisible( hwnd ):
winnn = win32gui.GetWindowText( hwnd )
if "Rune" in winnn:
print ( hex( hwnd ), winnn)
window_id = win32gui.FindWindow(None, winnn)
send_the_keys(window_id)
if "Oldchool" in winnn:
print ( hex( hwnd ), winnn)
window_id = win32gui.FindWindow(None, winnn)
send_the_keys(window_id)
def pressenter():
win32gui.EnumWindows( winEnumHandler, None )
pressenter();
using python 3.7 https://www.python.org/ftp/python/3.7.0/python-3.7.0-amd64.exe
and winpy for x64 python 3.7
https://jztkft.dl.sourceforge.net/project/pywin32/pywin32/Build%20221/pywin32-221.win-amd64-py3.7.exe
Related
First, the CameraGroup class is attributed to the wonderful youtube channel Clear Code.
Second, the hitboxes will not zoom (mousewheel) or scroll (WASD keys) with the planet icons. Try clicking the planets before zooming or scrolling and you will see the hitbox in action.
Third, as the screen is zoomed out the planets get smaller and the camera window shrinks towards the middle of the screen. Ideally, the camera window should stay the full size of the parent window to allow displaying more planets in the zoomed out state.
Finally, I am eager to learn, so please be brutal. Just drop the two planet icons in the folder with the .py file.
import os
import pygame
from pygame import *
from sys import exit
class CameraGroup(pygame.sprite.Group):
def __init__(self):
super().__init__()
self.display_surf_foreground = pygame.display.get_surface()
# camera offset
self.offset = pygame.math.Vector2()
self.half_w = self.display_surf_foreground.get_size()[0] // 2
self.half_h = self.display_surf_foreground.get_size()[1] // 2
self.scroll_offset = (0, 0)
# box setup
self.camera_borders = {'left': 200, 'right': 200, 'top': 100, 'bottom': 100}
l = self.camera_borders['left']
t = self.camera_borders['top']
w = self.display_surf_foreground.get_size()[0] - (self.camera_borders['left'] + self.camera_borders['right'])
h = self.display_surf_foreground.get_size()[1] - (self.camera_borders['top'] + self.camera_borders['bottom'])
self.camera_rect = pygame.Rect(l, t, w, h)
# camera speed
self.keyboard_speed = 10
# zoom
self.zoom_scale = 1
self.foreground_surf_size = (400, 400)
self.foreground_surf = pygame.Surface(self.foreground_surf_size, pygame.SRCALPHA)
self.foreground_rect = self.foreground_surf.get_rect(center=(self.half_w, self.half_h))
self.foreground_surf_size_vector = pygame.math.Vector2(self.foreground_surf_size)
self.foreground_offset = pygame.math.Vector2()
self.foreground_offset.x = self.foreground_surf_size[0] // 2 - self.half_w
self.foreground_offset.y = self.foreground_surf_size[1] // 2 - self.half_h
# planets and labels
self.planet_surf = pygame.Surface
self.planet_rect = pygame.Rect
def keyboard_control(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
self.camera_rect.x -= self.keyboard_speed
if keys[pygame.K_d]:
self.camera_rect.x += self.keyboard_speed
if keys[pygame.K_w]:
self.camera_rect.y -= self.keyboard_speed
if keys[pygame.K_s]:
self.camera_rect.y += self.keyboard_speed
self.offset.x = self.camera_rect.left - self.camera_borders['left']
self.offset.y = self.camera_rect.top - self.camera_borders['top']
def zoom_keyboard_control(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_q]:
self.zoom_scale += 0.1
if self.zoom_scale > 2:
self.zoom_scale = 2
if keys[pygame.K_e]:
self.zoom_scale -= 0.1
if self.zoom_scale < .5:
self.zoom_scale = .5
def custom_draw(self, planets):
self.keyboard_control()
self.zoom_keyboard_control()
self.foreground_surf.fill((0, 0, 0, 255))
# active elements
for planet in planets:
self.planet_surf = pygame.image.load(planet.icon).convert_alpha()
offset_coord = planet.coord - self.offset + self.foreground_offset
self.planet_rect = self.planet_surf.get_rect(center=offset_coord)
self.foreground_surf.blit(self.planet_surf, self.planet_rect)
scaled_surf = pygame.transform.scale(self.foreground_surf, self.foreground_surf_size_vector * self.zoom_scale)
scaled_rect = scaled_surf.get_rect(center=(self.half_w, self.half_h))
self.display_surf_foreground.blit(scaled_surf, scaled_rect)
class Game:
def __init__(self):
self.game_over = False
self.game_year = 0
self.game_state = 'splash'
#staticmethod
def activate_planet(screen, planets):
active_planet_coord = None
for planet in planets:
if planet.rect.collidepoint(pygame.mouse.get_pos()):
active_planet_coord = planet.rect.center
return active_planet_coord
return active_planet_coord
#staticmethod
def heartbeat(screen, active_planet_coord):
# global heartbeat_mod
global heartbeat
ticks = pygame.time.get_ticks()
heartbeat_thump = round(ticks / 1000) % 2
if heartbeat_thump == 0:
heartbeat_mod = .1
else:
heartbeat_mod = -.1
heartbeat += heartbeat_mod
if heartbeat < 1:
heartbeat = 1
elif heartbeat > 6:
heartbeat = 6
heartbeat_color = (0, 255, 0)
pygame.draw.circle(screen, heartbeat_color, active_planet_coord, 25 + round(heartbeat), round(heartbeat) + 2)
class Planet(pygame.sprite.Sprite):
def __init__(self, icon, group):
super().__init__(group)
self.icon = icon
self.coord = (0, 0)
self.group = group
self.image = pygame.image.load(self.icon).convert_alpha()
self.rect = self.image.get_rect(center=self.coord)
self.planet_icons = []
self.planet_names = []
#staticmethod
def update_coords(planets, star_coords):
i = 0
for planet in planets:
planet.coord = tuple(star_coords[i])
planet.rect = planet.image.get_rect(center=planet.coord)
i += 1
if i == len(star_coords):
del planets[len(star_coords):]
return planets
def main():
global heartbeat
global heartbeat_mod
pygame.init()
width, height = 400, 400
screen = pygame.display.set_mode((width, height))
pygame.display.init()
pygame.display.update()
active_planet_coord = (-100, -100)
heartbeat = 0
heartbeat_mod = .1
clock = pygame.time.Clock()
game = Game()
camera_group = CameraGroup()
planet_array = os.listdir('./')
planet_array.pop(0) # remove 'camera scroll example.py' file
planet_icons = planet_array
planets = []
for new_planet in range(2):
icon = planet_icons.pop()
planet = Planet(icon, camera_group)
planets.append(planet)
star_coords = [[100, 100], [200, 200]]
planets = planet.update_coords(planets, star_coords)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
active_planet_coord = game.activate_planet(screen, camera_group)
if active_planet_coord is None:
active_planet_coord = (-100, -100)
pygame.display.update()
elif event.type == pygame.MOUSEWHEEL:
camera_group.zoom_scale += event.y * 0.1
if camera_group.zoom_scale > 2:
camera_group.zoom_scale = 2
elif camera_group.zoom_scale < .5:
camera_group.zoom_scale = .5
camera_group.update()
camera_group.custom_draw(planets)
game.heartbeat(screen, active_planet_coord)
pygame.display.update()
clock.tick(60)
if __name__ == '__main__':
main()
An alternative way to solve this problem is to "inverse zoom" the mouse position when you use it for click detection:
zoom:
p_zoom = (p - zoom_center) * zoom_scale + zoom_center
inverse zoom:
p = (p_zoom - zoom_center) / zoom_scale + zoom_center
Apply this to your code:
class Game:
# [...]
#staticmethod
def activate_planet(screen, planets):
zoom_scale = planets.zoom_scale
zoom_center = pygame.math.Vector2(screen.get_rect().center)
pos = pygame.math.Vector2(pygame.mouse.get_pos())
pos = (pos - zoom_center) / zoom_scale + zoom_center
active_planet_coord = None
for planet in planets:
if planet.rect.collidepoint(pos):
planet_center = (planet.rect.center - zoom_center) * zoom_scale + zoom_center
active_planet_coord = round(planet_center.x), round(planet_center.y)
return active_planet_coord
return active_planet_coord
So I'm trying to create space Invaders currently and i'm trying to make the aliens shoot at the player randomnly. I've made it so that one projectile or enemy missle is shot at the player, but I can't figure out how I can make this happen from random places where the aliens are located, and how I can make the enemy repeatedly shoot missles,as opposed to just once as it's doing right now. My code that i'm using is down below (variables related to the shooting of the enemy are enemMissleFire and enemymissles)....
import pygame
import sys
import time
#initialize pygame
pygame.init()
width = 800
height = 600
# set the size for the surface (screen)
screen = pygame.display.set_mode((width, height),pygame.FULLSCREEN)
width = screen.get_width()
height = screen.get_height()
print(width)
print(height)
# set the caption for the screen
pygame.display.set_caption("Space Invaders")
def checkCollision(missles, type, score):
for missle in missles:
collision = missle.collidelist((type))
if collision > -1:
type.pop(collision)
missles.remove(missle)
missle.move_ip(0,missleSpeed)
pygame.draw.rect(screen, WHITE, missle,0)
# define colours you will be using
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
YELLOW = (255,255,0)
clock = pygame.time.Clock()
FPS = 60
s = 25
#load and scale images
smallInvaderImg = pygame.image.load("images/smallinvader.png")
smallInvaderImg = pygame.transform.scale(smallInvaderImg,(s,s))
medInvaderImg = pygame.image.load("images/crabinvader.png")
medInvaderImg = pygame.transform.scale(medInvaderImg, (s,s))
bigInvaderImg = pygame.image.load("images/biginvader.png")
bigInvaderImg = pygame.transform.scale(bigInvaderImg, (s,s))
shipImg = pygame.image.load("images/ship.png")
shipImg = pygame.transform.scale(shipImg, (60,60))
smallInvaders = []
medInvaders = []
bigInvaders = []
enemiesMap = ["sssssssssss",
"mmmmmmmmmmm",
"mmmmmmmmmmm",
"bbbbbbbbbbb"]
invadertype = [smallInvaders,medInvaders,bigInvaders]
dx = 1
dy = 0
x = 240
y = 0
gap = 10
for element in enemiesMap:
for char in element:
if char == "s":
smallInvaders.append(pygame.Rect(x,y,s,s))
elif char == "m":
medInvaders.append(pygame.Rect(x,y,s,s))
elif char == "b":
bigInvaders.append(pygame.Rect(x,y,s,s))
x += s + gap
y += s + gap
x = 240
score = 2
ship = pygame.Rect(width/2,525,60,60)
if ship.right == width:
ship.right = width
#missles
maxMissles = 3
missleSpeed = -6
missleWidth = 5
missleHeight = 30
enemmissleWidth = 5
enemmissleHeight = 25
missles = []
missleFired = False
lives = 3
playbutton = pygame.Rect(width/2,height/2,155,90)
playbutton.center = (width/2,height/2)
quitbutton = pygame.Rect(width/2,height/2,155,90)
quitbutton.center = (width/2,height/2+110)
playagn = pygame.Rect(width/2,height/2,155,90)
playagn.center = (width/2,height/2)
playword = pygame.font.SysFont("comicsanms", 35)
title = pygame.font.SysFont("comicsanms", 90)
quitword = pygame.font.SysFont("comicsanms",35)
endscreen = pygame.font.SysFont("comicsanms", 90)
playagaintext = pygame.font.SysFont("comicsanms", 35)
enemMissleFire = False
enemmislist = []
enemymissles = (pygame.Rect(ship.centerx,y,enemmissleWidth,enemmissleHeight))
invaderDirSwapped = False
screenControl = 0
main = True
while main:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
main = False
for element in smallInvaders:
element.move_ip(dx,dy)
for element in smallInvaders:
if element.right >= width or element.left <= 0:
dx *= -1
invaderDirSwapped = True
for element in medInvaders:
element.move_ip(dx,dy)
if not invaderDirSwapped:
for element in medInvaders:
if element.right >= width or element.left <= 0:
dx *= -1
invaderDirSwapped = True
for element in bigInvaders:
element.move_ip(dx,0)
if not invaderDirSwapped:
for element in bigInvaders:
if element.right >= width or element.left <=0:
dx *= -1
invaderDirSwapped = True
key_input = pygame.key.get_pressed()
if key_input[pygame.K_RIGHT] and ship.right < width:
ship.move_ip(4,0)
if key_input[pygame.K_LEFT] and ship.left > 0:
ship.move_ip(-4,0)
if key_input[pygame.K_SPACE] and not missleFired:
missleFired = True
missles.append(pygame.Rect(ship.centerx,ship.top,missleWidth,missleHeight))
if screenControl == 0:
screen.fill(BLACK)
texttitle = title.render("SPACE INVADERS", True, WHITE)
textrect = texttitle.get_rect()
textrect.center = (width/2, 100)
screen.blit(texttitle,textrect)
if playbutton.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
screenControl = 1
pygame.draw.rect(screen,WHITE,(playbutton), 0)
if playbutton.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen,BLUE, (playbutton), 4)
if quitbutton.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
main = False
pygame.draw.rect(screen,WHITE,(quitbutton), 0)
if quitbutton.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen,BLUE,quitbutton,4)
textplay = playword.render("PLAY", True, BLUE)
textrect2 = textplay.get_rect()
textrect2.center = (width/2,height/2)
screen.blit(textplay,textrect2)
textquit = quitword.render("QUIT",True,BLUE)
textrect3 = textquit.get_rect()
textrect3.center = (width/2,height/2+110)
screen.blit(textquit,textrect3)
if screenControl == 1:
screen.fill(BLACK)
if len(missles) > 0:
if missleFired and missles[-1].bottom < (ship.top - 120) and not key_input[pygame.K_SPACE]:
missleFired = False
if len(missles) == 0:
missleFired = False
if enemMissleFire:
enemymissles.colliderect(ship)
enemymissles.move_ip(0,-missleSpeed)
pygame.draw.rect(screen, WHITE, enemymissles,0)
for invader in smallInvaders:
screen.blit(smallInvaderImg, invader)
for invader in medInvaders:
screen.blit(medInvaderImg, invader)
for invader in bigInvaders:
screen.blit(bigInvaderImg, invader)
screen.blit(shipImg,ship)
#move and draw missles
checkCollision(missles,smallInvaders,score)
checkCollision(missles,medInvaders,score)
checkCollision(missles,bigInvaders,score)
if smallInvaders == [] and medInvaders == [] and bigInvaders == []:
screenControl = 2
if screenControl == 2:
screen.fill(BLACK)
if playagn.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
screenControl = 0
pygame.draw.rect(screen,WHITE,(playagn),0)
if quitbutton.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
main = False
pygame.draw.rect(screen,WHITE, (quitbutton),0)
if playagn.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen,BLUE,(playagn), 4)
if quitbutton.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen,BLUE,(quitbutton),4)
textend = endscreen.render("YOU WON!", True, WHITE)
textrect4 = textend.get_rect()
textrect4.center = (width/2, 150)
screen.blit(textend,textrect4)
textplayagn = playagaintext.render("PLAY AGAIN", True, BLUE)
textrect5 = textplayagn.get_rect()
textrect5.center = (width/2,height/2)
screen.blit(textplayagn,textrect5)
textquit = quitword.render("QUIT",True,BLUE)
textrect3 = textquit.get_rect()
textrect3.center = (width/2,height/2+110)
screen.blit(textquit,textrect3)
pygame.display.update()
Regardless, I can't figure out how I can make it so that projectiles can be shot from random aliens, over the course of the player shooting, and so any help would be appreicated.
Import Random and Time
this will get the random and time functions built in
from random import randint as ran
import time
Get the Number
this will get the time between the previous shot and the next
t = ran(Min_Time,Max_Time)
Get The Countdown
this will count a second between numbers
time.sleep(1)
t -= 1
print(t)
Shot!
shoot
if t == 0:
print('shot!')
FINAL CODE (trumpet fanfare)
from random import randint as ran
import time
def randshot(Min_Time,Max_Time):
t = ran(Min_Time,Max_Time)
print(t)
while t:
time.sleep(1)
t -= 1
print(t)
if t == 0:
print('shot!')
while True:
randshot(5,10)
Hope this Helped!
im trying to create a function that fill the screen with dots(that will be the points in the game)
the problem is the points created by a for loop and when i run the program the points just move around and wont stay in place.
the code:
def random_points():
point_x = random.randint(0, 900)
point_y = random.randint(0, 500)
rand_color = (random.random(), random.random(), (random.random()))
R = random.randint(1, 4)
for _ in range(1, 5):
pygame.draw.circle(WIN, rand_color, (point_x, point_y), R)
You need to create a list of points before the application loop:
point_list = []
for _ in range(1, 5):
point_x = random.randint(0, 900)
point_y = random.randint(0, 500)
rand_color = (random.random(), random.random(), (random.random()))
R = random.randint(1, 4)
point = (rand_color, (point_x, point_y), R)
point_list.append(point)
Draw the points from the list in the application loop:
run = True
while run:
for event = pygame.event.get():
if event.type == pygame.QUIT:
run = False
WIN.fill(0)
for color, center, rad in point_list:
pygame.draw.circle(WIN, color, center, rad)
pygame.disaply.flip()
I wish to detect an image from my webcam and write the result whether it is moving left or right to a file. To increase the frame rate(because this project involves a lot more processing and might be run on a raspberry pi) I decided to do the file writing part through multiprocessing (which I am new to):
code:
function for multi-processing
def send_cmd(cv):
# ####EXECUTE LOGIC AND CREATE COMMAND###
# writing to file
# just a sample command// change as will
dictionary = {'left': 0, 'right': 0, 'stop': 0}
if cv[0] == 'left':
dictionary['right'] = 1
else:
dictionary['left'] = 1
cmd = '{"left":' + str(dictionary['left']) + ',"right":' + str(dictionary['left'
]) + ',"stop":' + str(dictionary['left']) + '}'
print("command written: " + cmd)
f = open('command.txt', 'w')
f.write(cmd)
f.close()
Main code:
while True:
try:
frame = cv.VideoCapture(0)
frame = imutils.resize(frame, width=400)
if W is None or H is None:
(H, W) = frame.shape[:2]
blob = cv.dnn.blobFromImage(cv.resize(frame, (300, 300)),
0.007843, (300, 300), 127.5)
net.setInput(blob)
detections = net.forward()
rects = []
for i in range(0, detections.shape[2]):
if detections[0, 0, i, 2] > args['confidence']:
box = detections[0, 0, i, 3:7] * np.array([W, H, W, H])
rects.append(box.astype('int'))
(startX, startY, endX, endY) = box.astype('int')
cv.rectangle(frame, (startX, startY), (endX, endY), (0,
0xFF, 0), 2)
objects = ct.update(rects)
for (objectID, centroid) in objects.items():
text = 'ID {}'.format(objectID)
cv.putText(
frame,
text,
(centroid[0] - 10, centroid[1] - 10),
cv.FONT_HERSHEY_SIMPLEX,
0.5,
(0, 0xFF, 0),
2,
)
cv.circle(frame, (centroid[0], centroid[1]), 4, (0, 0xFF,
0), -1)
center = (centroid[0], centroid[1])
pts.appendleft(center)
for i in np.arange(1, len(pts)):
if pts[i - 1] is None or pts[i] is None:
continue
if counter >= 10 and i == 1 and pts[-1] is not None:
dX = pts[-1][0] - pts[i][0]
dY = pts[-1][1] - pts[i][1]
global dirX
global dirY
(dirX, dirY) = ('', '')
if np.abs(dX) > 20:
dirX = ('left' if np.sign(dX) == 1 else 'right')
if np.abs(dY) > 20:
dirY = ('up' if np.sign(dY) == 1 else 'down')
#tried multiprocessing with process method but to many process calls at the same time
order = multiprocessing.Process(target = send_cmd,args = ([dirX, dirY]))
order.start()
order.join()
# send_cmd(cv=[dirX, dirY], us=ultra_sonic)
if dirX != '' and dirY != '':
direction = '{}-{}'.format(dirY, dirX)
else:
direction = (dirX if dirX != '' else dirY)
thickness = int(np.sqrt(args['buffer'] / float(i + 1))
* 2.5)
cv.putText(
frame,
direction,
(10, 30),
cv.FONT_HERSHEY_SIMPLEX,
0.65,
(0, 0, 0xFF),
3,
)
cv.putText(
frame,
'dx: {}, dy: {}'.format(dX, dY),
(10, frame.shape[0] - 10),
cv.FONT_HERSHEY_SIMPLEX,
0.35,
(0, 0, 0xFF),
1,
)
cv.imshow('Frame', frame)
key = cv.waitKey(1) & 0xFF
counter += 1
Error:
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:
if __name__ == '__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable.
Can someone guide me?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am having a problem that I wish you guys could help me.
In this soccer game when i move the player around the field the goals dont stick to there positions and they move along with the ball.
Example:
import pygame
import random
import sys, glob
from pygame.locals import *
class Ball(pygame.sprite.Sprite):
def __init__(self,x,y,image_x):
self.bottom = 20
self.image = pygame.image.load("res/images/ball1.png")
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
screen.blit(self.image,(self.rect.x,self.rect.y))
self.change_x=x
self.change_y=y
class Field(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
#self.field = pygame.image.load('res/images/field.png').convert()
#self.field_rect = self.field.get_rect()
#self.field_rect.x = 0
#screen.blit(self.field,(self.field_rect.x,self.field_rect.y))
def goal_top(self):
self.goal_top = pygame.image.load("res/images/goal-top.png")
screen.blit(self.goal_top,(425,0))
def goal_bottom(self):
self.goal_bottom = pygame.image.load("res/images/goal-btm.png")
self.goal_bottom_rect = self.goal_bottom.get_rect()
self.goal_bottom_rect.y = 720
screen.blit(self.goal_bottom,(425,self.goal_bottom_rect.y ))
class Player(pygame.sprite.Sprite):
def __init__(self,x,y,image_x,image_y):
self.bottom = 20
self.image = pygame.image.load("res/images/player/boy.png")
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
screen.blit(self.image,(self.rect.x,self.rect.y))
self.change_x=x
self.change_y=y
def changespeed_x(self,x):
self.change_x = x
def changespeed_y(self,y):
self.change_y = y
class Camera(object):
def __init__(self, camera_func, width, height):
self.camera_func = camera_func
self.state = Rect(0, 0, width, height)
def apply(self, target):
try:
return target.rect.move(self.state.topleft)
except AttributeError:
return map(sum, zip(target, self.state.topleft))
def update(self, target):
self.state = self.camera_func(self.state, target.rect)
def complex_camera(camera, target_rect):
l, t, _, _ = target_rect
_, _, w, h = camera
l, t, _, _ = -l + HALF_WIDTH, -t+HALF_HEIGHT, w, h
l = min(0, l) # stop scrolling left
l = max(-(camera.width-WIN_WIDTH), l) # stop scrolling right
t = max(-(camera.height-WIN_HEIGHT), t) # stop scrolling bottom
t = min(0, t) # stop scrolling at the top
return Rect(l, t, w, h)
pygame.init()
# Set the height and width of the screen
WIN_WIDTH = 963
WIN_HEIGHT = 760
HALF_WIDTH = int(WIN_WIDTH / 2)
HALF_HEIGHT = int(WIN_HEIGHT / 2)
size=[WIN_WIDTH,WIN_HEIGHT]
screen=pygame.display.set_mode(size)
#screen=pygame.display.set_mode(size,FULLSCREEN)
pygame.display.set_caption("Soccer")
clock=pygame.time.Clock()
x=500
y=280
set_ball_x = 500
set_ball_y = 300
shot = False
type=''
dir_y=0
##INITIAL POSITION OF IMAGES
image_x=0
image_y=0
ball_image_x=0
dir_y=0
##CAMERA TRACK
total_level_width = 963 ##BACKGROUND (Field) width
total_level_height = 1200 ##BACKGROUND (Field) height
camera = Camera(complex_camera, total_level_width, total_level_height)
background = pygame.image.load('res/images/field.png').convert()
background_rect = background.get_rect()
while 1:
clock.tick(20)
screen.blit(background, camera.apply((0,0)))
ball = Ball(set_ball_x,set_ball_y,ball_image_x)
camera.update(ball)
player = Player(x,y,image_x,image_y)
field = Field()
field.goal_top()
field.goal_bottom()
if pygame.key.get_pressed()[pygame.K_RIGHT]:
x=x+6
pos =+1
image_x = 0
if image_y < 90:
image_y +=30
else:
image_y = 0
if pygame.key.get_pressed()[pygame.K_LEFT]:
x=x-6
image_x = 130
if image_y < 90:
image_y +=30
else:
image_y = 0
if pygame.key.get_pressed()[pygame.K_UP]:
y=y-6
image_x = 195
if image_y < 90:
image_y +=30
else:
image_y = 0
if pygame.key.get_pressed()[pygame.K_DOWN]:
y=y+6
image_x = 70
if image_y < 90:
image_y +=30
else:
image_y = 0
if pygame.sprite.collide_rect(player,ball):
set_ball_x = player.change_x
set_ball_y = player.change_y+20
if pygame.key.get_pressed()[pygame.QUIT]:
sys.exit()
if pygame.key.get_pressed()[pygame.K_q]: ## KEY "Q" to EXIT
sys.exit()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.flip()
pygame.display.update()
Any ideas why this is happening?
Thank you
What is Camera.apply() doing?
This:
l, t, _, _ = target_rect
_, _, w, h = camera
Should be:
loc = target_rect.topleft
size = camera.size
And
l, t, _, _ = -l + HALF_WIDTH, -t+HALF_HEIGHT, w, h
If you're trying to get the center coordinate? You use
loc = target_rect.center