Pygame buttons functionality and correcting grid select mouse function - python

I've added two rectangles, red and green to the top of the following code, and for some reason my code, which otherwise worked, does not now. The grid cells should go RED when clicked, but the clicking is skewed. Can anyone advise on the problem? I have two issues:
An upvote to the first one to spot and point out the error, unless I get it first!
I also want to add text (user 1 and user 2) to the rectangles and make them clickable. On clicking, the user selects a random grid cell (which turns either red or green)
Code as follows:
import pygame
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
pygame.init()
size = (350, 350)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
done = False
clock = pygame.time.Clock()
width=22
height=22
margin=12
grid=[]
#Loop for each row in the list
for row in range(7):
#for each row, create a list that will represent an entire row
grid.append([])
#loop for each column
for column in range(7):
#add the number zero to the current row
grid[row].append(0)
#set row 1, column 5 to one
#grid[1][3]=1
#print(grid[1][3]) #this is the 2nd row and the 4th element along (0...1 row and 0...1...2....3 Column)
# -------- Main Program Loop -----------
while not done:
#ALL EVENT PROCESSING SHOULD GO BELOW THIS LINE
# --- Main event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
#************CODE ADDED HERE**********************
elif event.type == pygame.MOUSEBUTTONDOWN:
#print("user clicked the screen")
pos=pygame.mouse.get_pos()
#x = grid[0]
#y= grid[1]
#print(pos)
#CHANGE THE X and Y screen coordinates as in the comments above to grid coordinates
column=pos[0]//(width+margin+50)
row=pos[1]//(height+margin+60)
#set the location to one (when selected by the mouse)
grid[row][column]=1
#print("User click ", pos, "Grid coordinates:", row+1, column+1)
# --- Game logic should go here
# --- Screen-clearing code goes here
# Here, we clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
# If you want a background image, replace this clear with blit'ing the
# background image.
screen.fill(BLACK)
# --- Drawing code should go here
#Drawing the red and Green rectangles
pygame.draw.rect(screen,RED, [0,0,120,50])
pygame.draw.rect(screen,GREEN, [240,0,120,50])
for row in range(7):
#the column number - this refers to the number of columns it will produce. 2, for example, will produce only 2 columns
for column in range(7):
color = WHITE
if grid[row][column] ==1:
color = RED
#****MOVING THE REST OF THE GRID DOWN*****
#the 60 is the margin from the top
#the 50 is the margin from the left
pygame.draw.rect(screen,color,[(margin + width) * column + margin+50, (margin + height) * row + margin+60,width,height])
#*******PRINTING TEXT TO THE SCREEN**********
# Select the font to use, size, bold, italics
#font = pygame.font.SysFont('Calibri', 25, True, False)
#text = font.render("a", True, BLACK)
# Put the image of the text on the screen at 250x250
#screen.blit(text, [25, 25])
# --- This bit updates the screen with what we've drawn.
pygame.display.flip()
# --- Limit to 60 frames per second
clock.tick(60)
# Close the window and quit.
pygame.quit()

