Can't create a transparent window with pygame [duplicate] - python

This question already has answers here:
Fully transparent windows in Pygame?
(2 answers)
How to make a pygame window transparent while still receiving and blocking mouse clicks?
(1 answer)
Closed 5 days ago.
I'm trying to create a transparent window that lets me draw over it.
ChatGPT (sorry) wrote me this code, but I can't get it to actually create a transparent window - I just get a black window. Otherwise it seems to do what I want. Any suggestions on how to get it working with transparency?
import pygame
from pygame.locals import *
import os
# Set up Pygame and create a window
pygame.init()
#os.environ['SDL_VIDEO_WINDOW_POS'] = '0,0'
screen_info = pygame.display.Info()
WINDOW_SIZE = (screen_info.current_w, screen_info.current_h)
#os.environ['SDL_VIDEO_CENTERED'] = '1' # Center window
screen = pygame.display.set_mode(WINDOW_SIZE, pygame.NOFRAME)
surface = pygame.Surface(WINDOW_SIZE, pygame.SRCALPHA)
screen.set_alpha(0)
screen.fill((0, 0, 0, 0))
screen.blit(surface, (0, 0))
# Set up colors and line width
RED = (255, 0, 0)
LINE_WIDTH = 5
# Set up drawing variables
drawing = False
last_pos = None
# Define a function to draw a line
def draw_line(start, end):
pygame.draw.line(screen, RED, start, end, LINE_WIDTH)
# Run the game loop
running = True
while running:
# Handle events
for event in pygame.event.get():
if event.type == QUIT:
running = False
elif event.type == KEYDOWN and event.key == K_ESCAPE:
screen.fill((0, 0, 0, 0)) # Clear the screen
last_pos = None
pygame.quit()
elif event.type == MOUSEBUTTONDOWN and event.button == 1:
drawing = True
last_pos = pygame.mouse.get_pos()
elif event.type == MOUSEBUTTONUP and event.button == 1:
drawing = False
last_pos = None
elif event.type == MOUSEMOTION and drawing:
pos = pygame.mouse.get_pos()
if last_pos is not None:
draw_line(last_pos, pos)
last_pos = pos
# Update the screen
pygame.display.flip()

Related

How to fix pygame menu (space invaders)?

This is my first game so excuse the messy code. I am making a space invaders game and everything i implemented is working fine (sprites, function of the game, music, pause screen, etc). I wanted to implement a really simple menu screen where, if you press C, the game starts. However, the problem with this is that no matter where i call the menu function, there is always a problem, here is the code (im just going to post the menu function and main loop since everything else i believe is not needed).
import pygame
import random
import math
from pygame import mixer
# Start pygame
pygame.init()
# Create Screen
screen = pygame.display.set_mode((1000, 710))
# Background Image
background = pygame.image.load('background.png').convert_alpha()
# Menu Variables
menu_font = pygame.font.Font('freesansbold.ttf', 65)
menuX = 380
menuY = 250
# Menu Function
def game_intro(x, y):
menu = True
while menu:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
menu = False
if event.key == pygame.K_q:
pygame.quit()
quit()
# Menu Text
menu_text = menu_font.render("Space Invaders", True, (255, 255, 255))
screen.blit(menu_text, (x, y))
pygame.display.update()
# Game Loop
running = True
while running:
# RGB - Red, Green, Blue
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
----game_intro(menuX,menuY)---IF I PUT IT HERE, THE ACTUAL GAME APPEARS FOR ONE SECOND AND IT GOES BACK TO MAIN MENU-----------
# Making the screen stay still
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
--------game_intro(menuX,menuY)--- IF I PUT IT HERE, THE GAME APPEARS ONLY WHEN 'c' IS BEING HELD DOWN-----------------
*more code*
# Updating
pygame.display.update()
if i put it above pygame.display.update(), then the same thing happens: the game appears for one second and then it goes back to the menu screen. I have tried to search everywhere but the videos either are from 2014, and the websites with some similar problem don't explain how to fix it. Please help.
First of all you should throw the while loop out of your function.
def game_intro(x, y):
# Menu Text
menu_text = menu_font.render("Space Invaders", True, (255, 255, 255))
screen.blit(menu_text, (x, y))
the missing code gets put in the mainloop like this
...
# Making the screen stay still
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
menu = False
if event.key == pygame.K_q:
pygame.quit()
...
now in your mainloop you need to decide whether to draw the menu or the game
if menu:
game_intro(x, y)
else:
#CODE THAT DRAWS THE GAME
all together:
import pygame
import random
import math
from pygame import mixer
# Start pygame
pygame.init()
# Create Screen
screen = pygame.display.set_mode((1000, 710))
# Background Image
background = pygame.image.load('background.png').convert_alpha()
# Menu Variables
menu_font = pygame.font.Font('freesansbold.ttf', 65)
menuX = 380
menuY = 250
# Menu Function
def game_intro(x, y):
# Menu Text
menu_text = menu_font.render("Space Invaders", True, (255, 255, 255))
screen.blit(menu_text, (x, y))
# Game Loop
running = True
while running:
# RGB - Red, Green, Blue
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
# Making the screen stay still
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
menu = False
if event.key == pygame.K_q:
pygame.quit()
if menu:
game_intro(x, y)
else:
# CODE THAT DRAWS THE GAME
# Updating
pygame.display.update()
this should work
note that you need to set menu to True somewhere to get into the menu

