Click in specified place without moving mouse error - python

So I have been looking for multiple ways to perform a "click" without actually moving the mouse. After hours of searching, I came upon these two pages:
ctypes mouse_events
and
https://schurpf.com/python-mouse-control/
where there's some code that can apparently perform a click without moving the mouse.
The code seems to come from the same person, but https://schurpf.com/python-mouse-control/ seems more up to date with the "Added functions".
I tried fixing it for a while but didn't get anywhere and am stuck with the following script
import win32gui, win32api, win32con, ctypes
class Mouse:
"""It simulates the mouse"""
MOUSEEVENTF_MOVE = 0x0001 # mouse move
MOUSEEVENTF_LEFTDOWN = 0x0002 # left button down
MOUSEEVENTF_LEFTUP = 0x0004 # left button up
MOUSEEVENTF_RIGHTDOWN = 0x0008 # right button down
MOUSEEVENTF_RIGHTUP = 0x0010 # right button up
MOUSEEVENTF_MIDDLEDOWN = 0x0020 # middle button down
MOUSEEVENTF_MIDDLEUP = 0x0040 # middle button up
MOUSEEVENTF_WHEEL = 0x0800 # wheel button rolled
MOUSEEVENTF_ABSOLUTE = 0x8000 # absolute move
SM_CXSCREEN = 0
SM_CYSCREEN = 1
def _do_event(self, flags, x_pos, y_pos, data, extra_info):
"""generate a mouse event"""
x_calc = 65536 * x_pos / ctypes.windll.user32.GetSystemMetrics(self.SM_CXSCREEN) + 1
y_calc = 65536 * y_pos / ctypes.windll.user32.GetSystemMetrics(self.SM_CYSCREEN) + 1
return ctypes.windll.user32.mouse_event(flags, x_calc, y_calc, data, extra_info)
def _get_button_value(self, button_name, button_up=False):
"""convert the name of the button into the corresponding value"""
buttons = 0
if button_name.find("right") >= 0:
buttons = self.MOUSEEVENTF_RIGHTDOWN
if button_name.find("left") >= 0:
buttons = buttons + self.MOUSEEVENTF_LEFTDOWN
if button_name.find("middle") >= 0:
buttons = buttons + self.MOUSEEVENTF_MIDDLEDOWN
if button_up:
buttons = buttons << 1
return buttons
def move_mouse(self, pos):
"""move the mouse to the specified coordinates"""
(x, y) = pos
old_pos = self.get_position()
x = x if (x != -1) else old_pos[0]
y = y if (y != -1) else old_pos[1]
self._do_event(self.MOUSEEVENTF_MOVE + self.MOUSEEVENTF_ABSOLUTE, x, y, 0, 0)
def press_button(self, pos=(-1, -1), button_name="left", button_up=False):
"""push a button of the mouse"""
self.move_mouse(pos)
self._do_event(self.get_button_value(button_name, button_up), 0, 0, 0, 0)
def click(self, pos=(-1, -1), button_name= "left"):
"""Click at the specified placed"""
## self.move_mouse(pos)
self._do_event(self._get_button_value(button_name, False)+self._get_button_value(button_name, True), 0, 0, 0, 0)
def double_click (self, pos=(-1, -1), button_name="left"):
"""Double click at the specifed placed"""
for i in xrange(2):
self.click(pos, button_name)
def get_position(self):
"""get mouse position"""
return win32api.GetCursorPos()
#-----------------------------------------------------------------------------------------
#Added functions
#-----------------------------------------------------------------------------------------
def invisible_click(self,pos=(-1, -1), button_name="left"):
"""Click in specified place without moving mouse"""
xcur,ycur = win32gui.GetCursorPos()
ctypes.windll.user32.SetCursorPos(pos[0],pos[1])
self.click(pos,button_name)
ctypes.windll.user32.SetCursorPos(xcur,ycur)
def invisible_click_rel(self,handle,pos, button_name="left"):
"""Click in window coordinates without moving mouse"""
#get window info
xleft, ytop, xright, ybottom = win32gui.GetWindowRect(handle)
xcur,ycur = win32gui.GetCursorPos()
ctypes.windll.user32.SetCursorPos(pos[0]+xleft,pos[1]+ytop)
self.click((pos[0]+xleft,pos[1]+ytop),button_name)
ctypes.windll.user32.SetCursorPos(xcur,ycur)
if __name__ == '__main__':
p = (500,500)
print (win32gui.GetForegroundWindow())
mouse = Mouse()
mouse.invisible_click(p)
What I am trying to do is trigger the invisible_click function of the Mouse class so that it performs an "invisible click" at position 500,500.
The error I am getting with the code above is
File "C:\Users\MyName\Desktop\test1del\Future.py", line 21, in _do_event
return ctypes.windll.user32.mouse_event(flags, x_calc, y_calc, data, extra_info)
ctypes.ArgumentError: argument 2: <class 'TypeError'>: Don't know how to convert parameter 2
Sorry if it's something obvious that I am missing, I would really appreciate the help!
Thanks for reading

