Is it possible to call object from another object - python

I am trying to make a class for colors in pygame.
This is what I have now.
class color:
white = (255, 255, 255)
black = (0, 0, 0)
red = (200, 0 ,0)
green = (0, 200, 0)
blue = (0, 0, 200)
brightRed = (255, 0, 0)
darkRed = (127, 0, 0)
color = color()
print (color.brightRed)
And this as expected will print (255, 0, 0).
I wonder is it possible to make something like this:
color = color()
print(color.red)
print(color.red.bright)
print(color.red.dark)
So I can get the next prints:
(200, 0 ,0)
(255, 0, 0)
(127, 0, 0)
I know that this example is pointless, but I could make something else if it is possible.

You can define another class
class Red:
bright = (255, 0, 0)
dark = (127, 0, 0)
normal = (200, 0, 0)
class color:
white = (255, 255, 255)
black = (0, 0, 0)
red = Red
green = (0, 200, 0)
blue = (0, 0, 200)
brightRed = Red.bright
darkRed = Red.dark
color = color()
print(color.red.normal)
print(color.red.bright)
print(color.red.dark)
You can't have color.red be both a user-defined class and a tuple at the same time, so you can't use color.red in place of color.red.normal. But you could have normalRed = Red.normal and then use color.normalRed.

Related

In Pygame, how would I fill a drawn circle with an image instead of a colour? [duplicate]

I need to create a surface that has a bounding circle. Anything drawn on that surface should not be visible outside that bounding circle. I've tried using masks, subsurfaces, srcalpha, etc., but nothing seems to work.
My attempt:
w = ss.get_width ()
h = ss.get_height ()
TRANSPARENT = (255, 255, 255, 0)
OPAQUE = ( 0, 0, 0, 225)
crop = pygame.Surface ((w, h), pygame.SRCALPHA, ss)
crop.fill (TRANSPARENT)
c = round (w / 2), round (h / 2)
r = 1
pygame.gfxdraw. aacircle (crop, *c, r, OPAQUE)
pygame.gfxdraw.filled_circle (crop, *c, r, OPAQUE)
ss = crop.subsurface (crop.get_rect ())
App.set_subsurface (self, ss)
Later...
self.ss.fill (BLACK)
self.ss.blit (self.background, ORIGIN)
The background is a square image. It should be cropped into the shape of a circle and rendered on screen
Solution based on notes from Rabbid76:
def draw_scene (self, temp=None):
if temp is None: temp = self.ss
# 1. Draw everything on a surface with the same size as the window (background and scene).
size = temp.get_size ()
temp = pygame.Surface (size)
self.draw_cropped_scene (temp)
# 2. create the surface with the white circle.
self.cropped_background = pygame.Surface (size, pygame.SRCALPHA)
self.crop ()
# 3. blit the former surface on the white circle.
self.cropped_background.blit (temp, ORIGIN, special_flags=pygame.BLEND_RGBA_MIN)
# 4. blit the whole thing on the window.
self.ss.blit (self.cropped_background, ORIGIN)
def draw_cropped_scene (self, temp): App.draw_scene (self, temp)
An example implementation of crop() is:
def crop (self):
o, bounds = self.bounds
bounds = tr (bounds) # round elements of tuple
pygame.gfxdraw. aaellipse (self.cropped_background, *bounds, *bounds, OPAQUE)
pygame.gfxdraw.filled_ellipse (self.cropped_background, *bounds, *bounds, OPAQUE)
The background is a square image. It should be cropped into the shape of a circle and rendered on screen
You can achieve this by using the blend mode BLEND_RGBA_MIN (see pygame.Surface.blit).
Create a transparent pygame.Surface with the same size as self.background. Draw a whit circle in the middle of the Surface and blend the background on this Surface using the blend mode BLEND_RGBA_MIN. Finally you can blit it on the screen:
size = self.background.get_size()
self.cropped_background = pygame.Surface(size, pygame.SRCALPHA)
pygame.draw.ellipse(self.cropped_background, (255, 255, 255, 255), (0, 0, *size))
self.cropped_background.blit(self.background, (0, 0), special_flags=pygame.BLEND_RGBA_MIN)
self.ss.fill(BLACK)
self.ss.blit(self.cropped_background, ORIGIN)
Minimal example: repl.it/#Rabbid76/PyGame-ClipCircularRegion-1
import pygame
pygame.init()
window = pygame.display.set_mode((250, 250))
background = pygame.Surface(window.get_size())
for x in range(5):
for y in range(5):
color = (255, 255, 255) if (x+y) % 2 == 0 else (255, 0, 0)
pygame.draw.rect(background, color, (x*50, y*50, 50, 50))
size = background.get_size()
cropped_background = pygame.Surface(size, pygame.SRCALPHA)
pygame.draw.ellipse(cropped_background, (255, 255, 255, 255), (0, 0, *size))
cropped_background.blit(background, (0, 0), special_flags=pygame.BLEND_RGBA_MIN)
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill(0)
window.blit(cropped_background, (0, 0))
pygame.display.flip()
See Also How to fill only certain circular parts of the window in pygame?