How to draw a continuous line in Pygame?

I want to draw a line when mouse clicked and moving in Pygame framework, it will be a line if I move the mouse very slowly. However, if I move the mouse quickly, it's just incontinuous dots. The question is how to draw a continuous line when mouse move? Thanks in advance.
import pygame, sys
from pygame.locals import *
def main():
pygame.init()
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
mouse_position = (0, 0)
drawing = False
screen = pygame.display.set_mode((600, 800), 0, 32)
screen.fill(WHITE)
pygame.display.set_caption("ScratchBoard")
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
if (drawing):
mouse_position = pygame.mouse.get_pos()
pygame.draw.line(screen, BLACK, mouse_position, mouse_position, 1)
elif event.type == MOUSEBUTTONUP:
mouse_position = (0, 0)
drawing = False
elif event.type == MOUSEBUTTONDOWN:
drawing = True
pygame.display.update()
if __name__ == "__main__":
main()
By calling pygame.draw.line with the same argument (mouse_position) twice, you're not drawing a line, you're drawing a single pixel, because start_pos and end_pos are the same.
To get a contiguous line, you need to save the last position and draw a line between it and the next position, like this (changes are the lines with last_pos):
import pygame, sys
from pygame.locals import *
def main():
pygame.init()
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
mouse_position = (0, 0)
drawing = False
screen = pygame.display.set_mode((600, 800), 0, 32)
screen.fill(WHITE)
pygame.display.set_caption("ScratchBoard")
last_pos = None
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
if (drawing):
mouse_position = pygame.mouse.get_pos()
if last_pos is not None:
pygame.draw.line(screen, BLACK, last_pos, mouse_position, 1)
last_pos = mouse_position
elif event.type == MOUSEBUTTONUP:
mouse_position = (0, 0)
drawing = False
elif event.type == MOUSEBUTTONDOWN:
drawing = True
pygame.display.update()
if __name__ == "__main__":
main()
vgel is right, you need to pass the previous position and the current position to pygame.draw.line. You can also calculate the previous position by subtracting the event.rel attribute of the event from the event.pos attribute.
It's also possible get rid of the drawing variable by using the event.buttons attribute. If event.buttons[0] is True then the left mouse button is being pressed.
import pygame
def main():
pygame.init()
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
screen = pygame.display.set_mode((600, 800), 0, 32)
screen.fill(WHITE)
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
elif event.type == pygame.MOUSEMOTION:
if event.buttons[0]: # Left mouse button down.
last = (event.pos[0]-event.rel[0], event.pos[1]-event.rel[1])
pygame.draw.line(screen, BLACK, last, event.pos, 1)
pygame.display.update()
clock.tick(30) # Limit the frame rate to 30 FPS.
if __name__ == "__main__":
main()

How would I go about making clickable text in Pygame? [duplicate]

This question already has an answer here:
How to detect when a rectangular object, image or sprite is clicked
(1 answer)
Closed 2 years ago.
Basically, here is a section of my code in Pygame:
button_text=pygame.font.Font("C:\Windows\Fonts\Another Danger - Demo.otf",35)
textSurface,textRect=text_objects("Start game",button_text)
textRect.center=(105,295)
screen.blit(textSurface,textRect)
This is the text I'd like to turn into a clickable format, so that when someone presses the text, it can run a function, such as running the next thing possible.
Any help would be greatly appreciated.
Thanks.
Get the rect from the surface that font.render returns and use it for collision detection and the blit position.
import sys
import pygame as pg
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
font = pg.font.Font(None, 30)
text_surface = font.render('text button', True, pg.Color('steelblue3'))
# Use this rect for collision detection with the mouse pos.
button_rect = text_surface.get_rect(topleft=(200, 200))
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
if event.type == pg.MOUSEBUTTONDOWN:
if event.button == 1:
# Use event.pos or pg.mouse.get_pos().
if button_rect.collidepoint(event.pos):
print('Button pressed.')
screen.fill((40, 60, 70))
screen.blit(text_surface, button_rect)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
sys.exit()
PyGame does not have buttons, so what you can do here is get the mouse cursor position when clicking with pygame.mouse.get_pos(). If the mouse cursor position is inside the text then you know the text was selected.
Here is an example:
import pygame, sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((1000, 700))
clock = pygame.time.Clock()
tx, ty = 250, 250
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
mouse = pygame.mouse.get_pos()
if mouse[0]in range (tx, tx + 130) and mouse[1] in range (ty, ty + 20):
print("You clicked on the text.")
myfont = pygame.font.SysFont("Marlett", 35)
textsurface = myfont.render(("Start game"), True, (230, 230, 230))
screen.blit(textsurface,(tx, ty))
pygame.display.update()
clock.tick(60)
In this example, I used tx and ty for sizes but you can use rect, it's the same thing.