This is by no means an ideal way to achieve your goal, but I tried to keep the code as consistent with yours as possible. Let me know if you have any questions about how this works. I will do my best to answer quickly.
import pygame
from pygame.locals import *
pygame.init()
# first we define some constants
# doing this will reduce the amount of 'magic' numbers throughout the code
WINWIDTH = 350
WINHEIGHT = 350
WINSIZE = (WINWIDTH, WINHEIGHT)
CELLWIDTH = 22
CELLHEIGHT = 22
CELLSIZE = (CELLWIDTH, CELLHEIGHT)
CELLMARGINX = 12 # number of pixels to the left and right of each cell
CELLMARGINY = 12 # number of pixels to the top and bottom of each cell
SCREENPADX = 60 # number of pixels between the GRID and the left and right of the window
SCREENPADY = 70 # number of pixels between the GRID and the top and bottom of the window
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
DONE = False # is our program finished running?
# information about the two buttons (red and green)
REDBUTTON = (0, 0, 120, 50)
GREENBUTTON = (240, 0, 120, 50)
# create the WINDOW and CLOCK
WINDOW = pygame.display.set_mode(WINSIZE)
pygame.display.set_caption('My Game')
CLOCK = pygame.time.Clock()
CURRENTCOLOR = RED # which color is active
# setting up the GRID
# cells can be accessed by GRID[row][col] ie. GRID[3][4] is the 3rd row and 4th column
# each cell contains [x, y, color]
# where x is the x position on the screen
# y is the y position on the screen
# color is the current color of the cell
GRID = []
for y in range(7):
row = []
for x in range(7):
row.append([x * (CELLWIDTH + CELLMARGINX) + SCREENPADX, y * (CELLHEIGHT + CELLMARGINY) + SCREENPADY, WHITE])
GRID.append(row)
# main loop
while not DONE:
# process all events
for event in pygame.event.get():
if event.type == QUIT: # did the user click the 'x' to close the window
DONE = True
if event.type == MOUSEBUTTONDOWN:
# get the position of the mouse
mpos_x, mpos_y = event.pos
# check if REDBUTTON was clicked
button_x_min, button_y_min, button_width, button_height = REDBUTTON
button_x_max, button_y_max = button_x_min + button_width, button_y_min + button_height
if button_x_min <= mpos_x <= button_x_max and button_y_min <= mpos_y <= button_y_max:
CURRENTCOLOR = RED
# check if GREENBUTTON WAS CLICKED
button_x_min, button_y_min, button_width, button_height = GREENBUTTON
button_x_max, button_y_max = button_x_min + button_width, button_y_min + button_height
if button_x_min <= mpos_x <= button_x_max and button_y_min <= mpos_y <= button_y_max:
CURRENTCOLOR = GREEN
# calculations for clicking cells
mpos_x -= SCREENPADX # mouse position relative to the upper left cell
mpos_y -= SCREENPADY # ^ same
col = mpos_x // (CELLWIDTH + CELLMARGINX) # which cell is the mouse clicking
row = mpos_y // (CELLHEIGHT + CELLMARGINY) # ^ same
# make sure the user clicked on the GRID area
if row >= 0 and col >= 0:
try:
# calculate the boundaries of the cell
cell_x_min, cell_y_min = col * (CELLHEIGHT + CELLMARGINY), row * (CELLWIDTH + CELLMARGINX)
cell_x_max = cell_x_min + CELLWIDTH
cell_y_max = cell_y_min + CELLHEIGHT
# now we will see if the user clicked the cell or the margin
if cell_x_min <= mpos_x <= cell_x_max and cell_y_min <= mpos_y <= cell_y_max:
GRID[row][col][2] = CURRENTCOLOR if event.button == 1 else WHITE
else:
# the user has clicked the margin, so we do nothing
pass
except IndexError: # clicked outside of the GRID
pass # we will do nothing
# logic goes here
# drawing
WINDOW.fill(BLACK)
pygame.draw.rect(WINDOW, RED, REDBUTTON)
pygame.draw.rect(WINDOW, GREEN, GREENBUTTON)
for row in GRID:
for x, y, color in row:
pygame.draw.rect(WINDOW, color, (x, y, CELLWIDTH, CELLHEIGHT))
pygame.display.flip()
CLOCK.tick(60)
pygame.quit()

Related

How do I toggle the colors of a tile in pygame?