File "C:\Users\MyName\Desktop\test1del\Future.py", line 21, in
_do_event
return ctypes.windll.user32.mouse_event(flags, x_calc, y_calc, data, extra_info) ctypes.ArgumentError: argument 2: : Don't know how to convert parameter 2
This error message indicate that parameters x_calc and y_calc passed in function mouse_event have wrong type. They are float but unsigned int required .
Try the following code:
import math
#...
x_calc = math.floor(65536 * x_pos / ctypes.windll.user32.GetSystemMetrics(self.SM_CXSCREEN) + 1)
y_calc = math.floor(65536 * y_pos / ctypes.windll.user32.GetSystemMetrics(self.SM_CYSCREEN) + 1)
Note: mouse_event function has been superseded. Use SendInput instead.

Related

Lag while drawing lines with the Python Arcade Library

I've been migrating from Pygame to Arcade and overall it's much better. That said, the method I was using to draw the lines of my track for my car game in Pygame is exorbitantly laggy in Arcade. I know it's lagging from drawing all the lines, I'm just wondering if there's a better way to do it that doesn't cause so much lag.
import arcade
import os
import math
import numpy as np
SPRITE_SCALING = 0.5
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "Move Sprite by Angle Example"
MOVEMENT_SPEED = 5
ANGLE_SPEED = 5
class Player(arcade.Sprite):
""" Player class """
def __init__(self, image, scale):
""" Set up the player """
# Call the parent init
super().__init__(image, scale)
# Create a variable to hold our speed. 'angle' is created by the parent
self.speed = 0
def update(self):
# Convert angle in degrees to radians.
angle_rad = math.radians(self.angle)
# Rotate the ship
self.angle += self.change_angle
# Use math to find our change based on our speed and angle
self.center_x += -self.speed * math.sin(angle_rad)
self.center_y += self.speed * math.cos(angle_rad)
def upgraded_distance_check(player_sprite, point_arrays, distance_cap):
center_coord = player_sprite.center
intersect_array = []
distance_array = []
sensor_array = player_sprite.points
for sensor in sensor_array:
intersect_array.append([-10000, -10000])
for point_array in point_arrays:
for i in range(len(point_array[:-1])):
v = line_intersection(
[sensor, center_coord], [point_array[i], point_array[i + 1]]
)
if v == (None, None):
continue
if (
(point_array[i][0] <= v[0] and point_array[i + 1][0] >= v[0])
or (point_array[i][0] >= v[0] and point_array[i + 1][0] <= v[0])
) and (
(point_array[i][1] <= v[1] and point_array[i + 1][1] >= v[1])
or (point_array[i][1] >= v[1] and point_array[i + 1][1] <= v[1])
):
if intersect_array[-1] is None or math.sqrt(
(intersect_array[-1][0] - center_coord[0]) ** 2
+ (intersect_array[-1][1] - center_coord[1]) ** 2
) > math.sqrt(
(v[0] - center_coord[0]) ** 2
+ (v[1] - center_coord[1]) ** 2
):
if not is_between(sensor, center_coord, v):
intersect_array[-1] = v
for i in range(len(sensor_array)):
if distance(sensor_array[i], intersect_array[i]) > distance_cap:
intersect_array[i] = None
distance_array.append(None)
else:
distance_array.append(distance(sensor_array[i], intersect_array[i]))
return intersect_array
class MyGame(arcade.Window):
"""
Main application class.
"""
def __init__(self, width, height, title):
"""
Initializer
"""
# Call the parent class initializer
super().__init__(width, height, title)
# Set the working directory (where we expect to find files) to the same
# directory this .py file is in. You can leave this out of your own
# code, but it is needed to easily run the examples using "python -m"
# as mentioned at the top of this program.
file_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(file_path)
# Variables that will hold sprite lists
self.player_list = None
# Set up the player info
self.player_sprite = None
# Set the background color
arcade.set_background_color(arcade.color.WHITE)
def setup(self):
""" Set up the game and initialize the variables. """
# Sprite lists
self.player_list = arcade.SpriteList()
# Set up the player
self.player_sprite = Player(":resources:images/space_shooter/playerShip1_orange.png", SPRITE_SCALING)
self.player_sprite.center_x = SCREEN_WIDTH / 2
self.player_sprite.center_y = SCREEN_HEIGHT / 2
self.player_list.append(self.player_sprite)
#Setup all the array BS
self.track_arrays = []
self.drawing = False
def on_draw(self):
"""
Render the screen.
"""
# This command has to happen before we start drawing
arcade.start_render()
# Draw all the sprites.
# for i, ele in enumerate(self.player_sprite.points):
# arcade.draw_circle_filled(ele[0], ele[1], 7, arcade.color.AO)
self.player_list.draw()
if len(self.track_arrays) > 0 and len(self.track_arrays[0]) > 2:
for track_array in self.track_arrays:
for i in range(len(track_array[:-1])):
arcade.draw_line(track_array[i][0], track_array[i][1], track_array[i+1][0], track_array[i+1][1], arcade.color.BLACK, 1)
def on_update(self, delta_time):
""" Movement and game logic """
# Call update on all sprites (The sprites don't do much in this
# example though.)
self.player_list.update()
# print(self.drawing)
# print(self.player_sprite.points)
def on_key_press(self, key, modifiers):
"""Called whenever a key is pressed. """
# Forward/back
if key == arcade.key.UP:
self.player_sprite.speed = MOVEMENT_SPEED
elif key == arcade.key.DOWN:
self.player_sprite.speed = -MOVEMENT_SPEED
# Rotate left/right
elif key == arcade.key.LEFT:
self.player_sprite.change_angle = ANGLE_SPEED
elif key == arcade.key.RIGHT:
self.player_sprite.change_angle = -ANGLE_SPEED
def on_key_release(self, key, modifiers):
"""Called when the user releases a key. """
if key == arcade.key.UP or key == arcade.key.DOWN:
self.player_sprite.speed = 0
elif key == arcade.key.LEFT or key == arcade.key.RIGHT:
self.player_sprite.change_angle = 0
def on_mouse_press(self, x, y, button, modifiers):
"""
Called when the user presses a mouse button.
"""
self.track_arrays.append([])
self.drawing = True
def on_mouse_release(self, x, y, button, modifiers):
"""
Called when a user releases a mouse button.
"""
self.drawing = False
def on_mouse_motion(self, x, y, dx, dy):
""" Called to update our objects. Happens approximately 60 times per second."""
if self.drawing:
self.track_arrays[-1].append([x,y])
def main():
""" Main method """
window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
window.setup()
arcade.run()
if __name__ == "__main__":
main()

