Random Brick Color -> TypeError: 'pygame.Color' object is not callable - python

so this is my first time as a registered user here, so please bear with me if I was searching wrong,
but with the tags [python] or [pygame] I could not find an answer to this question of a random color.
So my problem is the following:
The Game
In this game I want the bricks to be random colors. To do so I made a function to generate a random color:
def brick_color():
color_var = random.randint(0,3)
if color_var == 0: #red
brick_color1 = pygame.Color(198,44,58)
elif color_var == 1:#blue
brick_color1 = pygame.Color(1,128,181)
elif color_var == 2:#yellow
brick_color1 = pygame.Color(255,211,92)
elif color_var == 3:#green
brick_color1 = pygame.Color(0,157,103)
return brick_color1
and implemented the function into this lines:
# brick init
brick = pygame.Surface([brick_width, brick_height]),brick_color # surface for a single brick
pygame.draw.rect(brick[0], brick[1], [0, 0, brick_width, brick_height])
bricks = [] # list of *coordinates* of the bricks
# initialize coordinates of bricks
for y in range(num_brick_rows):
brickY = (y * brick_row_height) + brick_offset_y
for x in range(num_bricks_in_row):
brickX = (x * brick_column_width) + brick_offset_x
color_of_brick = brick_color()
bricks.append((brickX, brickY),color_of_brick) # coordinates are in fact tuples (x,y)
But i keep getting this error:
File "C:\_____\unbenannt0.py", line 146, in <module>
color_of_brick = brick_color()
TypeError: 'pygame.Color' object is not callable
And this is the full code.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 2 09:33:50 2020
#author:
"""
# example from the Sloan Kelly book
# very slightly modified
# imports (or makes usable) external packages that may be 3rd party (such as pygame)
import pygame, sys, random
# enable "short-hand" notation for imported stuff
from pygame.locals import QUIT, MOUSEBUTTONUP, MOUSEMOTION, KEYDOWN, K_ESCAPE
from pygame import display
#Functions
def draw_bricks():
for b in bricks:
windowSurfaceObj.blit(brick[0], b) # makes a copy of brick image acording to coordinates, where stuff is drawn!
def draw_bat():
windowSurfaceObj.blit(bat, batRect)
def draw_ball():
windowSurfaceObj.blit(ball, ballRect)
def brick_color():
color_var = random.randint(0,3)
if color_var == 0: #red
brick_color = pygame.Color(198,44,58)
elif color_var == 1:#blue
brick_color = pygame.Color(1,128,181)
elif color_var == 2:#yellow
brick_color = pygame.Color(255,211,92)
elif color_var == 3:#green
brick_color = pygame.Color(0,157,103)
return brick_color
pygame.init()
fpsClock = pygame.time.Clock()
# new and improved:
# create surface object aka. the main window
inf = display.Info()
screen_width = inf.current_w - 200 # make window sizea little bit smaller than actual screen
screen_height = inf.current_h - 200
# windowSurfaceObj = display.set_mode(size=(screen_width, screen_height), flags=pygame.FULLSCREEN) # initialize window
windowSurfaceObj = display.set_mode(size=(screen_width, screen_height)) # initialize window
display.set_caption('New and improved Bricks'); # set window title
# brick layout
brick_width = 50
brick_height = 20
num_bricks_in_row = 7
num_brick_rows = 5
brick_row_height = 2 * brick_height
brick_offset_y = 100
brick_column_width = 2 * brick_width
brick_offset_x = int(screen_width/2 - brick_column_width*num_bricks_in_row/2) # place it in the middle of the screen
brick_color = brick_color()
# ball related stuff
ball_radius = int(screen_height/200)
# more game constants!
fps = 60 # desired frames per second
background_colour = pygame.Color(0, 0, 0) # background is black
# used variables for bat dimensions
bat_width = 100
bat_height = 10
# ball related stuff
ball_start_x = 24 # somehwere near the left of the window
ball_start_y = 200 # initial ball position when new ball is released
ball_speed = int(fps*0.15) # speed of ball in pixel per frame! use fps var. here to make real ball speed independent of frame rate
# bat init
# replace bat with crude hand drawn one
batcolor = pygame.Color(0, 0, 255) # bat color: blue!
bat = pygame.Surface([bat_width, bat_height]) # this Surface is for drawing the bat upon
pygame.draw.rect(bat, batcolor, [0, 0, bat_width, bat_height]) # draw bat. It's a simple rectangle.
bat = bat.convert_alpha() # deal with transparency
# place the bat somewhere near the bottom of the screen/window
player_start_x = 0 # initial position is on left
player_start_y = screen_height - 6 * bat_height # this is used as Y coordinate for bat, near the bottom of the screen
batRect = bat.get_rect() # rectangle around bat, used to move it around later
mousex = player_start_x
mousey = player_start_y # mousex and mousey later used for moving the bat around, not actual mouse coordinates at this point
# ball init
ball_color = pygame.Color(255, 255, 255) # white
ball = pygame.Surface([ball_radius*2, ball_radius*2]) # Surface for drawing the ball upon
pygame.draw.circle(ball, ball_color, (ball_radius, ball_radius), ball_radius) # draw circle on ball surface
ballRect = ball.get_rect() # rectangle around ball, use to move it around later
ballServed = False
bx = ball_start_x # bx is actual ball postion
by = ball_start_y # by is actual (current) ball position
sx = ball_speed # current ball speed in horizontal direction
sy = ball_speed # current ball speed vertical
ballRect.topleft = (bx, by) # move ball rectangle to initial position
# brick init
brick = pygame.Surface([brick_width, brick_height]),brick_color # surface for a single brick
pygame.draw.rect(brick[0], brick[1], [0, 0, brick_width, brick_height])
bricks = [] # list of *coordinates* of the bricks
# initialize coordinates of bricks
for y in range(num_brick_rows):
brickY = (y * brick_row_height) + brick_offset_y
for x in range(num_bricks_in_row):
brickX = (x * brick_column_width) + brick_offset_x
color_of_brick = brick_color()
bricks.append((brickX, brickY),color_of_brick) # coordinates are in fact tuples (x,y)
while True: # main loop, run once per frame (i.e. fps times per second)
windowSurfaceObj.fill(background_colour) # clear the screen
# brick draw
# for b in bricks: # remember: bricks is a list of brick coordinates, not surfaces
# windowSurfaceObj.blit(brick, b) # make copy of brick image and place it on screen, b = brick coordinates
draw_bricks()
# bat and ball draw, rectangles around bat and ball are used for positioning
# windowSurfaceObj.blit(bat, batRect) # copy surface with image of bat to screen
# windowSurfaceObj.blit(ball, ballRect) # same for ball
draw_bat()
draw_ball()
# main event loop
# process user interaction
for event in pygame.event.get():
# quit the game if window is closed or escape key is pressed
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONUP and not ballServed:
ballServed = True # start game, when mouse is clicked
elif event.type == MOUSEMOTION: # mouse has moved
mousex, mousey = event.pos # set mouse coordinate variables to actual mouse coordinates
if mousex < screen_width - bat_width:
if mousex < 0: # may occur in full screen / large window mode
batRect.topleft = (0, player_start_y)
else:
batRect.topleft = (mousex, player_start_y)
else:
batRect.topleft = (screen_width - bat_width, player_start_y)
# main game logic
if ballServed: # if game is in progress
ballRect.topleft = (bx, by) # position the ball using its rectangle
bx += sx # sx = speed of the ball in X direction
by += sy # sy = speed of the ball in Y direction
if (by >= screen_height): # ball below bottom of screen
ballServed = False # game not in progess, ball lost!
bx, by = (ball_start_x, ball_start_y) # ball is reset to start position
ballRect.topleft = (bx, by) # move the rectangle around ball to correct position
if by <= 0: # ball hits top
by = 0
sy *= -1 # reflect
if bx <= 0: # ball hits left side of window
bx = 0
sx *= -1 # reflect
if bx >= screen_width - ball_radius*2: # ball hits right side of window
bx = screen_width - ball_radius*2
sx *= -1 # reflection
# collision detection
brickForRemoval = None
for b in bricks: # remember: bricks is list of coordinates of bricks; iterating all bricks and check each one for collision
briX, briY = b # tuple unwrapping: x and y coordinates of top left of brick
if bx + ball_radius*2 >= briX and bx <= briX + brick_width: # is x coordinate of ball inside brick (or touching brick)
if (by + ball_radius*2 >= briY and by <= briY + brick_height): # same for y coordinate
brickForRemoval = b # brick was hit and is scheduled for removal
if bx <= briX + ball_radius*2: # ball hit brick from left
sx *= -1 # reflect
elif bx >= briX + brick_width - ball_radius*2: # ball hit brick from right
sx *= -1 # reflect
if by <= briY + ball_radius * 2: # ball hit brick from top
sy *= -1 # reflect
elif by >= briY + brick_height - ball_radius*2: # ball hit brick from below
sy *= -1 # reflect
break # ball hit a brick and cannot hit another one at the same time
if brickForRemoval != None: # if a brick is scheduled for removal…
bricks.remove(brickForRemoval) # … remove it!
# collision check: does bat hit ball?
if (bx >= mousex and bx <= mousex + bat_width): # using bat_width variable
if(by >= player_start_y - bat_height and by <= player_start_y):
sy *= -1 # reflect
pygame.display.update() # show updated screen
fpsClock.tick(fps) # limit fps
Any help is highly appreciated!

As per #jasonharper's comment, when you assign a value to a variable name that is the same as the function name, that name becomes "re-assigned", in this case - making the function no longer accessible.
Using any other variable name inside your function would fix it:
def brick_color():
color_var = random.randint(0,3)
if color_var == 0: #red
new_color = pygame.Color(198,44,58)
elif color_var == 1:#blue
new_color = pygame.Color(1,128,181)
elif color_var == 2:#yellow
new_color = pygame.Color(255,211,92)
elif color_var == 3:#green
new_color = pygame.Color(0,157,103)
return new_color
Your function could also use a python list to be a bit more flexible and compact:
def getRandomColor():
# red blue yellow green
color_list = [ (198,44,58), (1,128,181), (255,211,92), (0,157,103) ]
random_choice = random.randrange( len( color_list ) )
return color_list[ random_choice ]
This form is more flexible because you can easily add more colours by appending them to the list (no more to do).

Related

Pygame not letting me change display after .update()

I've put pygame.display.update() multiple different places but for some reason it absolutely doesnt let me do the H keypress so it draws help, everything else works.
This is for a school assignment that ive made much harder than it was. I'm technically done i just wanted to make a main menu, everything went smooth then the help screen never wanted to draw
import pygame
import time
import random
import sys
import os
# ! Use print(event) for coordinate reading
# TODO: Add highscore file read and overwrite ✔️
# TODO: Add Game over message ✔️
# TODO: Show highscore and points of that run ✔️
# TODO: Fix Snake not being on same x,y as apple (Most likely wrong movement increments) ✔️
# TODO: Add GRID ✔️
# ? Find a better spawning logic ✔️
# ? Add menu instead of a simple string - NOE AV DET JÆVLIGSTE JEG HAR STARTET PÅ
# ? Fine tune resolution and size
# ? Add a unique powerup with 3% spawn chance giving 5 points and 1 body length
# ! Pygame Initiatior
pygame.init() # * Initiates pygame
# ! Screen resolution and title
sc_width = 400
sc_height = 400
screen = pygame.display.set_mode((sc_width, sc_height)) # * Sets pygame window
pygame.display.set_caption('Snake') # * Sets window title to Snake
# ! Color Variables
bgcolor = (25, 51, 102) # * Dark blue for background color
yellow = (255, 255, 0) # * Yellow color for snake
red = (255, 0, 0) # * Red color for points & game over
white = (255, 255, 255) # * White color for score
# ! FPS variable
clock = pygame.time.Clock() # * Used to set the FPS of the game using clock.tick(xyz)
# ! Font
font = pygame.font.SysFont(None, 30) # * None = Default pygame font. 40 = size of font
# ! Game Over Draw function
def GameOver(msg, color): # * Function takes in a string and color and draws it on screen
text = font.render(msg, True, color) # * Draws msg with font with True for anti aliasing (Smooth edges) with specified color when func is called
screen.blit(text, [50, 100]) # * Draws text at 100x100
# ! Snake
snake_block = 10
def Snake(snake_block, snakelist):
for x in snakelist:
pygame.draw.rect(screen, yellow, [x[0], x[1], snake_block, snake_block])
# ! Grid
black = (0, 0, 0)
def Grid():
size = 10 # * Sets grid size to 10 (same as snake)
for x2 in range(0, sc_width, size): # * Gaps 10 in width
for y2 in range(0, sc_height, size): # * Gaps height with 10
drawGrid = pygame.Rect(x2, y2, size, size) # * Makes a grid
pygame.draw.rect(screen, black, drawGrid, 1) # * Draws it onto the screen
# ! Draw Score
def drawScore(score):
points = font.render('Score: ' + str(score), True, white)
screen.blit(points, [0, 0]) # * Draws it top left
# ! Make highscore txt
try:
f = open("highscore.txt", 'x') # * Creates file if it doesnt exist
f.write('0') # * No highscore set
f.close() # * Closes file to let other codes down the line rewrite the file
except FileExistsError: # * If exist continue to rest of code using it as the "highscore" file
pass
# ! Draw Highscore
f = open('highscore.txt', 'r') # * Opens as read
highscore = int(f.readline())
f.close()
def drawHighscore(highscore):
hc = font.render('Score: ' + str(highscore), True, white)
screen.blit(hc, [310, 0]) # * Draws it top right
# # ! Draw PRE GAME Screen
# def drawMenu(menu, color):
# pregame = font.render(menu, True, white)
# screen.blit(pregame, [50, 100])
# ! Multiline draw function (Stackoverflow) / PRE GAME
def drawMenu(menu, x, y, fsize):
lines = menu.splitlines()
for i, l in enumerate(lines):
screen.blit(font.render(l, 0, white), (x, y + fsize*i))
# ! Draw Help screen
def drawHelp(x, y, fsize):
help = "Controls: [W][A][S][D]\nInstructions: \nUse WASD to control the snake.\nGrab as many apples as you can;\nand dont crash into yourself :)\n\n [ (B) A C K ]"
hlp = help.splitlines()
for i, l in enumerate(hlp):
screen.blit(font.render(l, 0, white), (x, y + fsize*i))
def mainMenu():
menu = "[ (S) T A R T ]\n [ (H) E L P ]\n [ (Q) U I T ]\n jeg er best"
screen.fill(bgcolor)
drawMenu(menu, 140, 120, 80)
for event in pygame.event.get(): # * Gathers inputs
if event.type == pygame.KEYDOWN: # * Checks key presses
if event.key == pygame.K_q: # * If Q is pressed
pygame.quit()
sys.exit()
elif event.key == pygame.K_s: # * Calls game loop again
game()
elif event.key == pygame.K_h:
screen.fill(bgcolor)
drawHelp(25, 70, 40)
# ! Game Loop
def game():
finished = False
done = False
# ! Spawn location of snake
x = sc_width / 2 # * Spawns snake at screen width / 2
x_move = 0 # * To update x coordinates as the snake moves
y = sc_height / 2 # * Spawns snake at screen height / 2
y_move = 0 # * To update y coordinates as the snake moves
score = 0
f = open('highscore.txt', 'r') # * Opens as read
highscore = int(f.readline())
f.close()
snakelist = []
snake_len = 1
# ! Randomizing apple spawn locations
apple_x = round(random.randrange(0, sc_width - 10) / 10.0) * 10.0
apple_y = round(random.randrange(0, sc_height - 10) / 10.0) * 10.0
while not finished:
while done == True:
screen.fill(bgcolor)
drawScore(snake_len - 1)
drawHighscore(highscore)
mainMenu()
# ! Movement input logic
for event in pygame.event.get(): # * Gathers inputs
if event.type == pygame.QUIT: # * If pygame.quit gets called (clicking X on window) it will set finished to True which will end game loop
finished = True # * Ends game loop
sys.exit()
if event.type == pygame.KEYDOWN: # * Checks if a key is pressed down
if event.key == pygame.K_d: # * If key 'D' is pressed increase x by 10 making it move right
x_move = 10 # * Speed it moves
y_move = 0 # * No vertical movement
elif event.key == pygame.K_a: # * If key 'A' is pressed decrease x by -10 making it move left
x_move = -10 # * Speed it moves
y_move = 0 # * No vertical movement
elif event.key == pygame.K_w: # * If key 'W' is pressed decrease y by -10 making it move up
x_move = 0 # * No horizontal movement
y_move = -10 # * Speed it moves
elif event.key == pygame.K_s: # * If key 'S' is pressed increase y by 10 making it move down
x_move = 0 # * No horizontal movement
y_move = 10 # * Speed it moves
# ! Out of bounds logic
# * If snake is at a value higher than screen res or lower than 0; it means its outside the screen box, then the Game loop var will be True and game ends
if x >= sc_width or x < 0 or y >= sc_height or y < 0:
done = True
# ! Update movement
x += x_move
y += y_move
screen.fill(bgcolor)
# ! Draw grid
Grid() # * Draws grid
# ! Draw snake and apples
pygame.draw.rect(screen, red, [apple_x, apple_y, 10, 10]) # * Draws apples on screen with red color and puts it at apple_x,y with size of 10
pygame.draw.rect(screen, yellow, [x, y, 10, 10]) # * Draws snake on screen with yellow color and puts it at var x,y with a size of 10
snakeH = []
snakeH.append(x) # * Appends snake head x position
snakeH.append(y) # * Appends snake head y position
snakelist.append(snakeH) # * Adds snake head to THE snake list
if len(snakelist) > snake_len: # * If snake list is bigger than snake length
del snakelist[0] # * Kills head
for x1 in snakelist[:-1]:
# ? Tried to understand this by using prints and seeing values:
# ? I'm guessing since it checks each block (prints show list with values with 10 seperating (size of block))
# ? DOES NOT PRINT HEAD
# ? If head hits one of the other boxes, it will overlap in list and head wont be skipped and it dies
# ! print(snakelist[:-1]) (Bugtesting / code understanding)
if x1 == snakeH:
# ! print(snakelist[:-1]) (Bugtesting / code understanding)
done = True
Snake(snake_block, snakelist) # * Updates func with new values
drawScore(snake_len - 1) # * - 1 because dont want to count head as a point
drawHighscore(highscore)
# ! Snake eating apple and growing
if x == apple_x and y == apple_y: # * Checks if snake is at apple pos
apple_x = round(random.randrange(0, sc_width - 10) / 10.0) * 10.0 # * Spawns new apple inside play area
apple_y = round(random.randrange(0, sc_height - 10) / 10.0) * 10.0 # * Spawns new apple inside play area
snake_len += 1 # * Increases snake length by 1
score += 1 # * Increases score by 1
# ! Saving highscore
f = open("highscore.txt", 'r+') # * Opens Highscore
highscore = int(f.readline()) # * Reads Highscore
if highscore > score: # * If Highscore > score(that run)
f.close() # * Close file
else: # * But if score > highscore
f.close # * Close it so it doesnt add to existing number ex: highscore: 5 score that run 6 = highscore: 56
f = open("highscore.txt", 'w') # * Open as write so it writes a new number
f.write(f'{score}') # * Write current score
f.close() # * Close
f = open('highscore.txt', 'r') # * Opens as read
highscore = int(f.readline())
f.close() # * Close file
# ! Setting FPS
clock.tick(30) # * Sets FPS to 30
pygame.display.update()
pygame.quit() # * Uninitializes pygame
quit() # * Quits
while True:
mainMenu()
I have modified your drawHelp function as follows:
def drawHelp(x, y, fsize):
help = "Controls: [W][A][S][D]\nInstructions: \nUse WASD to control the snake.\nGrab as many apples as you can;\nand dont crash into yourself :)\n\n [ (B) A C K ]"
hlp = help.splitlines()
for i, l in enumerate(hlp):
screen.blit(font.render(l, 0, white), (x, y + fsize*i))
pygame.display.update()
# to stay in this function until the B key is pressed.
b_pressed = False
while not b_pressed:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_b:
b_pressed = True
Note I also had to add pygame.display.update() to the end of drawMenu() to make the main menu appear.
That said, there are several problems that make it harder for you to extend an debug your code. Typically pygame.display.update() should only be called once, also events should ideally be handled in one place. Event handlers would ideally modify the game state, e.g. change state from Main Menu to Help. Your event handlers call functions that take over event handling and drawing and updates. In order to achieve your outcome without refactoring your code, I've followed a similar practice.
It would probably help you to read up on state machines, here's an answer that may help you, or a pygame example whose use I imagine isn't strictly permitted for your homework. You've already started down this path with your done and finished variables.

Bouncing Ball doesn't come back pygame

import pygame
pygame.init()
width = 400
hight = 600
screen = pygame.display.set_mode((width, hight))
pygame.display.set_caption("Engine")
dot = pygame.image.load("KreisSchwarz.png")
clock = pygame.time.Clock()
running = True
WHITE = (255, 255, 255)
# Set (x, y) for Dot
def updateDot(x, y):
screen.blit(dot, (x, y))
# Display Dot at (x, y)
def update(fps=30):
screen.fill(WHITE)
updateDot(x, y)
pygame.display.flip()
return clock.tick(fps)
# Quit if User closes the window
def evHandler():
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
running = False
yKoords = []
(x, y) = (300, 200)
t = 1 # time variable
a = 2 # acceleration constant
tol = 40 # tolerance
i = 0 # just some iterator
# MAIN LOOP
while running:
evHandler()
update()
y += a * (t ^ 2)
t += 1
yKoords.append(int(y))
i += 1
if (y < (hight + tol)) and (y > (hight - tol)):
y = 580
yKoords.reverse()
update()
for q in range(i):
evHandler()
y = yKoords[q]
update()
if q == i - 1: # Because i didn't write the Part for the Dot coming back down
running = False
This is my Code for a Ball accelerating down and then jumping back up.
My Problem is, that the code works fine until the if statement. There the Programm just displays the Ball at the last position in yKoords and waits until the for loop finishes. If i remove the for loop the Ball gets displayed at y=580 and stops but thats fine.
Please help i have no idea whats wrong about this.
Don't do a separate process loop in the main loop.
It is sufficient to invert the direction, when the ball bounce on the ground (abs(y - hight)) or the ball reaches the top (t == 0).
direction = 1
while running:
evHandler()
update()
y += (a * (t ^ 2)) * direction
t += direction
if abs(y - hight) < tol:
y = 580
t -= 1
direction *= -1
elif t == 0:
direction *= -1

Pygame: colliding rectangles with other rectangles in the same list

I have a list of 10 drawn rectangles (referenced as cubes in my script) that are affected by gravity. I made a simple collision system for them to stop when they hit the ground. How can I make it so when 2 cubes collide they stop falling like they do with the ground?
import pygame
import time
import random
pygame.init()
clock = pygame.time.Clock()
wnx = 800
wny = 600
black = (0,0,0)
grey = (75,75,75)
white = (255,255,255)
orange = (255,100,30)
wn = pygame.display.set_mode((wnx, wny))
wn.fill(white)
def cube(cx,cy,cw,ch):
pygame.draw.rect(wn, orange, [cx, cy, cw, ch])
def floor(fx,fy,fw,fh):
pygame.draw.rect(wn, grey, [fx, fy, fw, fh])
def main():
floory = 550
number = 30
cubex = [0] * number
cubey = [0] * number
cubew = 10
cubeh = 10
for i in range(len(cubex)):
cubex[i] = (random.randrange(0, 80)*10)
cubey[i] = (random.randrange(2, 5)*10)
gravity = -10
exit = False
while not exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit = True
for i in range(len(cubex)): #i want to check here if it collides with an other cube
if not (cubey[i] + 10) >= floory:
cubey[i] -= gravity
wn.fill(white)
floor(0,floory,800,50)
for i in range(len(cubex)):
cube(cubex[i], cubey[i], cubew, cubeh)
pygame.display.update()
clock.tick(5)
main()
pygame.quit()
quit()
Use pygame.Rect.colliderect to check if to rectangles are intersecting.
Create an rectangle (pygame.Rect) which defines the next position (area) of the cube:
cubeR = pygame.Rect(cubex[i], cubey[i] + 10, cubew, cubeh)
Find all intersecting rectangles
cl = [j for j in range(len(cubey)) if j != i and cubeR.colliderect(pygame.Rect(cubex[j], cubey[j], cubew, cubeh))]
And don't move (let further "fall") the cube if there is any() collision:
if not any(cl):
# [...]
The check may look like this:
for i in range(len(cubex)):
cubeR = pygame.Rect(cubex[i], cubey[i] + 10, cubew, cubeh)
cisect = [j for j in range(len(cubey)) if j != i and cubeR.colliderect(pygame.Rect(cubex[j], cubey[j], cubew, cubeh))]
if not any(cisect) and not (cubey[i] + 10) >= floory:
cubey[i] -= gravity
Note, since all the cubes are aligned to an 10*10 raster, it is sufficient to check if the origins of the cubes are equal:
for i in range(len(cubex)):
cisect = [j for j in range(len(cubey)) if j != i and cubex[i] == cubex[j] and cubey[i]+10 == cubey[j]]
if not any(cisect) and not (cubey[i] + 10) >= floory:
cubey[i] -= gravity

Out of memory when using pygame.transform.rotate

I wrote a script that allows a user to control the sprite of an eagle to fly around to learn pygame. It seemed fine until i implemented a rotation function that makes the sprite rotate according to the direction it is flying along. The sprite becomes really fuzzy after moving a short while and an error soon pops up saying out of memory (at this line: eagle_img = pygame.transform.rotate(eagle_img,new_angle-angle))
My code:
# eagle movement script
import pygame, math, sys
from pygame.locals import *
pygame.init()
clock = pygame.time.Clock()
# terminate function
def terminate():
pygame.quit()
sys.exit()
# incircle function, check if mouse click is inside controller
def incircle(coordinates,cir_center,cir_out_rad):
if math.sqrt((coordinates[0]-cir_center[0])**2+\
(coordinates[1]-cir_center[1])**2) <= cir_out_rad:
return True
return False
# speed function, translates the controller movement into eagle movement
def speed(position,cir_center,eagle_speed):
x_dist = position[0] - cir_center[0]
y_dist = position[1] - cir_center[1]
dist = math.sqrt(x_dist**2+y_dist**2) # distance from controller knob to center
if dist != 0:
return [(x_dist/dist)*eagle_speed,(y_dist/dist)*eagle_speed]
else:
return [0,0]
# rotation function, rotates the eagle image
def rotation(position,cir_center):
x_dist = position[0] - cir_center[0]
y_dist = position[1] - cir_center[1]
new_radian = math.atan2(-y_dist,x_dist)
new_radian %= 2*math.pi
new_angle = math.degrees(new_radian)
return new_angle
# screen
screenw = 1000
screenh = 700
screen = pygame.display.set_mode((screenw,screenh),0,32)
pygame.display.set_caption('eagle movement')
# variables
green = (0,200,0)
grey = (100,100,100)
red = (255,0,0)
fps = 60
# controller
cir_out_rad = 150 # circle controller outer radius
cir_in_rad = 30 # circle controller inner radius
cir_center = [screenw-cir_out_rad,int(screenh/2)]
position = cir_center # mouse position
# eagle
eaglew = 100
eagleh = 60
eagle_speed = 3
eagle_pos = [screenw/2-eaglew/2,screenh/2-eagleh/2]
eagle = pygame.Rect(eagle_pos[0],eagle_pos[1],eaglew,eagleh)
eagle_img = pygame.image.load('eagle1.png').convert()
eagle_bg_colour = eagle_img.get_at((0,0))
eagle_img.set_colorkey(eagle_bg_colour)
eagle_img = pygame.transform.scale(eagle_img,(eaglew,eagleh))
# eagle controls
stop_moving = False # becomes True when player stops clicking
rotate = False # becomes True when there is input
angle = 90 # eagle is 90 degrees in the beginning
# game loop
while True:
# controls
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == MOUSEBUTTONUP:
stop_moving = True
rotate = False
mouse_input = pygame.mouse.get_pressed()
if mouse_input[0]:
coordinates = pygame.mouse.get_pos() # check if coordinates is inside controller
if incircle(coordinates,cir_center,cir_out_rad):
position = pygame.mouse.get_pos()
stop_moving = False
rotate = True
else:
cir_center = pygame.mouse.get_pos()
stop_moving = False
rotate = True
key_input = pygame.key.get_pressed()
if key_input[K_ESCAPE] or key_input[ord('q')]:
terminate()
screen.fill(green)
[dx,dy] = speed(position,cir_center,eagle_speed)
if stop_moving:
[dx,dy] = [0,0]
if eagle.left > 0:
eagle.left += dx
if eagle.right < screenw:
eagle.right += dx
if eagle.top > 0:
eagle.top += dy
if eagle.bottom < screenh:
eagle.bottom += dy
if rotate:
new_angle = rotation(position,cir_center)
if new_angle != angle:
eagle_img = pygame.transform.rotate(eagle_img,new_angle-angle)
eagle = eagle_img.get_rect(center=eagle.center)
rotate = False
angle = new_angle
outer_circle = pygame.draw.circle(screen,grey,(cir_center[0],cir_center[1]),\
cir_out_rad,3)
inner_circle = pygame.draw.circle(screen,grey,(position[0],position[1]),\
cir_in_rad,1)
screen.blit(eagle_img,eagle)
pygame.display.update()
clock.tick(fps)
Please tell me what's wrong here and how i can improve it. Feel free to try the code out using a sprite named "eagle1.png". Thanks!
the reason your eagle picture is becoming blurred is because your continually rotating the same png and not making a copy and rotating that copy while always keeping a non edited picture. here is a function i have always used when rotating square images
def rot_center(image, angle):
"""rotate an image while keeping its center and size"""
orig_rect = image.get_rect()
rot_image = pygame.transform.rotate(image, angle)
rot_rect = orig_rect.copy()
rot_rect.center = rot_image.get_rect().center
rot_image = rot_image.subsurface(rot_rect).copy()
return rot_image
here is one for any shape of picture
def rot_center(image, rect, angle):
"""rotate an image while keeping its center"""
rot_image = pygame.transform.rotate(image, angle)
rot_rect = rot_image.get_rect(center=rect.center)
return rot_image,rot_rect
source from here
as for the "out of memory" error i don't know for sure but i assume the leak is being caused by the rotation of the same png file over and over again. From some research that seems to occur often with other people.
hope this helps clear some things up:)

Python- Bouncing Balls? How to pass separately as one parameter? [duplicate]

This question already has answers here:
Pygame how to let balls collide
(2 answers)
pygame Get the balls to bounce off each other
(1 answer)
Closed last month.
How do I pass ball_boundary_2 and ball_boundary_3 separately as one parameter
to ball_collisions function?
Here is the code below:
## Import PyGame system
import sys, pygame
## Initialise PyGame system
pygame.init()
## Function to handle ball colissions
### NOTE: Should alos include sound but we could not get it to work properly. ##
def ball_collisions(ball_boundary, velocity, sound):
## If ball_boundary collides with the rectangle of ball_boundary_2 than ...
if ball_boundary.colliderect(ball_boundary_2):
## Change the direction of the balls
velocity[0] = -1 * velocity[0]
velocity[1] = -1 * velocity[1]
velocity_2[0] = -1 * velocity_2[0]
velocity_2[1] = -1 * velocity_2[1]
## Or if there is a colission between any of the other balls do the same
elif ball_boundary.colliderect(ball_boundary_3):
velocity[0] = -1 * velocity[0]
velocity[1] = -1 * velocity[1]
velocity_3[0] = -1 * velocity_3[0]
velocity_3[1] = -1 * velocity_3[1]
elif ball_boundary_2.colliderect(ball_boundary_3):
velocity_2[0] = -1 * velocity[0]
velocity_2[1] = -1 * velocity[1]
velocity_3[0] = -1 * velocity_3[0]
velocity_3[1] = -1 * velocity_3[1]
## Function to handel wall collisions
def wall_collisions(ball_boundary, velocity, sound, width, height):
## If ball_boundary collides with the right or left boundaries than ...
if ball_boundary.left < 0 or ball_boundary.right > width:
## Play sound and ...
sound.play()
## Reverse direction
velocity[0] = -1 * velocity[0]
## Do same for top and bottom
if ball_boundary.top < 0 or ball_boundary.bottom > height:
sound.play()
velocity[1] = -1 * velocity[1]
## Variables to hold important information to be called
ball_image = 'beachball.jpg'
bounce_sound = 'Thump.wav'
width = 800
height = 600
background_colour = 0,0,0
caption = 'Bouncing Ball animation'
velocity = [1,1]
velocity_2 = [1,-1]
velocity_3 = [-1,1]
## Create window frame and add caption to it
frame = pygame.display.set_mode((width,height))
pygame.display.set_caption(caption)
## Load image of ball and convert for PyGame to use
ball = pygame.image.load(ball_image).convert()
## Set rectangular boundaries for the ball images and set initial locations
ball_boundary = ball.get_rect(center=(300,300))
ball_boundary_2 = ball.get_rect(center=(100,200))
ball_boundary_3 = ball.get_rect(center=(400,100))
## Readies sound to be played for collisions
sound = pygame.mixer.Sound(bounce_sound)
## Event Loop:
while True:
for event in pygame.event.get():
## If statment for quiting of program
if event.type == pygame.QUIT: sys.exit(0)
## Call wall_collisions function for each ball
wall_collisions(ball_boundary, velocity, sound, width, height)
wall_collisions(ball_boundary_2, velocity_2, sound, width, height)
wall_collisions(ball_boundary_3, velocity_3, sound, width, height)
## Call ball_collisions function for each ball
ball_collisions(ball_boundary, velocity, sound)
ball_collisions(ball_boundary_2, velocity_2, sound)
ball_collisions(ball_boundary_3, velocity_3, sound)
## Calculate the next position of each ball after collision.
ball_boundary = ball_boundary.move(velocity)
ball_boundary_2 = ball_boundary_2.move(velocity_2)
ball_boundary_3 = ball_boundary_3.move(velocity_3)
## Fill the window background behind balls
frame.fill(background_colour)
## Draw copy (blit) images
frame.blit(ball, ball_boundary)
frame.blit(ball, ball_boundary_2)
frame.blit(ball, ball_boundary_3)
## Update display with completed image
pygame.display.flip()
if __name__ =='__main__':
bounce()
I'd consider passing a list of ball boundaries rather than individual ball boundaries. (Is that your question?)
If this doesn't answer your question, then shorten the answer, it's far too long and wordy. (My eyes glazeth over!)
You could just wrap the x-boundary and the y-boundary in a tuple, and pass that to the function ball-collisions.
ball-collisions((x, y), velocity, sound)

Categories