Circuitpython | Traceback ValueError | >BUTTON_A is being used<

Context
I hope I can get some help. Thanks in advance
I recently acquired a Circuit Playground Express as a project for college, and I am having some issues programming with it, specially because the Traceback is constantly giving me an error which I don't know how to fix, and I have tried several things now, and couldn't get anything different.
I am using a IDE for CircuitPython called "Mu Editor" https://codewith.mu/en/download, which provides me some interesting tools that have made my work kind of easier. (I have to clarify I have never coded in Python, so I am kinda lost in everything)
Error
Traceback (ultima llamada reciente):
Archivo "code.py", línea 61, en <module>
ValueError: BUTTON_A está siendo utilizado
El código terminó de ejecutar.
Code which is getting error
I am having the issue specially on these pieces of code:
Variable a_but, which will allow me to use the BUTTON_A of the Circuit Playground, so it does something when it is pressed
a_but = DigitalInOut(board.D4)
a_but.direction = Direction.INPUT
a_but.pull = Pull.DOWN
Variable b_but, which will allow me to use the BUTTON_B of the Circuit Playground, so it does something when it is pressed
b_but = DigitalInOut(board.D5)
b_but.direction = Direction.INPUT
b_but.pull = Pull.DOWN
Variable pixels that will allow me to access to modify the neopixels of the Circuit Playground
pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=1.0)
Examples of the above variables when being used:
a_but and b_but
while True:
if a_but.value:
print("Button A pressed")
if b_but.value:
print("Button B pressed")
pixels
if temp < 36:
pixels[0] = (0, 0, 255)
pixels[1] = (0, 0, 255)
pixels[2] = (0, 0, 255)
elif temp >= 36 and temp <= 37.2:
pixels[3] = (0, 0, 255)
pixels[4] = (0, 0, 255)
pixels[5] = (0, 0, 255)
pixels[6] = (0, 0, 255)
else:
pixels[7] = (0, 0, 255)
pixels[8] = (0, 0, 255)
pixels[9] = (0, 0, 255)
Here is the complete code in case you want to take a look (It might have some errors since that error is blocking me from moving on):
import time
import analogio
import board
import neopixel
import pulseio
import digitalio
from digitalio import DigitalInOut, Direction, Pull
import adafruit_irremote
import adafruit_thermistor
from adafruit_circuitplayground import cp
def sign(value):
if value > 0:
return 1
if value < 0:
return -1
return 0
def pulse_test():
# Turn only pixel #1 green
pixels[1] = (0, 255, 0)
# How many light readings per sample
NUM_OVERSAMPLE = 10
# How many samples we take to calculate 'average'
NUM_SAMPLES = 20
samples = [0] * NUM_SAMPLES
i = True
while i:
for i in range(NUM_SAMPLES):
# Take NUM_OVERSAMPLE number of readings really fast
oversample = 0
for s in range(NUM_OVERSAMPLE):
oversample += float(light.value)
# and save the aver age from the oversamples
samples[i] = oversample / NUM_OVERSAMPLE # Find the average
mean = sum(samples) / float(len(samples)) # take the average
print((samples[i] - mean,)) # 'center' the reading
if i > 0:
# If the sign of the data has changed munus to plus
# we have one full waveform (2 zero crossings), pulse LED
if sign(samples[i] - mean) <= 0 and sign(samples[i - 1] - mean) > 0:
pixels[9] = (200, 0, 0) # Pulse LED
else:
pixels[9] = (0, 0, 0) # Turn LED off
time.sleep(0.025) # change to go faster/slower
if b_but.value:
i = False
pixels[1] = (0, 0, 0)
pixels[9] = (0, 0, 0)
a_but = DigitalInOut(board.D4)
a_but.direction = Direction.INPUT
a_but.pull = Pull.DOWN
b_but = DigitalInOut(board.D5)
b_but.direction = Direction.INPUT
b_but.pull = Pull.DOWN
pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=1.0)
light = analogio.AnalogIn(board.LIGHT)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
GREEN = (0, 255, 0)
CYAN = (0, 255, 255)
BLUE = (0, 0, 255)
PURPLE = (180, 0, 255)
PIXELS_OFF = (0, 0, 0)
pulsein = pulseio.PulseIn(board.IR_RX, maxlen=120, idle_state=True)
decoder = adafruit_irremote.GenericDecode()
while True:
pulse = decoder.read_pulses(pulsein)
try:
received_code = decoder.decode_bits(pulse)
print("\n\nSeñal Adquirida : ", received_code)
if received_code == (223, 32, 111, 144):
print("¡Sospecha de infeccion detectada!\n\n")
for i in range(3):
pixels.fill(YELLOW)
pixels.show()
time.sleep(0.05)
pixels.fill(PIXELS_OFF)
pixels.show()
time.sleep(0.05)
print("¿Desea realizar un testeo basico?:")
print("\n\n Si. Presione A\n No. Presione B")
pixels[0] = (0, 255, 0)
pixels[1] = (0, 255, 0)
pixels[2] = (0, 255, 0)
pixels[3] = (0, 255, 0)
pixels[4] = (0, 255, 0)
pixels[5] = (255, 0, 0)
pixels[6] = (255, 0, 0)
pixels[7] = (255, 0, 0)
pixels[8] = (255, 0, 0)
pixels[9] = (255, 0, 0)
while True:
if a_but.value:
testeo_respuesta = True
for x in range(2):
pixels.fill(PIXELS_OFF)
pixels.show()
for i in range(9):
pixels[10] = (0, 255, 0)
time.sleep(0.075)
break
if b_but.value:
testeo_respuesta = False
for x in range(2):
pixels.fill(PIXELS_OFF)
pixels.show()
for i in range(9):
pixels[i] = (255, 0, 0)
time.sleep(0.075)
break
time.sleep(0.075)
pixels.fill(PIXELS_OFF)
pixels.show()
if testeo_respuesta:
for test_num in range(19):
regTemp = [cp.temperature] * test_num
time.sleep(1.0)
for k in range(19):
pixels[0] = (0, 0, 255)
temp = 0
if temp < regTemp[k]:
temp = regTemp[k]
pixels[0] = (0, 0, 0)
time.sleep(0.5)
if temp < 36:
pixels[0] = (0, 0, 255)
pixels[1] = (0, 0, 255)
pixels[2] = (0, 0, 255)
pixels[3] = (0, 0, 0)
pixels[4] = (0, 0, 0)
pixels[5] = (0, 0, 0)
pixels[6] = (0, 0, 0)
pixels[7] = (0, 0, 0)
pixels[8] = (0, 0, 0)
pixels[9] = (0, 0, 0)
resultado = True
elif temp >= 36 and temp <= 37.2:
pixels[0] = (0, 0, 0)
pixels[1] = (0, 0, 0)
pixels[2] = (0, 0, 0)
pixels[3] = (0, 0, 255)
pixels[4] = (0, 0, 255)
pixels[5] = (0, 0, 255)
pixels[6] = (0, 0, 255)
pixels[7] = (0, 0, 0)
pixels[8] = (0, 0, 0)
pixels[9] = (0, 0, 0)
resultado = False
else:
pixels[0] = (0, 0, 0)
pixels[1] = (0, 0, 0)
pixels[2] = (0, 0, 0)
pixels[3] = (0, 0, 0)
pixels[4] = (0, 0, 0)
pixels[5] = (0, 0, 0)
pixels[6] = (0, 0, 0)
pixels[7] = (0, 0, 255)
pixels[8] = (0, 0, 255)
pixels[9] = (0, 0, 255)
resultado = True
else:
print("¡No hay riesgo detectado!")
for i in range(3):
pixels.fill(GREEN)
pixels.show()
time.sleep(0.05)
pixels.fill(PIXELS_OFF)
pixels.show()
time.sleep(0.05)
except:
continue
time.sleep(0.025)

