why can i not click and drag circles on Python? - python

I want to click these 2 circle balls and drag them to mouse current mouse position but it is not working.
I just want to click and drag the balls with mouse.
some codes was not added(import pygame,draw a display, colors etc.)
import pygame
window = pygame.display.set_mode((800,400))
clock = pygame.time.Clock()
##bg = pygame.image.load("bgpool.png")
##window.blit(bg,(0,0))
black = (0,0,0)
yellow = (255,255,0)
class Circle:
def __init__(self,x,y,color,radius):
self.x = x
self.y = y
self.color = color
self.radius = radius
pygame.draw.circle(window, color,(x,y),radius)
def quitgame():
pygame.quit()
quit()
def loop():
cikis = False
while not cikis:
for event in pygame.event.get():
if event.type == pygame.QUIT:
cikis = True
pygame.quit()
quit()
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
bas = pygame.MOUSEBUTTONDOWN
window.fill((255,255,255))
main_circle = Circle(75,175,black,10)
aim_circle = Circle(375,175,yellow,10)
if click[0] == 1:
if mouse[0] >= main_circle.x and mouse[0] <= main_circle.x + main_circle.radius:
if mouse[1] >= main_circle.y and mouse[1] <= main_circle.y + main_circle.radius:
if click[0] == 1:
main_circle.x == mouse[0]
main_circle.y == mouse[1]
clock.tick(120)
pygame.display.update()
loop()
pygame.quit()
quit()

While click = pygame.mouse.get_pressed() works, it's very much recommended to use Pygame's events, like you have done for pygame.QUIT.
Because you didn't provide much code, I added the bare minimum to make the code runnable, and I commented every modification:
import pygame
pygame.init()
window = pygame.display.set_mode((700, 500))
class Circle:
def __init__(self, x, y, color, radius):
# Changed pos to contain both coordinates
self.pos = (x, y)
# Where the radius ends
self.x_boundary = (x - radius, x + radius)
self.y_boundary = (y - radius, y + radius)
self.color = color
self.radius = radius
def recalc_boundary(self):
# Recalculate the boundaries of the circle,
# this is needed whenever the circle is moved
self.x_boundary = (
self.pos[0] - self.radius, self.pos[0] + self.radius
)
self.y_boundary = (
self.pos[1] - self.radius, self.pos[1] + self.radius
)
# Single instantiation of our circle
# didn't add aim_circle because it is irrelevant
# in my answer
main_circle = Circle(75, 175, (255, 0, 0), 10)
# Small lambda function that'll take care of
# checking whether or not a point x is
# within two boundaries.
# This replaces your
# `if mouse[0] >= main_circle.x and mouse[0]
# <= main_circle.x + main_circle.radius:`
# lines
within = lambda x, low, high: low <= x <= high
# Boolean that attests to whether or not the
# user is clicking on our circle
selected = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
# Test for MOUSEBUTTONDOWN events
elif event.type == pygame.MOUSEBUTTONDOWN:
# Left mouse button
if event.button == 1:
pos = pygame.mouse.get_pos()
# Check if the mouse is within
# our circle's limits, to see if the
# user is trying to click on it
if (
within(pos[0], *main_circle.x_boundary)
and within(pos[1], *main_circle.y_boundary)
):
selected = True
elif event.type == pygame.MOUSEBUTTONUP:
# User released mouse buttons
selected = False
if selected:
# Move to mouse position when selected,
# the circle 'follows' the mouse
main_circle.pos = pygame.mouse.get_pos()
main_circle.recalc_boundary()
window.fill((0, 0, 0))
# Moved this draw call to outside
# your class definition
pygame.draw.circle(
window, main_circle.color,
main_circle.pos,
main_circle.radius
)
pygame.display.update()
Note: it's a bad idea to instantiate a new Circle object each game loop iteration, this'll consume lots of CPU for nothing. I believe you've done that because you placed your circle draw calls inside it, but you should really just move it out into the loop.

Related

how to compare 2 mouse positions in pygame