So I am trying to make a mini game in which you have to answer some questions and based on those you draw a qrcode. For this I have to be able to toggle between white and black as the user should have more than one shot at guessing the answer of a question.
Here is the code:
back = pygame.image.load("qrcode3outerM.jpg").convert()
def draw_scene(screen):
screen.fill(WHITE)
#draw the outer from a picture because I am too lazy to generate it
screen.blit(back,(0,0))
for row in range(size):
for col in range(size):
rect = pygame.Rect((MARGIN + row)*BOX_SIZE,(MARGIN+col)*BOX_SIZE, BOX_SIZE, BOX_SIZE)
pygame.draw.rect(screen, BLACK, rect, 1)
# if answ[row][col]:
# pygame.draw.rect(screen, BLACK, ((MARGIN + col) * BOX_SIZE, (MARGIN + row)*BOX_SIZE, BOX_SIZE, BOX_SIZE))
if __name__ == '__main__':
done = False
draw_scene(screen)
while not done:
state = 0
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
#get the location of the cell in terms of tiles where the mouse was clicked
elif event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
x = pos[0] // BOX_SIZE - 12 #magic numbers here to make it work for the time being
y = pos[1] // BOX_SIZE - 12
state = screen.get_at((x,y))
print(f'Current state of the pixel {state}')
print(f'coordinate of the mouse press: {x} {y} ')
print(answ[x][y])
print('black' if answ[x][y] else 'white')
user_answ[x][y] = state
pygame.draw.rect(screen, BLACK if state else WHITE, ((MARGIN + x) * BOX_SIZE, (MARGIN + y) * BOX_SIZE, BOX_SIZE, BOX_SIZE))
pygame.display.update()
pygame.quit()
Here I am drawing all of the tiles white first and then black at the location at which the mouse was pressed.
My idea was to get the current state of each cell using the get_at() method but for some reason even after I click a cell and it turns black on my screen the get_at() method still returns (255,255,255,255).
The question is: why does it still return white when it should return black
Also, if you have a better method of toggling please let me know
You calculate x and y as follows:
x = pos[0] // BOX_SIZE - 12 #magic numbers here to make it work for the time being
y = pos[1] // BOX_SIZE - 12
x and y are not the position of the tile on the screen, but the column and row of the tile. The top left position of the tile is ((MARGIN + x) * BOX_SIZE, (MARGIN + y) * BOX_SIZE). You don't need to determine the color of the pixel at all, because the state of the tile is stored in user_answ[x][y]. All you need to do is get the state from user_answ, then invert the state and write the new state back:
state = user_answ[x][y]
state = not state
user_answ[x][y] = state

How to use time.get_tick()

When I left click, a line should show from the origin, and if left clicked with two seconds, white circles should appear. After two seconds, another line is drawn and then after two seconds the previous line should disappear. Right now, when I click, a line shows from the origin and then when I click again, two lines show.
from pygame import *
import random
init()
size = width, height = 700, 700
screen = display.set_mode(size)
button = 0
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
color = RED
mx = 0
my = 0
cx = 0
cy = 0
def drawScene(screen, button):
if button == 1:
draw.circle(screen, RED, (mx,my), 5)
draw.line(screen, color, (mx,my),(lx,ly), 2)
cx = lx
cy = ly
draw.circle(screen, RED, (mx,my), 5)
display.flip()
if button == 3:
draw.line(screen, color, (mx,my),(lx,ly), 2)
draw.circle(screen, color, (lx,ly), 5)
display.flip()
running = True
myClock = time.Clock()
# Game Loop
while running:
lx = mx
ly = my
for evnt in event.get(): # checks all events that happen
if evnt.type == QUIT:
running = False
if evnt.type == MOUSEBUTTONDOWN:
mx,my = evnt.pos
button = evnt.button
if time.get_ticks() <= 2000 and time.get_ticks() > 0 :
draw.circle(screen, WHITE, (mx,my), 5)
else:
draw.line(screen, WHITE, (cx,cy),(lx,ly), 2)
if button == 3:
if color == RED:
color = BLUE
elif color == BLUE:
color = GREEN
elif color == GREEN:
color = RED
drawScene(screen, button)
myClock.tick(60)
quit()
Lets start with setting up a basic window first
from pygame import *
import random
init()
size = width, height = 700, 700
screen = display.set_mode(size)
button = 0
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
color = RED
running = True
myClock = time.Clock()
def drawScene():
screen.fill(BLACK)
display.update() #update is the same as flip()
# Game Loop
while running:
myClock.tick(60)
drawScene()
for evnt in event.get(): # checks all events that happen
if evnt.type == QUIT:
running = False
After helping someone else with this problem (the question i linked), i found that using lists would be the best idea
So lets create a list for the points where the circles go and lines connect to
points = [] #put this before the drawScene function so it can reference it
Now, when the user clicks, we want to add the point to the list and draw it on the screen
def drawScene():
screen.fill(BLACK)
for point in points:
draw.circle(screen,color,point,5)
display.update() #update is the same as flip()
if evnt.type == MOUSEBUTTONDOWN:
points.append(evnt.pos)
now we can create points on the screen by clicking. Lets create the lines
We want to start at the origin so add the origin to the list at the start
points = [(0,0)]
Now we want to loop through every point and draw a circle and a line in between. so change the loop to
for i in range(1,len(points)): #loop through all but the first point as you dont want circle at origin
draw.circle(screen,WHITE,points[i],5)
draw.line(screen,color,points[i - 1],points[i])
Now we can draw lines and circles. But we only want to draw the circles if we clicked within 2 seconds, so lets create a timer, we will make one for each line so lets make a list as each line disappears after 2 seconds aswell
timers = []
Once we click, we want to start the timer, we can do that with
if evnt.type == MOUSEBUTTONDOWN:
points.append(evnt.pos)
timers.append(time.get_ticks())
this gets the current time in milliseconds we want to know once its been 2 seconds so if we get the current time and minus the start time, we get the difference so
for i in range(len(timers)-1,-1,-1):
if time.get_ticks() - timers[i] > 2000: #if been 2 seconds
del timers[i] #delete the timer
del points[i + 1] #delete the point for the line
this gets pretty close after 2 seconds the new line moves to the origin, to fix this, we need to delete the origin point
del points[i]
but now after the lines disappear, it starts at the last place clicked instead of the origin. so lets check if there is no lines, make sure the origin is the first point
if len(points) == 1:
points[0] = (0,0)
Awesome, the last thing is the circles appearing within the 2 seconds, which also means more than 1 line so
if points[0] != (0,0) or len(points) > 2:
draw.circle(screen,WHITE,points[i],5)
Here is the full code:
from pygame import *
import random
init()
size = width, height = 700, 700
screen = display.set_mode(size)
button = 0
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
color = RED
running = True
myClock = time.Clock()
points = [(0,0)]
timers = []
def drawScene():
screen.fill(BLACK)
for i in range(1,len(points)): #loop through all but the first point as you dont want circle at origin
if points[0] != (0,0) or len(points) > 2:
draw.circle(screen,WHITE,points[i],5)
draw.line(screen,color,points[i - 1],points[i])
for i in range(len(timers)-1,-1,-1):
if time.get_ticks() - timers[i] > 2000: #if been 2 seconds
del timers[i] #delete the timer
del points[i] #delete the point for the line
if len(points) == 1:
points[0] = (0,0)
display.update() #update is the same as flip()
# Game Loop
while running:
myClock.tick(60)
drawScene()
for evnt in event.get(): # checks all events that happen
if evnt.type == QUIT:
running = False
if evnt.type == MOUSEBUTTONDOWN:
points.append(evnt.pos)
timers.append(time.get_ticks())