Using Arrays for backgrounds color changes on rectangles

Still new to using python and have a question. I'm working on changing colors on a screen using an array.
For example:
RED = (255,0,0)
BLACK= (0,0,0)
ColorArray = [RED,BLACK]
pygame.draw.rect(Page1,ColorArray[1],(80,60,100,10))
pygame.draw.rect(Page1,ColorArray[0],(80,60,100,10))
When I use my array, I get an error for an invalid color argument. Is there a workaround for this? When I just put RED or BLACK in the color location, everything works great.
Thanks,
Could you share your full code, because it works for me:
import pygame as pg
from pygame.locals import *
Page1 = pg.display.set_mode((500, 500), 0, 32)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
ColorArray = [RED, BLACK]
Page1.fill(WHITE)
pg.draw.rect(Page1, ColorArray[0], (80, 60, 100, 10))
pg.draw.rect(Page1, ColorArray[1], (100, 80, 100, 10))
pg.display.update()
while True:
for event in pg.event.get():
if event.type == QUIT:
pg.quit()

How to break your code up into smaller chunks, turn those chunks of code into functions, and then call the functions from within main in python?

I need a way to break my code up into smaller chunks, turn those chunks of code into functions, and then call the functions from within main.
import picture
def main():
# Size of the canvas
canvaswidth = 500
canvasheight = 500
canvas = picture.Picture(canvaswidth, canvasheight)
# My color pallette
black = (0, 0, 0)
purple = (128, 0, 128)
cream = (255, 255, 240)
brown = (102,51, 0)
blue = (0, 76, 173)
red = (255, 0, 0)
yellow = (255, 255, 0)
canvas.setFillColor(brown)
canvas.setOutlineColor(black)
canvas.setPenWidth(3)
canvas.drawRectFill(175,75,100,300)
canvas.setFillColor(red)
canvas.setOutlineColor(black)
canvas.setPenWidth(3)
canvas.drawPolygonFill([175,75,225,25,275,75])
canvas.setFillColor(red)
canvas.setOutlineColor(black)
canvas.setPenWidth(3)
canvas.drawPolygonFill([175,430,200,300,250,300,275,430])
canvas.setFillColor(red)
canvas.setOutlineColor(black)
canvas.setPenWidth(3)
canvas.drawPolygonFill([125,400,150,300,175,300,175,375])
canvas.setFillColor(red)
canvas.setOutlineColor(black)
canvas.setPenWidth(3)
canvas.drawPolygonFill([275,375,275,300,300,300,325,400])
canvas.display()
main()
Without knowing more about your purpose and motivation, it's difficult to give you an answer. Did you mean something like the following?
# Size of the canvas
canvaswidth = 500
canvasheight = 500
canvas = picture.Picture(canvaswidth, canvasheight)
# My color pallette
black = (0, 0, 0)
purple = (128, 0, 128)
cream = (255, 255, 240)
brown = (102,51, 0)
blue = (0, 76, 173)
red = (255, 0, 0)
yellow = (255, 255, 0)
def doit(canvas, fill_color, draw_method, *data):
canvas.setFillColor(fill_color)
canvas.setOutlineColor(black)
canvas.setPenWidth(3)
getattr(canvas, draw_method)(*data)
def main():
canvas = picture.Picture(canvaswidth, canvasheight)
doit(canvas, brown, 'drawRectFill', 175,75,100,300)
doit(canvas, red, 'drawPolygonFill', [175,75,225,25,275,75])
doit(canvas, red, 'drawPolygonFill', [175,430,200,300,250,300,275,430])
doit(canvas, red, 'drawPolygonFill', [125,400,150,300,175,300,175,375])
doit(canvas, red, 'drawPolygonFill', [275,375,275,300,300,300,325,400])
canvas.display()

