Mouse motion tracking Program with python - python

I am trying to track mouse motion on a variety of applications, like the desktop, or some web applications. This is to understand and capture user behaviour (those users who are computer illiterate, trying to understand how they behave and interact with the system). For example, if I make such a user sit in front of a desktop and leave him, my program should track all the movements which he makes with the mouse, which I can later correspond with the design of the system.
I wrote a small program in pygame to do the same.
import pygame
x = y = 0
running = 1
screen = pygame.display.set_mode((640, 400))
while running:
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = 0
elif event.type == pygame.MOUSEMOTION:
print "mouse at (%d, %d)" % event.pos
screen.fill((0, 0, 0))
pygame.display.flip()
I wish to change the "screen = pygame.display.set_mode((640, 400))". I dont want a new window to be opened by pygame. I want the same window I am working upon, and it tracks the mouse movements. Even if I close my editor, the program should run. There should be no seperate screen. How do I do it ?

yes you can in this event i have changed your code so that if the mouse is at the coordinate (300,200) then it changes the screen size to (400, 500)
p.s. look at what i added at the beginning:
import pygame
from pygame.locals import * #just so that some extra functions work
pygame.init() #this turns pygame 'on'
x = y = 0
running = 1
screen = pygame.display.set_mode((640, 400))
while running:
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = 0
elif event.type == pygame.MOUSEMOTION:
print "mouse at (%d, %d)" % event.pos
if event.pos == (300,200):
screen = pygame.display.set_mode((400, 500))
screen.fill((0, 0, 0))
pygame.display.flip()

I had a similar problem. I realized that pygame can't keylog, or track mouse events, if the window is not in focus, or if the mouse is not currently on the window. If you're looking for a keylogger/ mouse event recorder, try pyHook on pynpnut, depending on if you're using python 2 or 3. These modules can be installed with pip

Related

Resize pygame window with minimum width/height without flickering [duplicate]

I'm developing a grid based game in pygame, and want the window to be resizable. I accomplish this with the following init code:
pygame.display.set_mode((740, 440), pygame.RESIZABLE)
As well as the following in my event handler:
elif event.type == pygame.VIDEORESIZE:
game.screen = pygame.display.set_mode((event.w, event.h),
pygame.RESIZABLE)
# Code to re-size other important surfaces
The problem I'm having is that it seems a pygame.VIDEORESIZE event is only pushed once the user is done resizing the window, i.e. lets go of the border. screen.get_size() updates similarly. Since the graphics of my game are very simple, I'd really prefer for them to resize as the user drags the window. This is trivial in many other languages, but I can't find any reference for it in pygame - although I can't imagine a feature this basic would be impossible.
How can I update my game as the screen is being resized in pygame?
EDIT: Here is a minimal working example. Running on Windows 10, pygame 1.9.4, the following code will only draw the updated rectangle after the user finishes dragging the window.
import sys
import pygame
pygame.init()
size = 320, 240
black = 0, 0, 0
red = 255, 0, 0
screen = pygame.display.set_mode(size, pygame.RESIZABLE)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.VIDEORESIZE:
pygame.display.set_mode((event.w, event.h), pygame.RESIZABLE)
screen.fill(black)
pygame.draw.rect(screen, red, (10,10,screen.get_width(),screen.get_height()))
pygame.display.flip()
If you run into this kind of problem, it's always worth to google it using SDL instead of pygame, since pygame is a pretty low-level SDL wrapper.
So that's not a problem of pygame itself, but rather how sdl and your window manager interact, e.g. see this SDL bug report.
Nonetheless, if you really need to update the window while resizing, if you're using Windows, you can listen for the actual WM_SIZE event of Windows, redraw your screen, and update the "Windows"-window by calling RedrawWindow.
Here's a simple example:
import pygame
import win32gui
import win32con
def wndProc(oldWndProc, draw_callback, hWnd, message, wParam, lParam):
if message == win32con.WM_SIZE:
draw_callback()
win32gui.RedrawWindow(hWnd, None, None, win32con.RDW_INVALIDATE | win32con.RDW_ERASE)
return win32gui.CallWindowProc(oldWndProc, hWnd, message, wParam, lParam)
def main():
pygame.init()
screen = pygame.display.set_mode((320, 240), pygame.RESIZABLE | pygame.DOUBLEBUF)
def draw_game():
screen.fill(pygame.Color('black'))
pygame.draw.rect(screen, pygame.Color('red'), pygame.Rect(0,0,screen.get_width(),screen.get_height()).inflate(-10, -10))
pygame.display.flip()
oldWndProc = win32gui.SetWindowLong(win32gui.GetForegroundWindow(), win32con.GWL_WNDPROC, lambda *args: wndProc(oldWndProc, draw_game, *args))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
elif event.type == pygame.VIDEORESIZE:
pygame.display.set_mode((event.w, event.h), pygame.RESIZABLE| pygame.DOUBLEBUF)
draw_game()
if __name__ == '__main__':
main()
Default behaviour:
With RedrawWindow:

How to make the pygame mouse continue to return events using the pygame event loop

I would like to know how to make it so that when you hold down the pygame mouse, it continues getting events in the event loop.
I do not want to use pygame.mouse.get_pressed() because I want to also have a hold-down time to where it doesn't do anything.
Kind of like if you hold down a key in a text box in your browser: it types one key, then waits for about half a second, then starts typing a lot of keys really fast.
Also, I think it involves something before the main loop when the window is created or something, but I'm not sure.
I know there's a way to do this in pygame because I saw a Stack Overflow answer to it before, but after a while of searching, I cannot find it. If you have seen it or can find it, that is also appreciated too. This is my first time asking a question, so if I did anything wrong, please tell me.
Here is the code:
import pygame
WIDTH = 1000
HEIGHT = 800
WIN = pygame.display.set_mode()
def main():
run = True
clock = pygame.time.Clock()
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
print("the mouse was pressed")
WIN.fill((0, 0, 0))
pygame.display.update()
I would like to know how to make it so that when you hold down the pygame mouse, it continues getting events in the event loop.
Yo can't. However you can use pygame.mouse.get_pressed():
import pygame
WIDTH = 1000
HEIGHT = 800
WIN = pygame.display.set_mode()
def main():
run = True
clock = pygame.time.Clock()
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
buttons = pygame.mouse.get_pressed()
if any(buttons):
print("the mouse was pressed")
WIN.fill((0, 0, 0))
pygame.display.update()
The MOUSEBUTTONDOWN event occurs once when you click the mouse button and the MOUSEBUTTONUP event occurs once when the mouse button is released.
pygame.mouse.get_pressed() returns a list of Boolean values ​​that represent the current state (True or False) of all mouse buttons. The state of a button is True as long as a button is held down.

Pygame is not working in pycharm just a black window pops up