Python program game of life

I am currently trying to make conways game of life in python, I am trying to figure out how to make the program read the black squares as on, however I am having no luck, could anyone help. The onoff print currently just prints everything as off (0's) and I want it to print 1's where there is black squares, in order.
import pygame
import random
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
GREY = (0, 210, 230)
WIDTH = 20
HEIGHT = 20
MARGIN = 1
gridsize = 20
onoff = []
grid = []
for row in range(gridsize):
grid.append([])
for column in range(gridsize): # grid
grid[row].append([])
grid[row][column] = 0 # setting value of pixel to off
for x in range(gridsize*gridsize): #onoff update
onoff.append(grid[row][column])
print(onoff)
pygame.init()
WINDOW_SIZE = [21*gridsize, 21* gridsize]
screen = pygame.display.set_mode(WINDOW_SIZE) # screen size
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:# mosue click detection
pos = pygame.mouse.get_pos()
column = pos[0] // (WIDTH + MARGIN)
row = pos[1] // (HEIGHT + MARGIN)
grid[row][column] = 1
print(onoff)
print("Grid coordinates: ", row, column)
for row in range(gridsize):
for column in range(gridsize):
color = WHITE #grid creation
if grid[row][column] == 1:
color = BLACK
pygame.draw.rect(screen,
color,
[(MARGIN + WIDTH) * column + MARGIN, # black rect
(MARGIN + HEIGHT) * row + MARGIN,
WIDTH,
HEIGHT])
clock.tick(60)
pygame.display.flip()
pygame.quit()
onoff = []
grid = []
for row in range(gridsize):
grid.append([])
for column in range(gridsize): # grid
grid[row].append([])
grid[row][column] = 0 # setting value of pixel to off
onoff.append(grid[row][column])
for x in range(len(grid)):
print(grid[x])
its ok i solved it, thanks anyways

Change element in matrix from 0 to 1 when event takes place

I've recently written a program with a list, but now I need to change the list into a matrix. I programmed a grid by drawing rectangles. Now I want to change the color of the rectangle when I click on it. In my program with the list everything worked just fine, but now I have to use a matrix, because I need a matrix for the rest of my program. I've already got a matrix with all zeros, but now I want to change the 0 in to a 1 when I click on a rectangle.
x = 5
y = 5
height = 30
width = 50
size = 20
color = (255,255,255)
new_color = (0,255,0)
screen.fill((0,0,0))
def draw_grid():
for y in range(height):
for x in range(width):
rect = pygame.Rect(x * (size + 1),y * (size + 1),size,size)
pygame.draw.rect(screen,color,rect)
x += 20
y += 20
rects = [[0 for i in range(width)] for j in range(height)]
draw_grid()
while 1:
clock.tick(30)
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
if menu == 'start':
if pygame.mouse.get_pressed()[0]:
mouse_pos = pygame.mouse.get_pos()
for i,(rect,color) in enumerate(rects):
if rect.collidepoint(mouse_pos):
rects[i] = (rect,new_color)
for rect,color in rects:
pygame.draw.rect(screen,color,rect)
pygame.display.flip()
This is the code I used with the list, but I've already replaced the list with a matrix. When I run this code it gives an error:
ValueError: too many values to unpack
What is the best way to solve this problem?
To draw the rects you can iterate over the matrix and depending on the value (0 or 1) draw a white rect or a green rect. (You could also store the colors directly in the matrix, but I don't know if you want to do something else with it.)
To change the color of the clicked cells, you can easily calculate the indexes of the cells by floor dividing the mouse coords by (size+1), e.g. x = mouse_x // (size+1). Then just set matrix[y][x] = 1.
import sys
import pygame
WHITE = pygame.Color('white')
GREEN = pygame.Color('green')
def draw_grid(screen, matrix, size):
"""Draw rectangles onto the screen to create a grid."""
# Iterate over the matrix. First rows then columns.
for y, row in enumerate(matrix):
for x, color in enumerate(row):
rect = pygame.Rect(x*(size+1), y*(size+1), size, size)
# If the color is white ...
if color == 0:
pygame.draw.rect(screen, WHITE, rect)
# If the color is green ...
elif color == 1:
pygame.draw.rect(screen, GREEN, rect)
def main():
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
height = 30
width = 50
size = 20 # Cell size.
matrix = [[0 for i in range(width)] for j in range(height)]
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if pygame.mouse.get_pressed()[0]:
# To change the color, calculate the indexes
# of the clicked cell like so:
mouse_x, mouse_y = pygame.mouse.get_pos()
x = mouse_x // (size+1)
y = mouse_y // (size+1)
matrix[y][x] = 1
screen.fill((30, 30, 30))
# Now draw the grid. Pass all needed values to the function.
draw_grid(screen, matrix, size)
pygame.display.flip()
clock.tick(30)
if __name__ == '__main__':
pygame.init()
main()
pygame.quit()
sys.exit()

Adding gradient to moving objects in pygame

I want to add gradient to the ball in this program & also possibly the waves drawn to fade into the colour of the background (as if glowing) instead of one colour fills.
I've looked at tons of tutorials however none of them are making much sense to my syntax, the general idea to me is confusing as I have moving objects that draw the space I want to add gradient to quite slowly. Can anyone give an insight into how I can do this?
code:
import sys, pygame, math
from pygame.locals import *
# set up of constants
WHITE = (255, 255, 255)
DARKRED = (128, 0, 0)
RED = (255, 0, 0)
BLACK = ( 0, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
BGCOLOR = WHITE
screen = pygame.display.set_mode()
WINDOWWIDTH = 800 # width of the program's window, in pixels
WINDOWHEIGHT = 800 # height in pixels
WIN_CENTERX = int(WINDOWWIDTH / 2) # the midpoint for the width of the window
WIN_CENTERY = int(WINDOWHEIGHT / 2) # the midpoint for the height of the window
screen = pygame.display.get_surface()
FPS = 160 # frames per second to run at
AMPLITUDE = 80 # how many pixels tall the waves with rise/fall.
# standard pygame setup code
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), pygame.RESIZABLE)
pygame.display.set_caption('Window title')
fontObj = pygame.font.Font('freesansbold.ttf', 16)
# variables that track visibility modes
showSine = True
showSquare = True
pause = False
xPos = 0
step = 0 # the current input f
posRecord = {'sin': [], 'square': []} # keeps track of the ball positions for drawing the waves
yPosSquare = AMPLITUDE # starting position
# main application loop
while True:
# event handling loop for quit events
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
# fill the screen to draw from a blank state
DISPLAYSURF.fill(BGCOLOR)
# sine wave
yPos = -1 * math.sin(step) * AMPLITUDE
posRecord['sin'].append((int(xPos), int(yPos) + WIN_CENTERY))
if showSine:
# draw the sine ball and label
pygame.draw.circle(DISPLAYSURF, RED, (int(xPos), int(yPos) + WIN_CENTERY), 10)
sinLabelRect.center = (int(xPos), int(yPos) + WIN_CENTERY + 20)
DISPLAYSURF.blit(sinLabelSurf, sinLabelRect)
# draw the waves from the previously recorded ball positions
if showSine:
for x, y in posRecord['sin']:
pygame.draw.circle(DISPLAYSURF, DARKRED, (x,y), 4)
#drawing horizontal lines
# square
posRecord['square'].append((int(xPos), int(yPosSquare) + WIN_CENTERY))
if showSquare:
# draw the sine ball and label
pygame.draw.circle(DISPLAYSURF, GREEN, (int(xPos), int(yPosSquare) + WIN_CENTERY), 10)
squareLabelRect.center = (int(xPos), int(yPosSquare) + WIN_CENTERY + 20)
DISPLAYSURF.blit(squareLabelSurf, squareLabelRect)
# draw the waves from the previously recorded ball positions
if showSquare:
for x, y in posRecord['square']:
pygame.draw.circle(DISPLAYSURF, BLUE, (x, y), 4)
# draw the border
pygame.draw.rect(DISPLAYSURF, BLACK, (0, 0, WINDOWWIDTH, WINDOWHEIGHT), 1)
pygame.display.update()
FPSCLOCK.tick(FPS)
if not pause:
xPos += 1
#wave movement
if xPos > WINDOWWIDTH:
#sine
xPos = 0
posRecord['sin'] = []
step = 0
# square
yPosSquare = AMPLITUDE
posRecord['square'] = []
else:
#sine
step += 0.008
#step %= 2 * math.pi
# square
# jump top and bottom every 100 pixels
if xPos % 100 == 0:
yPosSquare *= -1
# add vertical line
for x in range(-AMPLITUDE, AMPLITUDE):
posRecord['square'].append((int(xPos), int(x) + WIN_CENTERY))
Use SPACE to change background color.
First line use only transparency - and has no problem with different background color.
Second line changes only circles color - and depends on background color.
Third and fourth line (it is the same line with different starting color) change circles color and transparency - and depends on background color.
Second and last line look good on one color background and need more work to find good-looking fading.
import pygame
pygame.init()
screen = pygame.display.set_mode((600,200))
#--------------------------------------
# circles positions and transparency (x,y, alpha)
circles = []
for x in range(100):
circles.append( [100+x*3, 200, x*2] )
#--------------------------------------
white = True # background color
#--------------------------------------
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
elif event.key == pygame.K_SPACE:
white = not white
#--------------------------------------
if white:
screen.fill((255,255,255))
else:
screen.fill((0,0,0))
#--------------------------------------
# first
circle_img = pygame.Surface((20,20))
pygame.draw.circle(circle_img, (255,0,0), (10,10), 10)
circle_img.set_colorkey(0)
for x in circles:
circle_img.set_alpha(x[2])
screen.blit(circle_img, (x[0],40))
#--------------------------------------
# second
circle_img = pygame.Surface((20,20))
for x in circles:
pygame.draw.circle(circle_img, (255,255-x[2],255-x[2]), (10,10), 10)
circle_img.set_colorkey(0)
screen.blit(circle_img, (x[0],90))
#--------------------------------------
# last
circle_img = pygame.Surface((20,20))
for x in circles:
pygame.draw.circle(circle_img, (255,255-x[2],255-x[2]), (10,10), 10)
circle_img.set_colorkey(0)
circle_img.set_alpha(x[2])
screen.blit(circle_img, (x[0],140))
#--------------------------------------
pygame.display.flip()
pygame.quit()

Categories

Resources