accessing each element in a numpy array

I'm attempting to remove stray white pixels from an alpha channel mask by looking at the adjacent pixels, but have been getting TypeEror: 'numpy.ndarray' object is not callable
I made an array using pygame.surfarray:
alphachannel3d = pygame.surfarray.pixels3d(alphachannel)
then attempt to step through it and change pixel values from white to black:
if (alphachannel3d[x] == (0, 0, 0)) & (alphachannel3d[x + 3] == (255, 255, 255)) & (alphachannel3d[x -3]==(255, 255, 255)):
alphachannel3d[x] = (255, 255, 255)
Here is the loop:
x=1
while 1:
count = x
print 'count is', count
print 'waiting 5 seconds'
pygame.time.wait(5000)
img = cam.get_image()
imgarray = pygame.PixelArray(img)
alphachannelarray = basearray.compare(imgarray, distance=0.09, weights=(0.01, 0.01, 0.01))
alphachannel = alphachannelarray.make_surface()
alphachannel3d = pygame.surfarray.pixels3d(alphachannel)
if (alphachannel3d[x] == (0, 0, 0)) & (alphachannel3d[x + 3] == (255, 255, 255)) & (alphachannel3d[x -3]==(255, 255, 255)):
alphachannel3d[x] = (255, 255, 255)
alphachannel = pygame.surfarray.make_surface(alphachannel3d)
srfcScreen.blit(alphachannel, (0,0))
print 'screen blitted'
pygame.display.flip()
print 'display flipped'
x = x+1
Based on your comment, I'm going to give the following speculative answer (without testing it):
if np.all(alphachannel3d[x] == (0, 0, 0)) & np.all(alphachannel3d[x + 3] == (255, 255, 255)) & np.all(alphachannel3d[x -3]==(255, 255, 255)):
alphachannel3d[x] = (255, 255, 255)

Categories