i have this code:
un = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
if event.type == pygame.MOUSEBUTTONUP:
x1, y1 = pygame.mouse.get_pos()
Player(PlayerX, PlayerY)
pygame.display.update()
i want to use the mouse x and the mouse y coordinates in both cases to see which one is bigger but i cant really use the coordinates since one of them always turns out undefined, how do i go about achieving this?
You can set a default position for the mouse, that corresponds to the slingshot being aimed foward. Make it like:
defx = 30 #Default x coordinate example
defy = 30 #Default y coordinate example
Then whenever you are comparing, you just get the difference just like you said.
But if you need to have the last mouse position, you can also make it like this:
lx, ly, x, y = 0, 0, 0, 0 #It's probably better to use two arrays here
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
lx, ly = x, y #This makes so that lx and ly are the last frame values of x and y
x, y = pygame.mouse.get_pos()
if event.type == pygame.MOUSEBUTTONUP:
x1, y1 = pygame.mouse.get_pos()
This way you can use lx and ly as the last x and y values.
I didn't really understand what you wanted to do on the mouse up part, but you can do the same using lx1 and ly1.
What you are doing will not work because you cannot simultaneously have mouse up and mouse down. What you can do is store the mouse position once when it is pressed down. Lets call this heldDownMomentPosition. Then on a mousebuttonup event anytime after that, you can calculate the difference between heldDownMomentPosition and current mouse position. This will give you the direction in which the slingshot bullet needs to go. I used this mechanism in a game I made a while ago, here it is with some modifications to make it minimal. It has a simple drag to make it stop too.
import pygame
window = pygame.display.set_mode((600, 600))
slingShotBullet = pygame.Surface((40, 40)).convert()
slingShotBullet.fill((255, 255, 255))
pos = [300, 300]
vel = [0, 0]
clock = pygame.time.Clock()
heldDownMomentPosition = None
while True:
dt = clock.tick(60) * 0.001 #delta time in s
mousePressed = pygame.mouse.get_pressed()
mousePos = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
if heldDownMomentPosition is None:
if pygame.Rect(*pos, 40, 40).collidepoint(mousePos):
heldDownMomentPosition = pos[0] + 20, pos[1] + 20
if event.type == pygame.MOUSEBUTTONUP:
if heldDownMomentPosition is not None:
vel = [heldDownMomentPosition[0] - mousePos[0], heldDownMomentPosition[1] - mousePos[1]]
heldDownMomentPosition = None
vel[0] *= 0.99
vel[1] *= 0.99
pos[0] += vel[0] * dt
pos[1] += vel[1] * dt
window.fill(0)
window.blit(slingShotBullet, pos)
if heldDownMomentPosition is not None:
pygame.draw.line(window, (255, 0, 0), mousePos, heldDownMomentPosition, 2)
pygame.display.flip()

Pygame icon() function not changing a global variable

I have a function that allows for the user to click an icon and set a boolean so that the main loop knows which action to perform. The code is intended to work as click airbrush icon -> set airbrushMode to true -> return airbrushMode so paintScreen() can detect it -> perform the action set by airbrushMode in the while loop. I added in print statements to locate the problem. The variable does change, but the variable is not returned, and the airbrush function does not work. It does work when I set airbrushMode to true inside paintScreen() but setting it to false in the function and outside the function both don't work.
The main function
def paintScreen():
airbrushMode = False
paint = True
gameDisplay.fill(cyan)
message_to_screen('Welcome to PyPaint', black, -300, 'large')
cur = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
pygame.draw.rect(gameDisplay, white, (50, 120, displayWidth - 100, displayHeight - 240))
while paint:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button('X', 20, 20, 50, 50, red, lightRed, action = 'quit')
icon(airbrushIcon, white, 50, displayHeight - 101, 51, 51, white, grey, 'airbrush')
icon(pencilIcon, white, 140, displayHeight - 101, 51, 51, white, grey, 'pencil')
icon(calligraphyIcon, white, 230, displayHeight - 101, 51, 51, white, grey, 'calligraphy')
pygame.display.update()
if cur[0] >= 50 <= displayWidth - 50 and cur[1] >= 120 <= displayHeight - 120:
if airbrushMode == True:
airbrush()
the function that creates the icons and detects the action, then returns it
def icon(icon, colour, x, y, width, height, inactiveColour, activeColour, action = None):
cur = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + width > cur[0] > x and y + height > cur[1] > y:#if the cursor is over the button
pygame.draw.rect(gameDisplay, activeColour, (x, y, width, height))
gameDisplay.blit(icon, (x, y))
if click[0] == 1 and action != None: #if clicked
print('click')
if action == 'quit':
pygame.quit()
quit()
elif action == 'airbrush':
airbrushMode = True
print('airbrush set')
return airbrushMode
print('airbrush active')
Your problem is that icon does not attempt to change any global variables; it's dealing strictly with its input parameters and local variables. If you want it to change a variable outside its own scope, you need to add
global airbrushMode
at the top of your function.
Also, if you expect paintScreen to recognize the global variable, you must have either a global presence (top-level usage) of that variable, or paintScreen also needs the global declaration.
For full details, look up global variables in Python.
Instead of checking for events in icon(), perhaps the code would flow more smoothly if it posted an event when the button was pressed.
def icon(icon, colour, x, y, width, height, inactiveColour, activeColour, action = None):
cur = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + width > cur[0] > x and y + height > cur[1] > y:#if the cursor is over the button
pygame.draw.rect(gameDisplay, activeColour, (x, y, width, height))
gameDisplay.blit(icon, (x, y))
if click[0] == 1 and action != None: #if clicked
print('click')
pygame.event.post( pygame.USEREVENT + 1, {} )
Then handle these in your main loop:
while paint:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.USEREVENT + 1
airbrushMode = True
If it were me, I would make a set of my own event types:
import enum
...
class MyEvents( enum.Enum ):
AIRBRUSH = pygame.USEREVENT + 1
PEN = pygame.USEREVENT + 2
PENCIL = pygame.USEREVENT + 3
Which allows:
pygame.event.post( MyEvents.AIRBRUSH, {} )
...
elif ( event.type == MyEvents.AIRBRUSH ):
airbrushMode = True