I'm using this bit of code in pycharm, but none of the print for events works(the quit, mouse button click or key pressing on keyboard)
Although I see the pygame window but the events doesn't work.
I also used the get() instead of wait() but still no luck.
any ideas?
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
while True:
event = pygame.event.wait()
if event.type == pygame.QUIT:
print('Quit')
if event.type == pygame.KEYDOWN:
print('Key Down')
print(event.key)
print(event.unicode)
if event.type == pygame.KEYUP:
print('Key Up')
print(event.key)
if event.type == pygame.MOUSEBUTTONDOWN:
print('Mouse Button Down')
print(event.pos)
print(event.button == pygame.BUTTON_RIGHT)
print(event.button == pygame.BUTTON_LEFT)
if event.type == pygame.MOUSEBUTTONUP:
print('Mouse Button Up')
print(event.pos)
print(event.button == pygame.BUTTON_RIGHT)
print(event.button == pygame.BUTTON_LEFT)
if event.type == pygame.MOUSEMOTION:
print('Mouse Motion')
print(event.pos)
print(event.rel)
UPDATE
I found out that it's a problem with pycharm.
when I run any code with pygame just a black pygame windows pop up, it doesn't run any other code(events, filling window with color ,...). Even the pygame window is not in dimensions that I've given.
Here another code example.
import pygame
pygame.init()
screen = pygame.display.set_mode((200, 200))
red = (255, 0, 0)
screen.fill(red)
pygame.display.update()
pygame.time.delay(10000)
when I run it in VS code:
Vs code pygame test
and when I run it in pycharm :( :
Pycharm pygame test
also I'm defining the same Interpreter for both VS code and pycharm and I've already reinstalled pygame package.
You can try to use a full game loop, as this would update the window repeatedly.
Try:
import pygame
pygame.init()
screen = pygame.display.set_mode((200, 200))
red = (255, 0, 0)
running = True
while running:
screen.fill(red)
pygame.display.flip()
for event in pygame.event.get():
if event.type = pygame.QUIT:
running = False
pygame.quit()
i was using pycharm but all the code did not wok so i right clicked it with the mouse and selected run in python cnsole.
OR ::::::::::::
SHIFT + ALT + E

Keyboard Controlls for video game--python

I'm new to python/pygame and I'm trying to make a game. Basically it is a space ship floating around in space(it will be a scrolling background) pointing towards the mouse/crosshair. on clicking it will shoot bullets. there will be flying enemies which need AI and clinging enemies which need AI. Also liquids need to "flow." Collision detection for running into walls/bullets,enemies/floor. And lastly I will need a menu GUI (if i used gui in the right context.)
But right now, i would like to move the background (or for now the sprite) with keyboard controls. also how do I do a stretched image for the background?
This is what i've got:
import pygame, random, sys, time
pygame.init()
SIZE = [1000, 1000]
screen = pygame.display.set_mode(SIZE)
crosshair = pygame.image.load('crosshair.jpg')
player = pygame.image.load('spaceship.jpg')
pygame.display.set_caption("Solar Warfare")
WHITE = [255, 255, 255]
mouse_pos = []
spaceshipX = 0
spaceshipY = 0
done = False
pygame.mouse.set_visible(False)
while not done:
for event in pygame.event.get():
if event.type == pygame.MOUSEMOTION:
mouse_pos = pygame.mouse.get_pos([])
screen.blit(crosshair, (mouse_pos[0], mouse_pos[1]))
pygame.display.flip()#What is the other way to
#update the screen?
if event.type == pygame.QUIT:
done = True
if event.type == pygame.K_RIGHT:
spaceshipX += 1
screen.fill(WHITE)
screen.blit(player, (spaceshipX, spaceshipY))
screen.blit(crosshair, (mouse_pos))
pygame.display.flip()
pygame.quit()
I would like to add a scrolling background.
I also need AI for the enemies, but thats later. Same with the Main Menu and levels and bosses/features etc...
I talk alot XD

PyGame - Plotting a Pixel and Printing out it's coordinates

This may seem like a really easy question to answer, but I'm just a beginner in need of quick help.
I'm trying to create a program that when you click somewhere on the pyGame window, it'll print out that you hit it with the left button on the mouse, and also print out co-ordinates of where it was pressed. I've got this already. I'm having problems with making it plot the pixel on the pyGame window. Basically, I want it to draw a pixel where I pressed down on the pyGame window.
#!/usr/bin/env python
#import the module for use
import pygame
#setting up some variables
running = 1
LEFT = 1
#Set up the graphics area/screen
screen=pygame.display.set_mode((640,400))
#continuous loop to keep the graphics running
while running==1:
event=pygame.event.poll()
if event.type==pygame.QUIT:
running=0
pygame.quit()
elif event.type==pygame.MOUSEBUTTONDOWN and event.button==LEFT:
print "You pressed the left mouse button at (%d,%d)" %event.pos
elif event.type==pygame.MOUSEBUTTONUP and event.button==LEFT:
print "You released the left mouse button at (%d,%d)" %event.pos
Try setting the color of each pixel when you receive the mouse down event.
elif event.type==pygame.MOUSEBUTTONDOWN and event.button==LEFT:
print "You pressed the left mouse button at (%d,%d)" %event.pos
screen.set_at((event.pos.x, event.pos.y), pygame.Color(255,0,0,255))
Note that this will temporarily lock and unlock the Surface as needed.
I edited Aesthete's code to a working standalone example:
Depending what you are doing, get/setting individual pixels can be slow. ( There is Surfarray and Pixelarray if you need to. )
import pygame
from pygame.locals import *
class Game(object):
done = False
def __init__(self, width=640, height=480):
pygame.init()
self.width, self.height = width, height
self.screen = pygame.display.set_mode((width, height))
# start with empty screen, since we modify it every mouseclick
self.screen.fill(Color("gray50"))
def main_loop(self):
while not self.done:
# events
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT: self.done = True
elif event.type == KEYDOWN:
if event.key == K_ESCAPE: self.done = True
elif event.type == MOUSEMOTION:
pass
elif event.type == MOUSEBUTTONDOWN and event.button == 1:
print "Click: ({})".format(event.pos)
self.screen.set_at(event.pos, Color("white"))
# draw
pygame.display.flip()
if __name__ == "__main__":
g = Game()
g.main_loop()

Categories

Resources