How do you create rect variables in python pygame - python

I am programming in Python with the pygame library. I want to know how to make a rectangle variable, something like:
import ...
rect1 = #RECT VARIABLE
rect2 = #RECT VARIABLE

Just do
pygame.Rect(left, top, width, height)
this will return you a Rect object in pygame

Perhaps something like this will work?
import pygame
# your whole code until you need a rectangle
rect1 = pygame.draw.rect( (x_coordinate, y_coordinate), (#a rgb color), (#size of rect in pixels) )
If you want a red rectangle with 100x150 size in 0x50 position, it will be:
rect1 = pygame.draw.rect( (0, 50), (255, 0, 0), (100, 150) )
To insert it into the screen you use:
pygame.screen_you_have_created.blit(rect1, 0, 50)

For rectangle draw pattern is : pygame.Rect(left, top, width, height)
You can modify this code according to your need.
import pygame, sys
from pygame.locals import *
pygame.init()
windowSurface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption('Title')
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
basicFont = pygame.font.SysFont(None, 48)
message = 'Hello '
text = basicFont.render(message, False, WHITE, BLUE)
textRect = text.get_rect()
textRect.centerx = windowSurface.get_rect().centerx
textRect.centery = windowSurface.get_rect().centery
windowSurface.fill(WHITE)
pixArray = pygame.PixelArray(windowSurface)
pixArray[480][380] = BLACK
del pixArray
windowSurface.blit(text, textRect)
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == K_ESCAPE:
pygame.quit()
sys.exit()

Related

Why don't three R, G and B circles blend correctly?

I am trying to represent the RGB color model using python + pygame.
I wanted to get the following:
So then, I wrote the following code:
import pygame, sys
from pygame.locals import *
ALPHA = 100
TRANSPARENT = (255,0,255)
BLACK = (0,0,0)
WHITE = (255,255,255)
RED = (255,0,0,100)
GREEN = (0,255,0,100)
BLUE = (0,0,255,100)
pygame.init()
size=(800,500)
screen= pygame.display.set_mode(size)
surf1 = pygame.Surface(size)
surf1.fill(TRANSPARENT)
surf1.set_colorkey(TRANSPARENT)
pygame.draw.circle(surf1, BLUE, (430, 280), 60 )
surf2 = pygame.Surface(size)
surf2.fill(TRANSPARENT)
surf2.set_colorkey(TRANSPARENT)
pygame.draw.circle(surf2, GREEN, (370, 280), 60 )
surf3 = pygame.Surface(size)
surf3.fill(TRANSPARENT)
surf3.set_colorkey(TRANSPARENT)
pygame.draw.circle(surf3, RED, (400, 220), 60 )
surf1.set_alpha(ALPHA)
surf2.set_alpha(ALPHA)
surf3.set_alpha(ALPHA)
while True :
screen.fill(WHITE)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.blit(surf1, (0,0))
screen.blit(surf2, (0,0))
screen.blit(surf3, (0,0))
pygame.display.flip()
But instead of getting the RGB color model, I got this, with colors incorrectly blended:
Does anybody know what it could be? Thanks!
This should work:
import pygame, sys
from pygame.locals import *
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0, 100)
GREEN = (0, 255, 0, 100)
BLUE = (0, 0, 255, 100)
pygame.init()
size = (800, 500)
screen = pygame.display.set_mode(size)
surf1 = pygame.Surface(size)
surf1.fill(BLACK)
surf1.set_colorkey(BLACK)
pygame.draw.circle(surf1, BLUE, (430, 280), 60)
surf2 = pygame.Surface(size)
surf2.fill(BLACK)
surf2.set_colorkey(BLACK)
pygame.draw.circle(surf2, GREEN, (370, 280), 60)
surf3 = pygame.Surface(size)
surf3.fill(BLACK)
surf3.set_colorkey(BLACK)
pygame.draw.circle(surf3, RED, (400, 220), 60)
surf4 = pygame.Surface(size)
surf4.set_colorkey(BLACK)
surf4.blit(surf1, (0, 0), special_flags=pygame.BLEND_RGB_ADD)
surf4.blit(surf2, (0, 0), special_flags=pygame.BLEND_RGB_ADD)
surf4.blit(surf3, (0, 0), special_flags=pygame.BLEND_RGB_ADD)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.fill(WHITE)
screen.blit(surf4, (0, 0))
pygame.display.flip()
You want to add the colors at the intersections of the circles, hence use the BLEND_RGB_ADD flag.
I created a fourth surface since you wanted a white background.

How to center text inside a shape?

I want to display a number inside a circle.
The number must be centered (x,y).
How to do it?
import pygame, sys
pygame.init()
screen= pygame.display.set_mode((0, 0))
black= (0,0,0)
white= (255,255,255)
red= (255,0,0)
number= "8"
bigfont = pygame.font.SysFont("arial", 50)
text = bigfont.render(number, True, white)
def draw():
pygame.draw.circle(screen, red, (300,300), 200)
screen.blit(text, (300,300))
pygame.display.update()
Get the bounding rectangle of the text and set the center of the rectangle by the center of the text. Use the rectangle to blit the text:
text_rect = text.get_rect()
text_rect.center = (300, 300)
screen.blit(text, text_rect)
The same with one line of code:
screen.blit(text, text.get_rect(center = (300, 300)))
Use this code in a function:
def draw_circle(x, y, text):
pygame.draw.circle(screen, red, (x, y), 200)
screen.blit(text, text.get_rect(center = (x, y)))
See pygame.Surface.blit:
[...] The dest argument can either be a pair of coordinates representing the position of the upper left corner of the blit or a Rect, where the upper left corner of the rectangle will be used as the position for the blit.
Minimal example:
import pygame
pygame.init()
window = pygame.display.set_mode((500, 500))
font = pygame.font.SysFont(None, 100)
clock = pygame.time.Clock()
text = font.render("Text", True, (255, 255, 0))
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window_center = window.get_rect().center
window.fill(0)
pygame.draw.circle(window, (255, 0, 0), window_center, 100)
window.blit(text, text.get_rect(center = window_center))
pygame.display.flip()
clock.tick(60)
pygame.quit()
exit()
To centre PyGame text around point x_pos, y_pos:
Get the dimensions of the text object: width, height = text.get_rect()[2:4]
When you render (screen.blit()) the image, shift the coordinates back by half the width and half the height: screen.blit(text, (x_pos - int(width / 2), y_pos - int(height / 2)))

why when calling font.render () does the program return an error?

i am trying to learn some of the basics of pygame via the following pdf: https://buildmedia.readthedocs.org/media/pdf/pygame/latest/pygame.pdf
and I stopped on page 29 where it shows me that the Rect class defines 4 cornerpoints, 4 mid points and 1 centerpoint. but when I start the program it gives me an error saying No module named 'rect' and if i delete it says font is not defined what should I add to make it work correctly?
import pygame
from pygame.locals import *
from rect import *
def draw_point(text, pos):
img = font.render(text, True, BLACK)
pygame.draw.circle(screen, RED, pos, 3)
screen.blit(img, pos)
pygame.init()
GRAY = (125, 125, 125)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
screen = pygame.display.set_mode((640, 240))
rect = Rect(50, 40, 250, 80)
pts = ('topleft', 'topright', 'bottomleft', 'bottomright', 'midtop', 'midright', 'midbottom', 'midleft', 'center')
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
screen.fill(GRAY)
pygame.draw.rect(screen, GREEN, rect, 4)
for pt in pts:
draw_point(pt, eval('rect.'+pt))
pygame.display.flip()
pygame.quit()
Keep reading that book; The section 3.9 The common code contains the definition of rect.py:
import pygame
from pygame.locals import *
from random import randint
width = 500
height = 200
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
MAGENTA = (255, 0, 255)
CYAN = (0, 255, 255)
BLACK = (0, 0, 0)
GRAY = (150, 150, 150)
WHITE = (255, 255, 255)
dir = {K_LEFT: (-5, 0), K_RIGHT: (5, 0), K_UP: (0, -5), K_DOWN: (0, 5)}
pygame.init()
screen = pygame.display.set_mode((width, height))
font = pygame.font.Font(None, 24)
running = True
Once you create that file you'll be fine.
You must define a font
for example:
font = pygame.font.SysFont("arial", 35)
game_over_text = "Press Space to Start"
game_over_label = font.render(game_over_text, 1, (255,255,255))
window.blit(game_over_label, (WIDTH-550, HEIGHT-400))

How do I draw text onto the screen in pygame?

I'm trying to just draw any text on to the screen in pygame but when I run the program it just runs normally but no text appears on the screen. Is there something I'm doing wrong?
import pygame, random, sys
from pygame.locals import *
pygame.init()
#set constants
WINDOWWIDTH = 600
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 255)
FPS = 40
BLACK = (0,0,0)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
#set variables
rectY1 = 200
rectY2 = 200
Y1change = 0
Y2change = 0
ballX = 320
ballY = 240
ballXvel = 0
ballYvel = 0
paddle1 = pygame.Rect(18,rectY1,10,100)
paddle2 = pygame.Rect(620,rectY2,10,100)
ball = pygame.Rect(ballX,ballY,30,30)
font = pygame.font.SysFont(None, 48)
#create shapes
def drawshapes():
pygame.draw.rect(DISPLAY, WHITE, paddle1)
pygame.draw.rect(DISPLAY, WHITE, paddle2)
pygame.draw.rect(DISPLAY, WHITE, ball)
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
#set up display
DISPLAY = pygame.display.set_mode((640,480),0,32)
pygame.display.set_caption('Pong')
fpsClock = pygame.time.Clock()
drawText('bruh', font, DISPLAY, (200), (200))
pygame.display.update
idk if this really is the loop you are talking about but here it is:
running = True
while running:
# RGB - Red, Green, Blue
screen.fill((0, 0, 128 ))
#background Image
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

