I am restarting some code for a covid simulation as I cant use the collide function in my current one. I have been able to draw the basic background, and draw one cell. However, when i try create the cell in a different place on my screen it does not appear for some reason.
My code is as seen below:
import random
import pygame
# import numpy
import time
pygame.init()
GREEN1 = (0, 255, 0) # Healthy cells
RED = (255, 0, 0) # Infected cells
GREEN2 = (0, 100, 0) # Healthy cells not susecptible
BLACK = (0, 0, 0) # Dead cells
WHITE = (255, 255, 255)
Bgcolor = (225, 198, 153)
ScreenSize = (800, 800)
Screen = pygame.display.set_mode(ScreenSize)
pygame.display.set_caption("Covid-19 Simualtion")
clock = pygame.time.Clock()
speed = [0.5, -0.5]
class Cells(pygame.sprite.Sprite):
def __init__(self, color, speed, width, height):
super().__init__()
self.color = color
self.x_cord = random.randint(0, 400)
self.y_cord = random.randint(50, 700)
self.radius = 5
self.speed = speed
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
pygame.draw.circle(self.image, self.color, [30, 70], self.radius, width = 0)
self.rect = self.image.get_rect()
self.radius = 5
#x_number = random.randint(0, 1)
#self.xSpeed = speed[x_number]
#y_number = random.randint(0, 1)
#self.ySpeed = speed[y_number]
allCellsList = pygame.sprite.Group()
Cell1 = Cells(GREEN1, 5, 50, 50)
allCellsList.add(Cell1)
End = False
while not End:
for event in pygame.event.get():
if event.type == pygame.QUIT:
End = True
Screen.fill(Bgcolor)
pygame.draw.rect(Screen, BLACK, (0, 50, 400, 700), 3)
allCellsList.update()
allCellsList.draw(Screen)
pygame.display.flip()
clock.tick(60)
Thanks for any help in advance
The main problem is that your cell has size (50,50) and you try to draw on position (20,70) so it draws outside rectangle (50, 50) and you can't see it. You have to draw inside rectangle (50, 50) - for example in center (25,25). And later you should use self.rect to move it on screen.
Second problem is that you keep position in self.x_coord, self.x_coord but you should use self.rect.x self.rect.y because Sprite use self.image and self.rect to draw it on screen.
And it show third problem - in Cell you need method update which will change values in self.rect to move object.
Minimal working example which move 5 cells in random directions.
I organize code in different way and try to use PEP 8 - Style Guide for Python Code
import random
import pygame
# --- constants --- (UPPER_CASE_NAMES)
GREEN1 = (0, 255, 0) # Healthy cells
RED = (255, 0, 0) # Infected cells
GREEN2 = (0, 100, 0) # Healthy cells not susecptible
BLACK = (0, 0, 0) # Dead cells
WHITE = (255, 255, 255)
BACKGROUND_COLOR = (225, 198, 153)
SCREEN_SIZE = (800, 800)
# --- classes --- (CamelCaseNames)
# class keeep only one cell so it should has name `Cell` instead of `Cells`
class Cell(pygame.sprite.Sprite):
def __init__(self, color, speed, width, height):
super().__init__()
self.color = color
self.speed = speed
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
self.radius = width//2 # 25
center = [width//2, height//2]
pygame.draw.circle(self.image, self.color, center, self.radius, width=0)
self.rect = self.image.get_rect()
self.rect.x = random.randint(0, 400)
self.rect.y = random.randint(50, 700)
def update(self):
self.rect.x += random.randint(-10, 10)
self.rect.y += random.randint(-10, 10)
# --- functions --- (lower_case_names)
# empty
# --- main --- (lower_case_names)
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption("Covid-19 Simualtion")
speed = [0.5, -0.5]
# - objects -
all_cells = pygame.sprite.Group() # PEP8: lower_case_name
for _ in range(5):
cell = Cell(GREEN1, 5, 50, 50) # PEP8: lower_case_name
all_cells.add(cell)
# - loop -
clock = pygame.time.Clock()
end = False
while not end:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
end = True
# - upadates (without draws) -
all_cells.update()
# - draws (without updates) -
screen.fill(BACKGROUND_COLOR)
pygame.draw.rect(screen, BLACK, (0, 50, 400, 700), 3)
all_cells.draw(screen)
pygame.display.flip()
clock.tick(30) # to use less CPU
# - end
pygame.quit() # some system may need it to close window
Related
This question already has answers here:
How do I detect collision in pygame?
(5 answers)
Closed 1 year ago.
My problem: I am trying to create a vertical ball drop game, and I am testing for collision, which does work. But how would I reset my ball when it hits the hoop? Instead of it detecting and then hitting the bottom of the screen which results in a Game over screen because you lose. Any help is appreciated.
import time, random
from pygame.locals import *
import pygame, sys
pygame.init()
FPS = 60
FramePerSec = pygame.time.Clock()
BLUE = (0, 0, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
SCREEN_BOTTOM = 0
SPEED = 5
SCORE = 0
font = pygame.font.SysFont("Verdana", 60)
font_small = pygame.font.SysFont("Verdana", 20)
game_over = font.render("Game Over", True, BLACK)
background = pygame.image.load("background.jpg")
DISPLAYSURF = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
DISPLAYSURF.fill(WHITE)
pygame.display.set_caption("Ball Drop")
class Ball(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("Ball.png")
self.rect = self.image.get_rect()
self.rect.center = (random.randint(40, SCREEN_WIDTH - 40), 0)
def move(self):
global SCORE
self.rect.move_ip(0, SPEED)
if (self.rect.bottom > 600):
self.rect.top = 0
self.rect.center = (random.randint(30, 380), 0)
# Need to check PNG for hit detection
class Basket(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("Basket.png")
self.rect = self.image.get_rect()
self.rect.center = (160, 520)
def move(self):
pressed_keys = pygame.key.get_pressed()
if(self.rect.x >= (SCREEN_WIDTH - 145)):
self.rect.x -= 5;
elif(self.rect.x <= -5):
self.rect.x += 5;
else:
if pressed_keys[pygame.K_a]:
self.rect.move_ip(-SPEED, 0)
if pressed_keys[pygame.K_d]:
self.rect.move_ip(SPEED, 0)
class Wall(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("wall.png")
self.rect = self.image.get_rect()
self.rect.center = (0, 670)
B2 = Basket()
B1 = Ball()
W1 = Wall()
balls = pygame.sprite.Group()
balls.add(B1)
# Need to fix wall sprite group
walls = pygame.sprite.Group()
walls.add(W1)
all_sprites = pygame.sprite.Group()
all_sprites.add(B2)
all_sprites.add(B1)
INC_SPEED = pygame.USEREVENT + 1
pygame.time.set_timer(INC_SPEED, 1000)
while True:
for event in pygame.event.get():
if event.type == INC_SPEED:
SPEED += 0.3
if event.type == QUIT:
pygame.quit()
sys.exit()
DISPLAYSURF.blit(background, (0, 0))
scores = font_small.render(str(SCORE), True, BLACK)
DISPLAYSURF.blit(scores, (10, 10))
for entity in all_sprites:
DISPLAYSURF.blit(entity.image, entity.rect)
entity.move()
# NEed to fix collison and Counting stats
if pygame.sprite.spritecollideany(W1, balls):
DISPLAYSURF.fill(RED)
DISPLAYSURF.blit(game_over, (30, 250))
pygame.display.update()
for entity in all_sprites:
entity.kill()
time.sleep(2)
pygame.quit()
sys.exit()
if pygame.sprite.spritecollideany(B2, balls):
print("Hit")
SCORE += 1
pygame.display.update()
pygame.display.update()
FramePerSec.tick(FPS)
pygame.sprite.spritecollideany() returns the hit Sprite (ball) object. Change the position of this ball:
while True:
# [...]
ball_hit = pygame.sprite.spritecollideany(B2, balls)
if ball_hit:
ball_hit.rect.center = (random.randint(30, 380), 0)
SCORE += 1
print("Hit")
# [...]
import pygame
import random
black = (0,0,0)
white = (255,255,255)
green = (0,255,0)
red = (255,0,0)
screen = pygame.display.set_mode((1200, 600))
title = pygame.display.set_caption("Speeding cars")
clock = pygame.time.Clock()
clock.tick(60)
class Car:
def __init__(self, x, y, height, width):
self.x = x
self.y = y
self.height = height
self.width = width
def drive(self, change):
self.change = random.randint(1, 3)
self.x += self.change
pygame.draw.rect(screen, black, (self.x, self.y, self.height, self.width))
pygame.display.flip()
car1 = Car(30, 100, 50, 15)
car2 = Car(30, 200, 50, 15)
car3 = Car(30, 300, 50, 15)
car4 = Car(30, 400, 50, 15)
car5 = Car(30, 500, 50, 15)
driving = True
while driving:
screen.fill(white)
car1.drive(0)
car2.drive(0)
car3.drive(0)
car4.drive(0)
car5.drive(0)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pygame.display.flip()
When i try to run this code everything works fine but the rectanges keeps flickering. I tried changing flip to update and adding or removing pygame.display.flip() at different points in code but it dosent seem to work.
Edit: I also just realised that when i comment out the rest of the cars and only run the first one, it runs fine. The problem starts with the second car.
Thanks for help.
Instead of updating the screen in the drive() method, do it at the end of your main loop.
Also, try not to use repetitive code for each new object that is created, but use a for loop instead.
Here you go:
import pygame
import random
black = (0,0,0)
white = (255,255,255)
green = (0,255,0)
red = (255,0,0)
screen = pygame.display.set_mode((1200, 600))
title = pygame.display.set_caption("Speeding cars")
clock = pygame.time.Clock()
clock.tick(60)
class Car:
def __init__(self, x, y, height, width):
self.x = x
self.y = y
self.height = height
self.width = width
def drive(self, change):
self.change = random.randint(1, 1)
self.x += self.change
pygame.draw.rect(screen, black, (self.x, self.y, self.height, self.width))
cars = []
for i in range(1,6):
cars.append(Car(30, 100*i, 50, 15))
driving = True
while driving:
screen.fill(white)
for car in cars:
car.drive(0)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pygame.display.update()
There should be only one flip()/update() which is executed after you draw all shapes and blit all image. It sends buffer screen to video card which display it on monitor.
If you use after every drive then it send screen to monitor with only one car and later it send screen only with second car, etc.
import pygame
import random
black = (0,0,0)
white = (255,255,255)
green = (0,255,0)
red = (255,0,0)
screen = pygame.display.set_mode((1200, 600))
title = pygame.display.set_caption("Speeding cars")
clock = pygame.time.Clock()
clock.tick(60)
class Car:
def __init__(self, x, y, height, width):
self.x = x
self.y = y
self.height = height
self.width = width
def drive(self, change):
self.change = random.randint(1, 3)
self.x += self.change
pygame.draw.rect(screen, black, (self.x, self.y, self.height, self.width))
# pygame.display.flip() # don't use it
car1 = Car(30, 100, 50, 15)
car2 = Car(30, 200, 50, 15)
car3 = Car(30, 300, 50, 15)
car4 = Car(30, 400, 50, 15)
car5 = Car(30, 500, 50, 15)
driving = True
while driving:
screen.fill(white)
car1.drive(0)
car2.drive(0)
car3.drive(0)
car4.drive(0)
car5.drive(0)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pygame.display.flip() # after `for event`, not inside `for event`
I'm at the very beginning of a chess program and want to print the board on the screen. However, I am having trouble at the first hurdle and cannot even get it to print the squares of the board. It just comes up with a black screen and doesn't put the sprite on it.
I've tried looking at some code from a previous project where it worked, but I can't find any differences in this part of the program.
import pygame
import os
import time
pygame.init()
WHITE = (0, 30, 0)
BLACK = (200, 200, 200)
screen_width = 1400
screen_height = 800
square_size = screen_height/10
screen = pygame.display.set_mode([screen_width, screen_height])
os.environ['SDL_VIDEO_WINDOWS_POS'] = '10,10'
class square(pygame.sprite.Sprite):
def __init__(self, colour, x, y):
super().__init__()
self.image = pygame.Surface([square_size, square_size])
pygame.draw.rect(self.image, colour, [0, 0, square_size, square_size])
self.colour = colour
self.rect = self.image.get_rect()
squares = pygame.sprite.Group()
s = square(WHITE, 20, 20)
squares.add(s)
squares.draw(screen)
time.sleep(3)
I would expect this to output one white square in the top left hand corner of the screen, but only a black screen appears.
You need an event.get loop, and to update your display using pygame.display.update() after the squares.draw(screen):
import pygame
import os
import time
pygame.init()
WHITE = (0, 30, 0)
BLACK = (200, 200, 200)
screen_width = 1400
screen_height = 800
square_size = screen_height/10
screen = pygame.display.set_mode([screen_width, screen_height])
os.environ['SDL_VIDEO_WINDOWS_POS'] = '10,10'
class square(pygame.sprite.Sprite):
def __init__(self, colour, x, y):
super().__init__()
self.image = pygame.Surface([square_size, square_size])
pygame.draw.rect(self.image, colour, [0, 0, square_size, square_size])
self.colour = colour
self.rect = self.image.get_rect()
for event in pygame.event.get():
pass
squares = pygame.sprite.Group()
s = square(WHITE, 20, 20)
squares.add(s)
squares.draw(screen)
pygame.display.update()
time.sleep(3)
Also note, an RGB value of (0, 30, 0) is not white, it's a dark green, if you want bright white try (255, 255, 255).
Most likely, your problem is that you didn't flip/update the screen.
I want to have 3 workers (objects of the class Worker) that move on the screen in different random directions and with a different speed. In other words, I just want to run something like this: worker1.makeRandomStep(x,y,1), worker2.makeRandomStep(x,y,2) and worker1.makeRandomStep(x,y,3).
This is my current code in which I have only one worker:
import pygame, random
import sys
WHITE = (255, 255, 255)
GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
SCREENWIDTH=1000
SCREENHEIGHT=578
class Background(pygame.sprite.Sprite):
def __init__(self, image_file, location):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
class Worker(pygame.sprite.Sprite):
def __init__(self, image_file, location):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.direction = 2
self.rect.left, self.rect.top = location
def makeRandomStep(self,x,y,step):
# there is a less than 1% chance every time that direction is changed
if random.uniform(0,1)<0.005:
self.direction = random.randint(1,4)
if self.direction == 1:
return x, y+step # up
elif self.direction == 2:
return x+step, y # right
elif self.direction == 3:
return x, y-step # down
elif self.direction == 4:
return x-step, y # left
else:
return x, y # stop
pygame.init()
size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
screen_rect=screen.get_rect()
pygame.display.set_caption("TEST")
worker = Worker("worker.png", [0,0])
w_x = worker.rect.left
w_y = worker.rect.top
bg = Background("background.jpg", [0,0])
#sprite_group = pygame.sprite.Group()
#sprite_group.add(worker)
carryOn = True
clock=pygame.time.Clock()
while carryOn:
for event in pygame.event.get():
if event.type==pygame.QUIT:
carryOn=False
pygame.display.quit()
pygame.quit()
quit()
# Draw floor layout
screen.blit(pygame.transform.scale(bg.image, (SCREENWIDTH, SCREENHEIGHT)), bg.rect)
# Draw geo-fences
geofence1 = pygame.draw.rect(screen, GREEN, [510,150,75,52])
geofence2 = pygame.draw.rect(screen, GREEN, [450,250,68,40])
w_x,w_y = worker.makeRandomStep(w_x,w_y,1)
# Worker should not go outside the screen area
if (w_x + worker.rect.width > SCREENWIDTH): w_x = SCREENWIDTH - worker.rect.width
if (w_x < 0): w_x = 0
if (w_y + worker.rect.height > SCREENHEIGHT): w_y = SCREENHEIGHT - worker.rect.height
if (w_y < 0): w_y = 0
worker.rect.clamp_ip(screen_rect)
screen.blit(worker.image, (w_x,w_y))
# Refresh Screen
pygame.display.flip()
#sprite_group.update()
#sprite_group.draw(screen)
#Number of frames per secong e.g. 60
clock.tick(20)
pygame.display.quit()
pygame.quit()
quit()
It is not very clear to me how should I proceed to my goal. I was thinking to use sprite_group, but I misunderstand how to correctly update all sprites (workers) inside the while loop.
Any help is highly appreciated. Thanks.
You have to move all worker logic into the Worker class (setting random values, updating position etc). Then create multiple instances.
Here's a running example. Note the comments for explanations:
import pygame, random
import sys
WHITE = (255, 255, 255)
GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
SCREENWIDTH=1000
SCREENHEIGHT=578
class Background(pygame.sprite.Sprite):
def __init__(self, image_file, location, *groups):
# we set a _layer attribute before adding this sprite to the sprite groups
# we want the background to be actually in the back
self._layer = -1
pygame.sprite.Sprite.__init__(self, groups)
# let's resize the background image now and only once
# always call convert() (or convert_alpha) after loading an image
# so the surface will have to correct pixel format
self.image = pygame.transform.scale(pygame.image.load(image_file).convert(), (SCREENWIDTH, SCREENHEIGHT))
self.rect = self.image.get_rect(topleft=location)
# we do everthing with sprites now, because that will make our live easier
class GeoFence(pygame.sprite.Sprite):
def __init__(self, rect, *groups):
# we set a _layer attribute before adding this sprite to the sprite groups
self._layer = 0
pygame.sprite.Sprite.__init__(self, groups)
self.image = pygame.surface.Surface((rect.width, rect.height))
self.image.fill(GREEN)
self.rect = rect
class Worker(pygame.sprite.Sprite):
def __init__(self, image_file, location, *groups):
# we set a _layer attribute before adding this sprite to the sprite groups
# we want the workers on top
self._layer = 1
pygame.sprite.Sprite.__init__(self, groups)
self.image = pygame.transform.scale(pygame.image.load(image_file).convert_alpha(), (40, 40))
self.rect = self.image.get_rect(topleft=location)
# let's call this handy function to set a random direction for the worker
self.change_direction()
# speed is also random
self.speed = random.randint(2, 4)
def change_direction(self):
# let's create a random vector as direction, so we can move in every direction
self.direction = pygame.math.Vector2(random.randint(-100, 100), random.randint(-100, 100))
# we don't want a vector of length 0, because we want to actually move
# it's not enough to account for rounding errors, but let's ignore that for now
while self.direction.length() == 0:
self.direction = pygame.math.Vector2(random.randint(-100, 100), random.randint(-100, 100))
# always normalize the vector, so we always move at a constant speed at all directions
self.direction = self.direction.normalize()
def update(self, screen):
# there is a less than 1% chance every time that direction is changed
if random.uniform(0,1)<0.005:
self.change_direction()
# now let's multiply our direction with our speed and move the rect
vec = [int(v) for v in self.direction * self.speed]
self.rect.move_ip(*vec)
# if we're going outside the screen, move back and change direction
if not screen.get_rect().contains(self.rect):
self.change_direction()
self.rect.clamp_ip(screen.get_rect())
pygame.init()
# currently, one group would be enough
# but if you want to use some collision handling in the future
# it's best to group all sprites into special groups (no pun intended)
all_sprites = pygame.sprite.LayeredUpdates()
workers = pygame.sprite.Group()
fences = pygame.sprite.Group()
screen = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT))
pygame.display.set_caption("TEST")
# create multiple workers
for pos in ((0,0), (100, 100), (200, 100)):
Worker("worker.png", pos, all_sprites, workers)
# create multiple of these green thingies
for rect in (pygame.Rect(510,150,75,52), pygame.Rect(450,250,68,40)):
GeoFence(rect, all_sprites, fences)
# and the background
Background("background.jpg", [0,0], all_sprites)
carryOn = True
clock = pygame.time.Clock()
while carryOn:
for event in pygame.event.get():
if event.type==pygame.QUIT:
carryOn = False
# see how clean our main loop is
# just calling update and draw on the all_sprites group
all_sprites.update(screen)
all_sprites.draw(screen)
pygame.display.flip()
clock.tick(20)
this program makes boxes move, but i need to make them move randomly and indepensent of each other,
by calling the method "rect.move()" for each of the boxes but i don't know how to do that can u help me.
ex. of how it should not look like: https://youtu.be/D7rkcA0-BR0
import pygame
import random
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
class Rect():
def __init__(self):
self.rectXPos = 0
self.rectYPos = 0
self.height = 0
self.width = 0
self.changeX = 0
self.changeY = 0
self.x = 0
self.y = 0
def move(self):
self.x += self.changeX
self.y += self.changeY
def draw(self,screen):
pygame.draw.rect(screen,RED,[self.x + self.rectXPos, self.y + self.rectYPos, self.height,self.width])
pygame.init()
# Set the width and height of the screen [width, height]
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
myList =[]
for i in range(10):
rect = Rect()
rect.rectXPos = random.randrange(0,700)
rect.rectYPos = random.randrange(0,500)
rect.height = random.randrange(20,70)
rect.width = random.randrange(20,70)
rect.changeX = random.randrange(-3,3)
rect.changeY = random.randrange(-3,3)
myList.append([rect.rectXPos , rect.rectYPos, rect.height, rect.width, rect.changeX, rect.changeY])
# -------- Main Program Loop -----------
while not done:
# --- Main event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# --- 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(WHITE)
for i in range(10):
rect.rectXPos = myList[i][0]
rect.rectYPos = myList[i][1]
rect.height = myList[i][2]
rect.width = myList[i][3]
rect.changeX = myList[i][4]
rect.changeY= myList[i][5]
rect.draw(screen)
rect.move()
# --- Drawing code should go here
# --- Go ahead and update 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 premade code from http://programarcadegames.com/
What you need is for the Rect attributes to be randomly generated with the random module. I have modified the code you gave an made some changes.
Firstly I changed the draw method so that it just draws at the x and y values.
The biggest change was that instead of the big complicated myList list in your code, I just stored 10 Rect objects in a list called myRects which I think is much simpler.
You can fiddle around some more with the number generation from around Line 45-52. You can read a bit more on the random.randrange() function here: https://docs.python.org/3/library/random.html#functions-for-integers
I hope this answer helped you! If you have any further questions please post a comment below!
import pygame
import random
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
class Rect():
def __init__(self):
self.x = 0
self.y = 0
self.height = 0
self.width = 0
self.changeX = 0
self.changeY = 0
def move(self):
self.x += self.changeX
self.y += self.changeY
def draw(self, screen):
pygame.draw.rect(screen, RED, [self.x, self.y, self.width, self.height], 0)
pygame.init()
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
done = False
clock = pygame.time.Clock()
myRects = []
for i in range(10):
rect = Rect()
rect.x = random.randrange(0, 700)
rect.y = random.randrange(0, 700)
rect.width = random.randrange(20, 70)
rect.height = random.randrange(20, 70)
rect.changeX = random.randrange(-3, 3)
rect.changeY = random.randrange(-3, 3)
myRects.append(rect)
print(myRects)
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(WHITE)
for rect in myRects:
rect.draw(screen)
rect.move()
pygame.display.update()
clock.tick(10)
pygame.quit()
quit()