pygame.mouse.get_pos() is not updating

So I'm trying to make this button change color when I hover over it, but pygame.mouse.get_pos() is not updating after I open the program.
I'm a novice to both python and program so any assistance would be a appreciated greatly.
import pygame
pygame.init()
gameDisplay = pygame.display.set_mode((800,600))
pygame.display.set_caption('Click to Adventure')
clock = pygame.time.Clock()
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
gameDisplay.fill(white)
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def button(msg,x,y,w,h,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
ycrd = int((y+(h/2)))
r = int(h/2)
print(mouse)
if x+(w+(h/2)) > mouse[0] > x-(h/2) and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay,ac,(x,y,w,h))
pygame.draw.circle(gameDisplay,ac,(x,ycrd),r,0)
pygame.draw.circle(gameDisplay,ac,(x+w,ycrd),r,0)
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(gameDisplay,ic,(x,y,w,h))
pygame.draw.circle(gameDisplay,ic,(x,ycrd),r,0)
pygame.draw.circle(gameDisplay,ic,(x+w,ycrd),r,0)
smallText = pygame.font.SysFont("comicsansms",20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ((x+(w/2)),(y+(h/2)))
gameDisplay.blit(textSurf, textRect)
button("Hi",300,200,100,50,red,green,None)
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
#print(event)
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
I'm not really sure why pygame.mouse.get_pos() isn't updating as I have both pygame.time.Clock() and clock.tick(60).
I'm not a pygame expert myself but what i can see is that you're calling the button() function only once when the game is starting. You need to make a function that will be called in every frame which will wait for an event to happen, in your case, changing the button's color.
Make a normal button on the screen. Then, make a function which will be called when the mouse is on top of the button and change color.
Something like,
Button = MakeButton(); #This function will create a button and show on the screen
In while not gameExit:
if Button.get_rect().collidepoint(pygame.mouse.get_pos()): #This line will wait for the mouse to hover over the button
ChangeButtonColor(); #This function will change the button color
These are pseudo codes to get you started.
pygame uses the "update/draw loop" pattern, commonly found in game development frameworks. This pattern consists of a loop that is mostly non-terminating, and you have it in your code as while not gameExit:. Inside this loop, you must handle all of the user input, through the usage of event flags. For example, your code deals with the QUIT event.
However, your button code is not particularly tailored for this pattern. Instead, it hopes to create a "button" as some sort of static object on the screen, like event-based GUIs.
First, you should separate the update step and the draw step. The update changes the game state, and the draw step simply checks the state and draw things on screen. In your case, the update step should check if the mouse is over the button or not, and define which color is used.
Let's do that separation:
# to be used in the draw step
def draw_button(msg, x, y, width, height, color):
ycrd = int((y + (h / 2)))
r = int(h / 2)
pygame.draw.rect(gameDisplay, color, (x, y, width, height))
pygame.draw.circle(gameDisplay, color, (x, ycrd), r, 0)
pygame.draw.circle(gameDisplay, color, (x + w, ycrd), r, 0)
smallText = pygame.font.SysFont("comicsansms",20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ((x + (w / 2)), (y + (h / 2)))
# to be used in the update step
def check_mouse_state_over_box(x, y, width, height):
# I'm returning strings here, but you should use something else like an enum
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + (w + (h / 2)) > mouse[0] > x - (h / 2) and y + h > mouse[1] > y:
if click[0] == 1:
return 'click'
else:
return 'hover'
else:
return 'no-relation'
Now that the button() function separates the update and draw steps, you can properly use it in the game loop:
while not game_exit:
# UPDATE STEP
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit() # this function is undefined it seems?
# you can also use 'elif event.type == pygame.MOUSEMOTION:' if you wish, but then the logic is a bit different
button_state = check_mouse_over_box(300, 200, 100, 50)
if button_state = 'no-relation':
button_color = red
else:
button_color = green
if button_state = 'click':
action() # define whatever action you want
# DRAW STEP
draw_button('Hi', 300, 200, 100, 50, button_color)
gameDisplay.blit() # I think this is mandatory in pygame
Now, this should work. But if you know object-oriented programming (OOP), you could define a class Button that holds its position and color, an update method that checks the mouse and change the button state properly, and a draw method that draws the button. If you don't know OOP, this is a great opportunity to learn it :)

Creating rect Buttons with Pygame [duplicate]

This question already has answers here:
Pygame mouse clicking detection
(4 answers)
Closed 1 year ago.
I am trying to make buttons using rect in Pygame. I started with the red quit button and checked if a click was inside the boundingbox of the button.
import pygame
"""import nemesis.py;"""
pygame.init();
screen = pygame.display.set_mode((400,300));
pygame.display.set_caption("menu");
menuAtivo = True;
start_button = pygame.draw.rect(screen,(0,0,240),(150,90,100,50));
continue_button = pygame.draw.rect(screen,(0,244,0),(150,160,100,50));
quit_button = pygame.draw.rect(screen,(244,0,0),(150,230,100,50));
pygame.display.flip();
while menuAtivo:
for evento in pygame.event.get():
print(evento);
if evento.type == pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pos() >= (150,230):
if pygame.mouse.get_pos() <= (250,280):
pygame.quit();
When using rects in pygame, it's best to use the in built collision detection.
here is an example code on how to do it hope it helps you solve your problem.
Before that though i'd like to mention you should render/draw your objects withing the while loop or the wont show up.
import pygame
import sys
def main():
pygame.init()
clock = pygame.time.Clock()
fps = 60
size = [200, 200]
bg = [255, 255, 255]
screen = pygame.display.set_mode(size)
button = pygame.Rect(100, 100, 50, 50) # creates a rect object
# The rect method is similar to a list but with a few added perks
# for example if you want the position of the button you can simpy type
# button.x or button.y or if you want size you can type button.width or
# height. you can also get the top, left, right and bottom of an object
# with button.right, left, top, and bottom
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = event.pos # gets mouse position
# checks if mouse position is over the button
if button.collidepoint(mouse_pos):
# prints current location of mouse
print('button was pressed at {0}'.format(mouse_pos))
screen.fill(bg)
pygame.draw.rect(screen, [255, 0, 0], button) # draw button
pygame.display.update()
clock.tick(fps)
pygame.quit()
sys.exit
if __name__ == '__main__':
main()
Another good way to create buttons on pygame (in python) is by installing the package called pygame_widgets (pip3 install pygame_widgets) on Mac or Linux and (pip install pygame_widgets) on Windows. And also make sure you have pip installed otherwise, it is not going to work.
# Importing Modules
import pygame as pg
import pygame_widgets as pw
# creating screen
pg.init()
screen = pg.display.set_mode((800, 600))
running = True
button = pw.Button(
screen, 100, 100, 300, 150, text='Hello',
fontSize=50, margin=20,
inactiveColour=(255, 0, 0),
pressedColour=(0, 255, 0), radius=20,
onClick=lambda: print('Click')
)
while running:
events = pg.event.get()
for event in events:
if event.type == pg.QUIT:
running = False
button.listen(events)
button.draw()
pg.display.update()
Hope this helps you.
TKS GUYS,
Here is my answer :
import pygame
pygame.init();
screen = pygame.display.set_mode((400,300));
pygame.display.set_caption("menu");
menuAtivo = True;
start_button = pygame.draw.rect(screen,(0,0,240),(150,90,100,50));
continue_button = pygame.draw.rect(screen,(0,244,0),(150,160,100,50));
quit_button = pygame.draw.rect(screen,(244,0,0),(150,230,100,50));
pygame.display.flip();
def startGame():
screen.fill((0,0,0));
pygame.display.flip();
import nemesis.py;
while menuAtivo:
for evento in pygame.event.get():
print(evento);
if evento.type == pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pos()[0] >= 150 and pygame.mouse.get_pos()[1] >= 230:
if pygame.mouse.get_pos()[0] <= 250 and pygame.mouse.get_pos()[1] <= 280:
pygame.quit();
if pygame.mouse.get_pos()[0] >= 150 and pygame.mouse.get_pos()[1] >= 90:
if pygame.mouse.get_pos()[0] <= 250 and pygame.mouse.get_pos()[1] <= 140:
startGame();
I think the main problem in your code is that you compare pygame.mouse.get_pos() directly with a Tuple, which is ambiguous. You should try testing x then y separately:
while menuAtivo:
for evento in pygame.event.get():
print(evento);
if evento.type == pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pos()[0] >= 150 and pygame.mouse.get_pos()[1] >= 230:
if pygame.mouse.get_pos()[0] <= 250 and pygame.mouse.get_pos()[1] <= 280:
pygame.quit();
I have already provided an answer on the above. Here is my another answer without the module pygame_widgets:
import pygame
import sys
# initializing the constructor
pygame.init()
# screen resolution
res = (720,720)
# opens up a window
screen = pygame.display.set_mode(res)
# white color
color = (255,255,255)
# light shade of the button
color_light = (170,170,170)
# dark shade of the button
color_dark = (100,100,100)
# stores the width of the
# screen into a variable
width = screen.get_width()
# stores the height of the
# screen into a variable
height = screen.get_height()
# defining a font
smallfont = pygame.font.SysFont('Corbel',35)
# rendering a text written in
# this font
text = smallfont.render('quit' , True , color)
while True:
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
pygame.quit()
#checks if a mouse is clicked
if ev.type == pygame.MOUSEBUTTONDOWN:
#if the mouse is clicked on the
# button the game is terminated
if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40:
pygame.quit()
# fills the screen with a color
screen.fill((60,25,60))
# stores the (x,y) coordinates into
# the variable as a tuple
mouse = pygame.mouse.get_pos()
# if mouse is hovered on a button it
# changes to lighter shade
if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40:
pygame.draw.rect(screen,color_light,[width/2,height/2,140,40])
else:
pygame.draw.rect(screen,color_dark,[width/2,height/2,140,40])
# superimposing the text onto our button
screen.blit(text , (width/2+50,height/2))
# updates the frames of the game
pygame.display.update()
Hope This Helps if pygame_widgets (pip install pygame_widgets) module could not be installed in your python version.
this is my solution
class button():
def __init__(self, color, x,y,width,height, text=''):
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
def draw(self,win,outline=None):
#Call this method to draw the button on the screen
if outline:
pygame.draw.rect(win, outline, (self.x-2,self.y-2,self.width+4,self.height+4),0)
pygame.draw.rect(win, self.color, (self.x,self.y,self.width,self.height),0)
if self.text != '':
font = pygame.font.SysFont('comicsans', 60)
text = font.render(self.text, 1, (0,0,0))
win.blit(text, (self.x + (self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2)))
def isOver(self, pos):
#Pos is the mouse position or a tuple of (x,y) coordinates
if pos[0] > self.x and pos[0] < self.x + self.width:
if pos[1] > self.y and pos[1] < self.y + self.height:
return True
return False

Move frameless pygame window? [duplicate]

I want to create a pygame window that doesn't have a frame and that moves when the user clicks on it and moves the mouse.
I tried this script but when I click on the windows, '0' is printed but not '1'
Something is wrong in my script.
# coding : utf-8
import pygame
from pygame.locals import *
from random import randint
from os import environ
from math import sqrt
pygame.init()
max_fps = 250
clock = pygame.time.Clock()
window_size_x, window_size_x = 720, 360
infos = pygame.display.Info()
environ['SDL_VIDEO_WINDOW_POS'] = str(int(infos.current_w / 2)) + ',' + str(int(infos.current_h / 2)) # center the window
screen = pygame.display.set_mode((window_size_x, window_size_x), pygame.NOFRAME)
def move_window(): # move the windows when custom bar is hold
window_x, window_y = eval(environ['SDL_VIDEO_WINDOW_POS'])
mouse_x, mouse_y = pygame.mouse.get_pos()
dist_x , dist_y = mouse_x - window_x, mouse_y - window_y # calculate the distance between mouse and window origin
for event in pygame.event.get():
if event.type != MOUSEBUTTONUP: # while bar is hold
print('1')
mouse_x, mouse_y = pygame.mouse.get_pos()
environ['SDL_VIDEO_WINDOW_POS'] = str(mouse_x - dist_x) + ',' + str(mouse_x - dist_x)
screen = pygame.display.set_mode((window_size_x, window_size_x), pygame.NOFRAME) # rebuild window
def main():
run = True
while run :
screen.fill((255, 255, 255))
pygame.display.update()
clock.tick(60) # build frame with 60 frame per second limitation
for event in pygame.event.get():
if event.type == MOUSEBUTTONDOWN:
print('0')
move_window()
if __name__ == '__main__':
main()
Write a function, which moves the window from dependent on a previous mouse position (start_x, start_y) and a mouse position (new_x, new_y)
def move_window(start_x, start_y, new_x, new_y):
global window_size_x, window_size_y
window_x, window_y = eval(environ['SDL_VIDEO_WINDOW_POS'])
dist_x, dist_y = new_x - start_x, new_y - start_y
environ['SDL_VIDEO_WINDOW_POS'] = str(window_x + dist_x) + ',' + str(window_y + dist_y)
# Windows HACK
window_size_x += 1 if window_size_x % 2 == 0 else -1
screen = pygame.display.set_mode((window_size_x, window_size_y), pygame.NOFRAME)
In this function is a very important line:
window_size_x += 1 if window_size_x % 2 == 0 else -1
this line changes the width of the window from alternately by +1 and -1. On Windows systems there seems to be a bug, which ignores the new position parameter, if the size of the window didn't change.
This "hack" is a workaround, which slightly change the size of the window whenever the position is changed.
A different approach, with no flickering, may look as follows. Note, though, that this version is significantly slower:
def move_window(start_x, start_y, new_x, new_y):
global window_size_x, window_size_y
buffer_screen = pygame.Surface((window_size_x, window_size_y))
buffer_screen.blit(pygame.display.get_surface(), pygame.display.get_surface().get_rect())
window_x, window_y = eval(environ['SDL_VIDEO_WINDOW_POS'])
dist_x, dist_y = new_x - start_x, new_y - start_y
environ['SDL_VIDEO_WINDOW_POS'] = str(window_x + dist_x) + ',' + str(window_y + dist_y)
window_size_x += 1 if window_size_x % 2 == 0 else -1
screen = pygame.display.set_mode((window_size_x, window_size_y), pygame.NOFRAME)
screen.blit(buffer_screen, buffer_screen.get_rect())
pygame.display.flip()
Change the position on MOUSEMOTION and MOUSEBUTTONUP:
def main():
run = True
pressed = False
start_pos = (0,0)
while run :
# [...]
for event in pygame.event.get():
if event.type == MOUSEBUTTONDOWN:
pressed = True
start_pos = pygame.mouse.get_pos()
elif event.type == MOUSEMOTION:
if pressed:
new_pos = pygame.mouse.get_pos()
move_window(*start_pos, *new_pos)
pygame.event.clear(pygame.MOUSEBUTTONUP)
elif event.type == MOUSEBUTTONUP:
pressed = False
new_pos = pygame.mouse.get_pos()
move_window(*start_pos, *new_pos)
Full example program:
# coding : utf-8
import pygame
from pygame.locals import *
from os import environ
pygame.init()
clock = pygame.time.Clock()
window_size_x, window_size_y = 720, 360
infos = pygame.display.Info()
environ['SDL_VIDEO_WINDOW_POS'] = str(int(infos.current_w/2)) + ',' + str(int(infos.current_h/2))
screen = pygame.display.set_mode((window_size_x, window_size_x), pygame.NOFRAME)
def move_window(start_x, start_y, new_x, new_y):
global window_size_x, window_size_y
window_x, window_y = eval(environ['SDL_VIDEO_WINDOW_POS'])
dist_x, dist_y = new_x - start_x, new_y - start_y
environ['SDL_VIDEO_WINDOW_POS'] = str(window_x + dist_x) + ',' + str(window_y + dist_y)
window_size_x += 1 if window_size_x % 2 == 0 else -1
screen = pygame.display.set_mode((window_size_x, window_size_y), pygame.NOFRAME)
def main():
run = True
pressed = False
start_pos = (0,0)
while run :
screen.fill((255, 255, 255))
pygame.display.update()
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
if event.type == MOUSEBUTTONDOWN:
pressed = True
start_pos = pygame.mouse.get_pos()
elif event.type == MOUSEMOTION:
if pressed:
new_pos = pygame.mouse.get_pos()
move_window(*start_pos, *new_pos)
pygame.event.clear(pygame.MOUSEBUTTONUP)
elif event.type == MOUSEBUTTONUP:
pressed = False
new_pos = pygame.mouse.get_pos()
move_window(*start_pos, *new_pos)
if __name__ == '__main__':
main()
This solution no longer works under Windows systems and with Pygame 2.0. The position of a window can, however, be changed with the WINAPI function MoveWindow:
import pygame
from ctypes import windll
pygame.init()
screen = pygame.display.set_mode((400, 400), pygame.NOFRAME)
clock = pygame.time.Clock()
def moveWin(new_x, new_y):
hwnd = pygame.display.get_wm_info()['window']
w, h = pygame.display.get_surface().get_size()
windll.user32.MoveWindow(hwnd, new_x, new_y, w, h, False)
window_pos = [100, 100]
moveWin(*window_pos)
run = True
while run :
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
elif event.type == pygame.MOUSEMOTION:
if pygame.mouse.get_pressed()[0]:
window_pos[0] += event.rel[0]
window_pos[1] += event.rel[1]
moveWin(*window_pos)
screen.fill((255, 255, 255))
pygame.display.update()
clock.tick(60)
This code use only one for event loop with MOUSEBUTTONDOWN to set moving = True, MOUSEBUTTONUP to set moving = False and MOUSEMOTION which changes window's position when moving is True.
After move I use pygame.event.clear(pygame.MOUSEBUTTONUP) to remove this type of events because new window was getting this even and it was stoping window.
import pygame
from os import environ
# --- constants --- (UPPER_CASE_NAMES)
WINDOW_WIDTH = 720
WINDOW_HEIGHT = 360
# --- main ---
def main():
pygame.init()
infos = pygame.display.Info()
environ['SDL_VIDEO_WINDOW_POS'] = '{},{}'.format(infos.current_w//2, infos.current_h//2) # center the window
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), pygame.NOFRAME)
moving = False
clock = pygame.time.Clock()
run = True
while run:
screen.fill((255, 255, 255))
pygame.display.update()
clock.tick(60) # build frame with 60 frame per second limitation
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
if not moving:
print('MOUSEBUTTONDOWN')
moving = True
# remeber start distance
#window_x, window_y = eval(environ['SDL_VIDEO_WINDOW_POS'])
window_x, window_y = map(int, environ['SDL_VIDEO_WINDOW_POS'].split(','))
dist_x = event.pos[0] # mouse x
dist_y = event.pos[1] # mouse y
elif event.type == pygame.MOUSEBUTTONUP:
if moving:
print('MOUSEBUTTONUP')
moving = False
elif event.type == pygame.MOUSEMOTION:
if moving:
print('moving')
mouse_x, mouse_y = pygame.mouse.get_pos()
diff_x = dist_x - mouse_x
diff_y = dist_y - mouse_y
window_x -= diff_x
window_y -= diff_y
environ['SDL_VIDEO_WINDOW_POS'] = "{},{}".format(window_x, window_y)
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), pygame.NOFRAME) # rebuild window
pygame.event.clear(pygame.MOUSEBUTTONUP) # to remove MOUSEBUTTONUP event which stops moving window
if __name__ == '__main__':
main()
The code's not ready, but I was getting there.
I had to abandon it, but it might help someone save some time.
Press f for full-screen mode. The part that is not done,
supposed to be the window-mode resize part. You must have an in-depth
look at toogle_resize() function for that.
The resize it's taking full desktop resolution and compare it
to the space between clik (MOUSEBUTTONDOWN) and (MOUSEBUTTONUP).
Or at least that's how I wanted it to work. Good luck!
Also the code needs to be optimized, it is raw.
import pyautogui
import pygame
import sys
from pygame.locals import *
from pyinput.mouse import Controller
Mouse controller gets the position on desktop, but I had to run it once more inside the while loop to get the updated values.
mouse = Controller()
standard = current_mouse_position = mouse.position
pygame.init()
Silkscreen = False
blueGray = (73, 111, 135)
width, height = pyautogui.size()
w = width / 4
h = height / 4
ww = width - w
hh = height - h
wi = ww - 4
hi = hh - 4
Set the background and the flags
room = pygame.image.load('img.png')
full_flags = pygame.FULLSCREEN | pygame.SCALED |
pygame.NOFRAME
normal_flags = pygame.NOFRAME | pygame.RESIZABLE |
pygame.SCALED
def toggle_fullscreen(f):
if f:
return pygame.display.set_mode((ww, hh), full_flags)
# pygame.display.set_mode(size, normal_flags) # uncomment
this to see issue being fixed as a workaround
return pygame.display.set_mode((ww, hh), normal_flags)
def toggle_resize(click):
if click:
return pygame.display.set_mode((ww + movement, hh),
normal_flags) # Expands by resize_y
# Set up the drawing window
screen = pygame.display.set_mode((ww, hh), normal_flags)
def bg():
screen.blit(room, (0, 0))
def border():
pygame.draw.rect(screen, blueGray, (0, 0, ww, hh), 2) #
width = 3
clock = pygame.time.Clock()
# Run until the user asks to quit
running = True
while running:
current_mouse_position = mouse.position
# print(current_mouse_position[0])
bg()
mw, mh = pygame.mouse.get_pos() # 0 - 1439(window size)
In the next line, I checked if the mouse is on the window border. Apply only to the left, right border. You must create code for the top, bottom border. Left, right borders, 3 pixels range each side.
if mw <= 3 or (mw > wi and mw < ww):
active = True
moveOne = 0
# print("data", moveOne)
# print(type(moveOne))
moveTwo = 0
# event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
running = False
sys.exit()
# print(mw, mh)
If the user clicks, the standard variable at the beginning of the code it gets the mouse current position. You must run the active bool and check if it is True if you want to start resizing from the border of the window.
The code is very complicated and needs some optimization, but I bet you gonna get it right. Good luck!;)
if event.type == pygame.MOUSEBUTTONDOWN:
standard = current_mouse_position[0]
print(standard)
if event.type == pygame.MOUSEBUTTONUP:
moveTwo = current_mouse_position[0]
movement = standard - moveTwo
print("This is:", moveTwo)
toggle_resize(click=MOUSEBUTTONUP)
active = False
Full-screen handler from here down. Press f for full screen and back to window mode.
if event.type == pygame.KEYDOWN:
Silkscreen = not Silkscreen
if event.key == K_f:
screen = toggle_fullscreen(Silkscreen)
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
border()
# Flip the display
pygame.display.flip()
clock.tick(144) # framerate
# Done! Time to quit.
pygame.quit()'
Here is a version of #Rabbid76's answer for Pygame 2. Note that this example may break as the module _sdl2.video, used to set the window position, is experimental.
move_window.py
import pygame
from pygame._sdl2.video import Window
start_pos = pygame.Vector2(0, 0) #Initial mouse position
pressed = False #Flag that denotes when the mouse is being continuously pressed down
def move_window(window : Window, start_mouse_pos : pygame.Vector2, new_mouse_pos : pygame.Vector2) -> None:
"""Moves the window by the offset between start_mouse_pos and new_mouse_pos"""
screen = pygame.display.get_surface()
buffer_screen = pygame.Surface((window.size[0], window.size[1]))
buffer_screen.blit(screen, screen.get_rect())
window_pos_Vec2 = pygame.Vector2(window.position)
window.position = window_pos_Vec2 + new_mouse_pos - start_mouse_pos
screen.blit(buffer_screen, buffer_screen.get_rect())
pygame.display.flip()
def check_event(window : Window, event : pygame.event, move_area : pygame.Rect = pygame.Rect(-1, -1, 1, 1)) -> None:
"""Takes a window and event and updates the window position accordingly. \n
move_area can be used to set what area of the screen can be clicked in order to move the window. \n
move_area defaults to a dummy rect which is then internally changed to the full window."""
global start_pos, pressed
if move_area == pygame.Rect(-1, -1, 1, 1):
move_area = pygame.Rect((0, 0), window.size)
mouse_pos = pygame.Vector2(pygame.mouse.get_pos())
if move_area.collidepoint(mouse_pos):
if event.type == pygame.MOUSEBUTTONDOWN:
pressed = True
start_pos = mouse_pos
elif event.type == pygame.MOUSEMOTION and pressed:
move_window(window, start_pos, mouse_pos)
elif event.type == pygame.MOUSEBUTTONUP:
pressed = False
move_window(window, start_pos, mouse_pos)
else:
pressed = False
And in your main file:
import pygame
from pygame._sdl2.video import Window
screen = pygame.display.set_mode(...)
window = Window.from_display_module()
#...
while True:
for event in pygame.event.get():
#...
move_window.check_event(window, event)

Categories

Resources