Creating a rect grid in Pygame

I need to create a clickable 8 by 8 grid in pygame.
Right now I have something like this:
#!/usr/bin/python2
#-------------------------------------------------------------------------------
# Imports & Inits
import pygame, sys
from pygame.locals import *
pygame.init()
#-------------------------------------------------------------------------------
# Settings
WIDTH = 105
HEIGHT = 105
FPS = 60
#-------------------------------------------------------------------------------
# Screen Setup
WINDOW = pygame.display.set_mode([WIDTH,HEIGHT])
CAPTION = pygame.display.set_caption('Test')
SCREEN = pygame.display.get_surface()
TRANSPARENT = pygame.Surface([WIDTH,HEIGHT])
TRANSPARENT.set_alpha(255)
TRANSPARENT.fill((255,255,255))
#-------------------------------------------------------------------------------
# Misc stuff
rect1 = pygame.draw.rect(SCREEN, (255, 255, 255), (0,0, 50, 50))
rect2 = pygame.draw.rect(SCREEN, (255, 255, 255), (0,55, 50, 50))
rect3 = pygame.draw.rect(SCREEN, (255, 255, 255), (55,0, 50, 50))
rect4 = pygame.draw.rect(SCREEN, (255, 255, 255), (55,55, 50, 50))
...
#-------------------------------------------------------------------------------
# Refresh Display
pygame.display.flip()
#-------------------------------------------------------------------------------
# Main Loop
while True:
pos = pygame.mouse.get_pos()
mouse = pygame.draw.circle(TRANSPARENT, (0, 0, 0), pos , 0)
# Event Detection---------------
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
if rect1.contains(mouse):
rect1 = pygame.draw.rect(SCREEN, (155, 155, 155), (0,0, 50, 50))
pygame.display.flip()
Now, in my original code, I have far more rectangles and I need a way to do something like this:
for i in rectangles:
if i hasbeenclickedon:
change color
Obviously, my solution is far too static.
So, how could I accomplish this?
Though your solution is indeed a little cumbersome, I'd first say
rectangles = (rect1, rect2, ...)
then you can iterate over them as intended.
Try sth like
pos = pygame.mouse.get_pos()
for rect in rectangles:
if rect.collidepoint(pos):
changecolor(rect)
You'd have to implement the changecolor method, of course.
Generally, I'd recommend creating a class for you clickable fields that defines a method changecolor.
Simple 'human' colors:
Color("red")
Color(255,255,255)
Color("#fefefe")
Use:
import pygame
# This makes event handling, rect, and colors simpler.
# Now you can refer to `Sprite` or `Rect()` vs `pygame.sprite.Sprite` or `pygame.Rect()`
from pygame.locals import *
from pygame import Color, Rect, Surface
pygame.draw.rect(screen, Color("blue"), Rect(10,10,200,200), width=0)
pygame.draw.rect(screen, Color("darkred"), Rect(210,210,400,400), width=0)

Categories

Resources