Kivy / pygame touch event CPU time [duplicate]

How can I detect if an image has been touched in pygame on a touch screen? I have searched but I can not find how to detect if a particular image is touched.
To detect if an image has been touched, you can use the MOUSEBUTTONDOWN event. See Pygame mouse clicking detection.
Load the image with pygame.image.load(). Crate the bounding rectangle (pygame.Rect). Create a pygame.Mask from the image with pygame.mask.from_surface:
image = pygame.image.load('image.png').convert_alpha()
image _rect = image.get_rect(topleft = (x, y))
image_mask = pygame.mask.from_surface(image)
Use the MOUSEBUTTONDOWN event to detect if the mouse is clicked in the rectangular area of the image. Check if the corresponding bit in the image mask is set:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
image_x, image_y = event.pos[0] - image_rect.x, event.pos[1] - image_rect.y
if image_rect.collidepoint(event.pos) and image_mask.get_at((image_x, image_y)):
print("touched")
Minimal example:
import pygame
pygame.init()
window = pygame.display.set_mode((400, 400))
font = pygame.font.SysFont(None, 100)
clock = pygame.time.Clock()
text = font.render("Text", True, (255, 255, 0))
bomb = pygame.image.load('Bomb-256.png').convert_alpha()
bomb_rect = bomb.get_rect(center = window.get_rect().center)
bomb_mask = pygame.mask.from_surface(bomb)
click_count = 0
click_text = font.render('touch: ' + str(click_count), True, "black")
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
image_x, image_y = event.pos[0] - bomb_rect.x, event.pos[1] - bomb_rect.y
if bomb_rect.collidepoint(event.pos) and bomb_mask.get_at((image_x, image_y)):
click_count += 1
click_text = font.render('touch: ' + str(click_count), True, "black")
window.fill((255, 255, 255))
window.blit(bomb, bomb_rect)
window.blit(click_text, click_text.get_rect(topleft = (20, 20)))
pygame.display.flip()
pygame.quit()
exit()
If I run this from the raspberry pi desktop the touch is not detected.
But if I execute this from ssh remote it works fine

How do I check to see if a mouse click is within a circle in pygame?

import pygame
pygame.init()
white = 255,255,255
cyan = 0,255,255
gameDisplay = pygame.display.set_mode((800,600))
pygame.display.set_caption('Circle Click Test')
stop = False
while not stop:
gameDisplay.fill(white)
pygame.draw.circle(gameDisplay,cyan,(400,300),(100))
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
####################################################
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
Here I have a circle on the screen, and I would like to check to see if the user
clicked within the circle. I know how to do this with a rectangle, I would assume it would be similar. Thanks for any help, I am quite new to pygame.
here is what I have for rectangles:
import pygame
pygame.init()
white = 255,255,255
cyan = 0,255,255
gameDisplay = pygame.display.set_mode((800,600))
pygame.display.set_caption('Circle Click Test')
rectangle = pygame.Rect(400,300,200,200)
stop = False
while not stop:
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, cyan,rectangle,4)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
click = rectangle.collidepoint(pygame.mouse.get_pos())
if click == 1:
print 'CLICKED!'
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
Use the distance formula:
################################################################################
# Imports ######################################################################
################################################################################
from pygame.locals import *
import pygame, sys, math
################################################################################
# Screen Setup #################################################################
################################################################################
pygame.init()
scr = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Box Test')
################################################################################
# Game Loop ####################################################################
################################################################################
while True:
pygame.display.update(); scr.fill((200, 200, 255))
pygame.draw.circle(scr, (0, 0, 0), (400, 300), 100)
x = pygame.mouse.get_pos()[0]
y = pygame.mouse.get_pos()[1]
sqx = (x - 400)**2
sqy = (y - 300)**2
if math.sqrt(sqx + sqy) < 100:
print 'inside'
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
################################################################################
################################################################################
################################################################################
you could sample the pixel like this
detect click on shape pygame
otherwise use pythagoras to get the distance from the centre.
As Malik shows, pythagoras works well for circles, but for general solid colour shapes you can do:
if event.type == pygame.MOUSEBUTTONDOWN:
click = gameDisplay.get_at(pygame.mouse.get_pos()) == cyan
if click == 1:
print 'CLICKED!'

Categories