Label Position, Resize Background And Hide Title Bar

I'm trying to better understand Pyglet and I'm using a script posted by Torxed in my previous question. I started to modify it until I reached this point:
import pyglet, datetime, os
from pyglet.gl import *
from collections import OrderedDict
from time import time
from pathlib import Path
key = pyglet.window.key
class main(pyglet.window.Window):
#Variable Display
Fullscreen = False
CountDisplay = 0
setDisplay0 = (1024, 576)
setDisplay1 = (800, 600)
setDisplay2 = (1024, 768)
setDisplay3 = (1280, 720)
setDisplay4 = (1280, 1024)
setDisplay5 = (1366, 768)
setDisplay6 = (1920, 1080)
#Variable Info
infoHidden = False
title = "Pokémon Life And Death: Esploratori Del Proprio Destino"
build = "Versione: 0.0.0"
keyPrint = "Nessuno"
MousekeyPrint = "Nessuno"
infoFullscreen = "Disattivo"
infoDisplay = "1024, 576"
def __init__ (self, width=1024, height=576, fullscreen=False, *args, **kwargs):
super(main, self).__init__(width, height, fullscreen, *args, **kwargs)
platform = pyglet.window.get_platform()
display = platform.get_default_display()
screen = display.get_default_screen()
self.infoScreen = (screen.width, screen.height)
self.xDisplay = int(screen.width / 2 - self.width / 2)
self.yDisplay = int(screen.height / 2 - self.height / 2)
self.set_location(self.xDisplay, self.yDisplay)
self.sprites = OrderedDict()
self.spritesInfo = OrderedDict()
#Information Hidden
#Title
self.spritesInfo["title_label"] = pyglet.text.Label(self.title, x=self.infoPos("x", 0), y=self.infoPos("y", 0))
#Build Version
self.spritesInfo["build_label"] = pyglet.text.Label(self.build, x=self.infoPos("x", 0), y=self.infoPos("y", 20))
#Fullscreen
self.spritesInfo["fullscreen_label"] = pyglet.text.Label("Fullscreen: " + self.infoFullscreen, x=self.infoPos("x", 0), y=self.infoPos("y", 40))
#Display
self.spritesInfo["screen_label"] = pyglet.text.Label("Display: " + self.infoDisplay, x=self.infoPos("x", 0), y=self.infoPos("y", 60))
#FPS
self.spritesInfo["fps_label"] = pyglet.text.Label("FPS: 0", x=self.infoPos("x", 0), y=self.infoPos("y", 80))
self.last_update = time()
self.fps_count = 0
#Mouse Position
self.mouse_x = 0
self.mouse_y = 0
self.spritesInfo["mouse_label"] = pyglet.text.Label(("Mouse Position (X,Y): " + str(self.mouse_x) + "," + str(self.mouse_y)), x=self.infoPos("x", 0), y=self.infoPos("y", 100))
#Player Position
self.player_x = 0
self.player_y = 0
self.spritesInfo["player_label"] = pyglet.text.Label(("Player Position (X,Y): " + str(self.player_x) + "," + str(self.player_y)), x=self.infoPos("x", 0), y=self.infoPos("y", 120))
#Key Press
self.keys = OrderedDict()
self.spritesInfo["key_label"] = pyglet.text.Label(("Key Press: " + self.keyPrint), x=self.infoPos("x", 0), y=self.infoPos("y", 140))
#Mouse Press
self.spritesInfo["MouseKey_label"] = pyglet.text.Label(("Mouse Key Press: " + self.MousekeyPrint), x=self.infoPos("x", 0), y=self.infoPos("y", 160))
self.alive = 1
def infoPos(self, object, ny):
posInfo = self.get_size()
if object is "x":
elab = 10
elif object is "y":
elab = posInfo[1] - 20 - ny
else:
elab = 0
return elab
def on_draw(self):
self.render()
def on_close(self):
self.alive = 0
def on_mouse_motion(self, x, y, dx, dy):
self.mouse_x = x
self.mouse_y = y
def on_mouse_release(self, x, y, button, modifiers):
self.MousekeyPrint = "Nessuno"
def on_mouse_press(self, x, y, button, modifiers):
self.MousekeyPrint = str(button)
def on_mouse_drag(self, x, y, dx, dy, button, modifiers):
self.drag = True
print('Dragging mouse at {}x{}'.format(x, y))
def on_key_release(self, symbol, modifiers):
self.keyPrint = "Nessuno"
try:
del self.keys[symbol]
except:
pass
def on_key_press(self, symbol, modifiers):
if symbol == key.ESCAPE:
self.alive = 0
if symbol == key.F2:
datanow = datetime.datetime.now()
if not Path("Screenshot").is_dir():
os.makedirs("Screenshot")
pyglet.image.get_buffer_manager().get_color_buffer().save("Screenshot/"+str(datanow.day)+"-"+str(datanow.month)+"-"+str(datanow.year)+"_"+str(datanow.hour)+"."+str(datanow.minute)+"."+str(datanow.second)+".png")
if symbol == key.F3:
if self.infoHidden:
self.infoHidden = False
else:
self.infoHidden = True
if symbol == key.F10:
self.CountDisplay += 1
if self.CountDisplay == 1:
size = self.setDisplay1
elif self.CountDisplay == 2:
size = self.setDisplay2
elif self.CountDisplay == 3:
size = self.setDisplay3
elif self.CountDisplay == 4:
size = self.setDisplay4
elif self.CountDisplay == 5:
size = self.setDisplay5
elif self.CountDisplay == 6:
size = self.setDisplay6
else:
self.CountDisplay = 0
size = self.setDisplay0
self.set_size(size[0], size[1])
self.infoDisplay = str(size[0]) + "," + str(size[1])
pos = (int(self.infoScreen[0] / 2 - size[0] / 2), int(self.infoScreen[1] / 2 - size[1] / 2))
self.set_location(pos[0], pos[1])
if symbol == key.F11:
if self.Fullscreen:
self.Fullscreen = False
self.set_fullscreen(False)
self.infoFullscreen = "Disattivo"
else:
self.Fullscreen = True
self.set_fullscreen(True)
self.infoFullscreen = "Attivo"
self.keyPrint = str(symbol)
self.keys[symbol] = True
def pre_render(self):
pass
def render(self):
self.clear()
#FPS
self.fps_count += 1
if time() - self.last_update > 1:
self.spritesInfo["fps_label"].text = "FPS: " + str(self.fps_count)
self.fps_count = 0
self.last_update = time()
#Mouse Position
self.spritesInfo["mouse_label"].text = "Mouse Position (X,Y): " + str(self.mouse_x) + "," + str(self.mouse_y)
#Player Position
self.spritesInfo["player_label"].text = "Player Position (X,Y): " + str(self.player_x) + "," + str(self.player_y)
#Key Press
self.spritesInfo["key_label"].text = "Key Press: " + self.keyPrint
#Mouse Press
self.spritesInfo["MouseKey_label"].text = "Mouse Key Press: " + self.MousekeyPrint
#Fullscreen
self.spritesInfo["fullscreen_label"].text = "Fullscreen: " + self.infoFullscreen
#Display
self.spritesInfo["screen_label"].text = "Display: " + self.infoDisplay
#self.bg.draw()
self.pre_render()
for sprite in self.sprites:
self.sprites[sprite].draw()
if self.infoHidden:
for spriteInfo in self.spritesInfo:
self.spritesInfo[spriteInfo].draw()
self.flip()
def run(self):
while self.alive == 1:
self.render()
event = self.dispatch_events()
if __name__ == '__main__':
x = main()
x.run()
But now I find myself in front of a point where I can not proceed in Pyglet alone.
I can not understand how I can change the coordinates of the "label" every time the window size changes.
I would like to be able to use an image as a background and adapt it to the size of the window (basic the image is 1920x1080, ie the maximum window size). The problem is that I did not find much on this subject. I state that what I'm working on is 2D, not 3D. I had found a possible solution in another question, always answered by Torxed on the resizing of an image, but in some tests before this, after having adapted it, it did not work. So I do not know where to bang my head sincerely. In Pygame it was easy to use "pygame.transform.scale", but in Pyglet I would not know.
Finally, I tried both on the Pyglet wiki and on the web, but I did not find anything. How can I delete or hide the window title bar? In Pygame, you could with the flags. Is it possible to do this also with Pyglet?
EDIT:
I forgot to ask another question. When I press a key on the keyboard or mouse, the information displayed with F3 is printed in the corresponding key number. Is there a way to replace the number with the name of the button? For example, 97 is replaced with "A"? Obviously, I mean if there's a way without having to list all the keys and put the "if" statement for everyone.
EDIT2:
It seems like the script posted, the def on_resize (self, width, height) part does not like it very much. Let me explain, if for itself the function works correctly. The problem is that if I insert it, the labels, once pressed F3, do not appear. I tried to test it using print in several places and it seems that the only instruction that is not executed is self.spritesInfo [spriteInfo] .draw ()

Displaying movement tiles for a Python game

I am trying to create a simple tactical RPG in python, similar to Fire Emblem or Advanced Wars, but in ASCII. I have been following this tutorial, which uses the libtcod module, and modifying the tutorial code for my own purposes
Right now I am struck trying to display movement tiles for each character. Basically I want the game to display the tiles each character can move to, whenever the user clicks his mouse over that character. I have created a function (get_total_squares) that generates the coordinates of the tiles to be highlighted based on the character's coordinates and movement range (hard-coded to 5, for now) and a function (show_move_tiles) to highlight these tiles. To record the click coordinates I have another function target_tile and a function to see if the coordinates match with a character's (target_character)
The program runs without errors, but clicking the mouse over a character does nothing (no tiles are shown).
Here is the code:
import libtcodpy as libtcod
#actual size of the window
SCREEN_WIDTH = 80
SCREEN_HEIGHT = 50
#size of the map
MAP_WIDTH = 80
MAP_HEIGHT = 43
LIMIT_FPS = 20 #20 frames-per-second maximum
color_dark_wall = libtcod.Color(0, 0, 50)
color_dark_ground = libtcod.Color(5, 50, 0)
color_move_tile = libtcod.Color (100, 0, 0)
class Tile:
#a tile of the map and its properties
def __init__(self, blocked, block_sight = None):
self.blocked = blocked
#by default, if a tile is blocked, it also blocks sight
if block_sight is None: block_sight = blocked
self.block_sight = block_sight
def target_tile():
#return the position of a tile left-clicked, or (None,None) if right-clicked.
global key, mouse
while True:
libtcod.console_flush()
libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS|libtcod.EVENT_MOUSE, key, mouse)
render_all()
(x, y) = (mouse.cx, mouse.cy)
if mouse.rbutton_pressed or key.vk == libtcod.KEY_ESCAPE:
return (None, None) #cancel if the player right-clicked or pressed Escape
if mouse.lbutton_pressed:
return (x, y)
print "works!"
def target_character():
#Shows movement tiles if character is on click-coordinate
(x, y) = target_tile()
#return the first clicked character
for obj in objects:
if obj.x == x and obj.y == y:
obj.show_move_tiles()
def make_map():
global map
#fill map with "unblocked" tiles
map = [[ Tile(False)
for y in range(MAP_HEIGHT) ]
for x in range(MAP_WIDTH) ]
map[30][22].blocked = True
map[30][22].block_sight = True
map[50][22].blocked = True
map[50][22].block_sight = True
class Object:
#this is a generic object: the player, a monster, an item, the stairs...
#it's always represented by a character on screen.
def __init__(self, x, y, char, color):
self.x = x
self.y = y
self.char = char
self.color = color
def move(self, dx, dy):
#move by the given amount
if not map[self.x + dx][self.y + dy].blocked:
self.x += dx
self.y += dy
def draw(self):
#set the color and then draw the character that represents this object at its position
libtcod.console_set_default_foreground(con, self.color)
libtcod.console_put_char(con, self.x, self.y, self.char, libtcod.BKGND_NONE)
def show_move_tiles(self):
global mouse
global color_move_tile
(x,y) = (mouse.cx, mouse.cy)
coord_in_range = get_total_squares(5, self.x, self.y)
for [x,y] in coord_in_range:
if [x,y] is not [self.x, self.y]:
libtcod.console_set_char_background(con, x, y, color_move_tile, libtcod.BKGND_SET)
def clear(self):
#erase the character that represents this object
libtcod.console_put_char_ex(con, self.x, self.y, '.', libtcod.white, libtcod.black)
def handle_keys():
#key = libtcod.console_check_for_keypress() #real-time
global key #turn-based
if key.vk == libtcod.KEY_ENTER and key.lalt:
#Alt+Enter: toggle fullscreen
libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())
elif key.vk == libtcod.KEY_ESCAPE:
return True #exit game
def get_total_squares(dist, playerx, playery):
coord_in_range = []
for x in range(-dist,dist+1):
for y in range(-dist, dist+1):
if abs(x)+abs(y) <= dist:
coord_in_range.append([playerx+x, playery+y])
return coord_in_range
def render_all():
global color_dark_wall
global color_dark_ground
#go through all tiles, and set their background color
for y in range(MAP_HEIGHT):
for x in range(MAP_WIDTH):
wall = map[x][y].block_sight
if wall:
libtcod.console_put_char_ex(con, x, y, '#', libtcod.white, libtcod.black)
else:
libtcod.console_put_char_ex(con, x, y, '.', libtcod.white, libtcod.black)
#draw all objects in the list and show movement if mouse hovers over player
for item in objects:
item.draw()
if mouse.cx == item.x and mouse.cy == item.y:
item.show_move_tiles()
#blit the contents of "con" to the root console
libtcod.console_blit(con, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0)
#############################################
# Initialization & Main Loop
#############################################
libtcod.console_set_custom_font('arial10x10.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)
libtcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, 'python/libtcod tutorial', False)
libtcod.sys_set_fps(LIMIT_FPS)
con = libtcod.console_new(SCREEN_WIDTH, SCREEN_HEIGHT)
#create object representing the player
player = Object(30, 15, '#', libtcod.white)
#create an NPC
npc = Object(SCREEN_WIDTH/2 - 5, SCREEN_HEIGHT/2, '#', libtcod.yellow)
#the list of objects with those two
objects = [npc, player]
make_map()
mouse = libtcod.Mouse()
key = libtcod.Key()
while not libtcod.console_is_window_closed():
libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS|libtcod.EVENT_MOUSE,key,mouse)
#render the screen
render_all()
target_tile()
libtcod.console_flush()
#erase all objects at their old locations, before they move
for object in objects:
object.clear()
#handle keys and exit game if needed
exit = handle_keys()
if exit:
break
EDIT: I solved the previous problem of the movement tiles not showing up when I hovered the mouse over the character, but have updated the problem with a new one: trying to toggle the movement tiles on and off with a mouse click

Python pygame Detect if mouse is over non transparent part of surface

I am trying to make a UI for my game and there are some curves to the UI. Now I can detect collision between two surfaces. I can detect by pixel between two sprites, but it seems mouse detection by pixel is alluding me. Basically I want to detect when the mouse is over the UI and then ignore everything below that while getting the UI.
This is a picture of what I have so far. If you notice the pink square the mouse is over the GUI while the yellow selector box is over a tile. The yellow selector is a box frame over a tile.
I am using pygame with openGL but at this point I am looking for ANY solution to this. I can adapt pretty easily as I am not new to programming and pretty much looking for any solution.
Also I would post the code but to much code to post so if thing specific is needed let me know.
One thing to note is that the GUI is flexable in that the upper left area will slide in and out. Also the white is just placeholder so final colors are not used and would be difficult to check. Is it possible to get the surface elements under the mouse when clicked by z order?
Texture
import pygame
from OpenGL.GL import *
from OpenGL.GLU import *
class Texture(object):
image = None
rect = None
src = ''
x = 0
y = 0
'''
zOrder Layers
0 - background
1 -
2 -
3 - Tile Selector
s - Tiles
5 -
6 -
7 - Panels
8 - Main Menu
9 - GUI Buttons
10 -
'''
def __init__(self, src):
self.src = src
self.image = pygame.image.load(src)
self.image.set_colorkey(pygame.Color(255,0,255,0))
self.rect = self.image.get_rect()
texdata = pygame.image.tostring(self.image,"RGBA",0)
# create an object textures
self.texid = glGenTextures(1)
# bind object textures
glBindTexture(GL_TEXTURE_2D, self.texid)
# set texture filters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
# Create texture image
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,self.rect.w,self.rect.h,0,GL_RGBA,GL_UNSIGNED_BYTE,texdata)
self.newList = glGenLists(2)
glNewList(self.newList, GL_COMPILE)
glBindTexture(GL_TEXTURE_2D, self.texid)
glBegin(GL_QUADS)
glTexCoord2f(0, 0); glVertex3f(0, 0 ,0)
glTexCoord2f(0, 1); glVertex3f(0, self.rect.h, 0)
glTexCoord2f(1, 1); glVertex3f(self.rect.w, self.rect.h, 0)
glTexCoord2f(1, 0); glVertex3f(self.rect.w, 0, 0)
glEnd()
glEndList()
def getImg(self):
return self.image
def getPos(self):
rect = self.getImg().get_rect()
pos = dict(x=self.x,y=self.y,w=rect[2],h=rect[3])
return pos
def draw(self,x,y,rotate=0):
glLoadIdentity()
self.x = int(x)
self.y = int(y-self.rect.h+32)
glTranslatef(x,y-self.rect.h+32,0)
glPushAttrib(GL_TRANSFORM_BIT)
glMatrixMode(GL_TEXTURE)
glLoadIdentity()
glRotatef(rotate,0,0,1)
glPopAttrib()
if glIsList(self.newList):
glCallList(self.newList)
gui Class
import hashlib, string, pygame
from classes.texture import Texture
'''
Created on Jun 2, 2013
#author: Joel
'''
class gui(object):
INSTANCES = 0 # Count of instances of buildings
ID = 0 # Building ID
TYPE = 0 # Building type
NAME = '' # name of Building
DESCRIPTION = '' # Description of building
IMAGE = '' # Image name of building
zOrder = 0
clickable = True
def __init__(self, Game, name = 'Building', description = '', image = 'panel'):
self.INSTANCES += 1
self.setName(name)
self.setDescription(description)
self.setImage(Game, Game.SETTING["DIR"]["IMAGES"] + Game.SETTING["THEME"] + '\\gui\\'+image+'.png')
self.setType(name.lower())
self.setZ(6)
def getDescription(self):
return self.DESCRIPTION
def setDescription(self, description):
self.DESCRIPTION = description
def getID(self):
return self.ID
def setID(self, i):
allchr = string.maketrans('','')
nodigits = allchr.translate(allchr, string.digits)
s = hashlib.sha224(i).hexdigest()
s = s.translate(allchr, nodigits)
self.ID = s[-16:]
def getImage(self):
return self.IMAGE
def setImage(self, Game, i):
self.IMAGE = Texture(Game.CWD + '\\' + i)
def getName(self):
return self.NAME
def setName(self, name):
self.NAME = name
def getType(self):
return self.TYPE
def setType(self, t):
self.TYPE = t
def click(self, x, y):
if pygame.mouse.get_pressed()[0] == 1:
if x > self.x and x < (self.x + self.rect.w):
if y > self.y and y < (self.y + self.rect.h):
print("Clicked: " + str(self.x) + ', ' + str(self.y) + ', ' + str(self.rect.w) + ', ' + str(self.rect.y))
def getClickable(self):
return self.clickable
def setClickable(self, c):
self.clickable = c
def getZ(self):
return self.zOrder
def setZ(self, z):
self.zOrder = z
You could create a mask of the UI (this would be easiest if the UI is contained in one surface which is then applied to the screen surface), and set the threshold of the mask to the appropriate value so that your transparent pixels are set to 0 in the mask.
http://www.pygame.org/docs/ref/mask.html#pygame.mask.from_surface
With the mask object's get_at((x,y)) function you can test if a specific pixel of the mask is set (a non-zero value is returned if the pixel is set).
http://www.pygame.org/docs/ref/mask.html#pygame.mask.Mask.get_at
If you pass in the mouse's position, you can verify that it is over a visible part of the UI if you receive a non-zero value.
Two possible answers:
1) Statically create a 2D array of True or False that is as big as the screen - True if clicking here would click on the UI, False if clicking here would not click on the UI. Test clicks against the position in this array.
2) Use the 'paint and check' algorithm (don't recall the real name). You know how when you draw to the screen you draw the background, then background objects, then foreground objects? You can use a similar trick to detect what object you have clicked on - draw the background in one solid colour, each object in another solid colour, each UI element in another solid colour, etc... and as long as each solid colour is unique, you can test what colour pixel is under the cursor in this buffer and use it to determine what was visible and clicked on by the mouse.
Okay I am thinking of this as the best option rather then some of the alternatives. Will keep everyone up to date if this works or not.
global click variable to store data in a dict
Objects have layer variable ranging from 1 to ? from lowest to greatest layer(similar to html zIndex)
Primary Loop
reset the global click var
click event get position
loop over clickable objects to get everything under mouse
loop over everything under mouse to get highest layer
Return for global click var
run click code in object.
Layer organization currently which can be modified.
zOrder Layers
background
na
Tiles
Tile Selector
na
na
Panels
Main Menu
GUI Buttons
na
Loop
for i in range(len(self.OBJECTS)):
#img = Texture(see op)
img = self.OBJECTS[i].IMAGE
print(img)
e = None
if self.OBJECTS[i].zOrder == 4: # is isometric image
# tx and ty are translated positions for screen2iso. See Below
if ((self.tx >= 0 and self.tx < self.SETTING['MAP_WIDTH']) and (self.ty >= 0 and self.ty < self.SETTING['MAP_HEIGHT'])):
# map_x and map_y are starting points for the map its self.
ix, iy = self.screen2iso(
(x - (self.map_x + (self.SETTING['TILE_WIDTH'] / 2))),
(y - (self.map_y))
)
imgx, imgy = self.screen2iso(
(img.x - (self.map_x + (self.SETTING['TILE_WIDTH'] / 2))),
(img.y - (self.map_y))
)
if (imgx+2) == ix:
if (imgy+1) == iy:
e = self.OBJECTS[i]
else:
continue
else:
continue
else: # Not an isometric image
if x > img.x and x < (img.x + img.rect[2]):
if y > img.y and y < (img.y + img.rect[3]):
#is click inside of visual area of image?
if self.getCordInImage(x, y, self.OBJECTS[i].IMAGE):
if self.getAlphaOfPixel(self.OBJECTS[i]) != 0:
e = self.OBJECTS[i]
else:
continue
else:
continue
else:
continue
if e != None:
if self.CLICKED['zOrder'] < e.getZ():
self.CLICKED['zOrder'] = e.getZ()
self.CLICKED['e'] = e
else:
continue
else:
continue
getCordInImage
def getCordInImage(self, x, y, t):
return [x - t.x, y - t.y]
getAlphaOfPixel
def getAlphaOfPixel(self, t):
mx,my = pygame.mouse.get_pos()
x,y = self.getCordInImage(mx,my,t.IMAGE)
#mask = pygame.mask.from_surface(t.IMAGE.image)
return t.IMAGE.image.get_at([x,y])[3]
screen2iso
def screen2iso(self, x, y):
x = x / 2
xx = (y + x) / (self.SETTING['TILE_WIDTH'] / 2)
yy = (y - x) / (self.SETTING['TILE_WIDTH'] / 2)
return xx, yy
iso2screen
def iso2screen(self, x, y):
xx = (x - y) * (self.SETTING['TILE_WIDTH'] / 2)
yy = (x + y) * (self.SETTING['TILE_HEIGHT'] / 2)
return xx, yy

ctypes mouse_events

ctypes.windll.user32.mouse_event(3, 0, 0, 0,0)
I'm messing around with mouse positions and stumbled upon this line which from what I understand emulates a mouse click. Does anyone have documentation to similar lines (such as right-click and so on)?
I have a small class that wraps the mouse management.
import win32gui, win32api, win32con, ctypes
class Mouse:
"""It simulates the mouse"""
MOUSEEVENTF_MOVE = 0x0001 # mouse move
MOUSEEVENTF_LEFTDOWN = 0x0002 # left button down
MOUSEEVENTF_LEFTUP = 0x0004 # left button up
MOUSEEVENTF_RIGHTDOWN = 0x0008 # right button down
MOUSEEVENTF_RIGHTUP = 0x0010 # right button up
MOUSEEVENTF_MIDDLEDOWN = 0x0020 # middle button down
MOUSEEVENTF_MIDDLEUP = 0x0040 # middle button up
MOUSEEVENTF_WHEEL = 0x0800 # wheel button rolled
MOUSEEVENTF_ABSOLUTE = 0x8000 # absolute move
SM_CXSCREEN = 0
SM_CYSCREEN = 1
def _do_event(self, flags, x_pos, y_pos, data, extra_info):
"""generate a mouse event"""
x_calc = 65536 * x_pos / ctypes.windll.user32.GetSystemMetrics(self.SM_CXSCREEN) + 1
y_calc = 65536 * y_pos / ctypes.windll.user32.GetSystemMetrics(self.SM_CYSCREEN) + 1
return ctypes.windll.user32.mouse_event(flags, x_calc, y_calc, data, extra_info)
def _get_button_value(self, button_name, button_up=False):
"""convert the name of the button into the corresponding value"""
buttons = 0
if button_name.find("right") >= 0:
buttons = self.MOUSEEVENTF_RIGHTDOWN
if button_name.find("left") >= 0:
buttons = buttons + self.MOUSEEVENTF_LEFTDOWN
if button_name.find("middle") >= 0:
buttons = buttons + self.MOUSEEVENTF_MIDDLEDOWN
if button_up:
buttons = buttons << 1
return buttons
def move_mouse(self, pos):
"""move the mouse to the specified coordinates"""
(x, y) = pos
old_pos = self.get_position()
x = x if (x != -1) else old_pos[0]
y = y if (y != -1) else old_pos[1]
self._do_event(self.MOUSEEVENTF_MOVE + self.MOUSEEVENTF_ABSOLUTE, x, y, 0, 0)
def press_button(self, pos=(-1, -1), button_name="left", button_up=False):
"""push a button of the mouse"""
self.move_mouse(pos)
self._do_event(self.get_button_value(button_name, button_up), 0, 0, 0, 0)
def click(self, pos=(-1, -1), button_name= "left"):
"""Click at the specified placed"""
self.move_mouse(pos)
self._do_event(self._get_button_value(button_name, False)+self._get_button_value(button_name, True), 0, 0, 0, 0)
def double_click (self, pos=(-1, -1), button_name="left"):
"""Double click at the specifed placed"""
for i in xrange(2):
self.click(pos, button_name)
def get_position(self):
"""get mouse position"""
return win32api.GetCursorPos()
Here is a small example:
import time
mouse = Mouse()
mouse.click((20, 10), "left")
time.sleep(2.0)
mouse.click((100, 100), "right")
I hope it helps
This is from http://blog.lazynice.net/?p=63.
The script detect the windows’s inactivity every minute. If the inactivity exceeds 5 minutes, it simply sends an mouse event that move the mouse a little, so the screensaver may think it comes from the user input then reset the timer. Just set the inactivity duration less than the screensaver’s waiting time then run it!
from ctypes import Structure, windll, c_uint, sizeof, byref
import time
class LASTINPUTINFO(Structure):
_fields_ = [('cbSize', c_uint), ('dwTime', c_uint)]
def get_idle_duration():
lastInputInfo = LASTINPUTINFO()
lastInputInfo.cbSize = sizeof(lastInputInfo)
windll.user32.GetLastInputInfo(byref(lastInputInfo))
millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime
return millis / 1000.0
while True:
d = get_idle_duration()
if d > 60 * 5:
windll.user32.mouse_event(1, 1, 1, 0, 0)
time.sleep(60)

Categories