Python pygame balls moving - python

I am writing a simple "game" and I have three questions for you:
How can I make all the balls moving independetly?
When I drag a ball with a mouse and click on the screen, how can i make the ball stay there. I want to draw it on that specific coordinate where the mouse key was pressed. It has to stay there all the time.
If a small ball touches the large one it shoud become a large one and dissapear after 10 seconds.
I have no idea how to do this. Can you please help me.
My code:
import pygame
import sys
from pygame.locals import *
import random
pygame.init()
width = 800
height = 600
fps = 25
clock = pygame.time.Clock()
black = (0, 0, 0)
white = (255, 255, 255)
display_window = pygame.display.set_mode((width, height))
pygame.display.set_caption('Bouncy')
game_over = False
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
x_cor = random.randint(15, width - 15)
y_cor = random.randint(15, height - 15)
x_change = random.randint(3, 7)
y_change = random.randint(3, 7)
coordinates = []
for i in range(10):
x = random.randint(0, width)
y = random.randint(0, height)
coordinates.append([x, y])
while not game_over:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
if event.type == pygame.mouse.get_pressed():
pass
x_cor += x_change
y_cor += y_change
display_window.fill(white)
mouse_x, mouse_y = pygame.mouse.get_pos()
for coordinate in coordinates:
pygame.draw.circle(display_window, (r, g, b), (coordinate[0], coordinate[1]), 15, 0)
pygame.draw.circle(display_window, black, (mouse_x, mouse_y), 25, 0)
pygame.draw.circle(display_window, (r, g, b), (x_cor, y_cor), 15, 0)
if x_cor > (width - 15) or x_cor < 15:
x_change = x_change * -1
if y_cor > (height - 15)or y_cor < 15:
y_change = y_change * -1
clock.tick(fps)
pygame.display.update()

First and foremost, do the research required before you post here (see the help documents on the intro tour). There are many tutorials on the Internet, and many answered questions in SO (StackOverflow) that deal with moving objects. To get you started in general:
You move the balls independently by keeping a separate set of coordinates for each ball. On each iteration of the game clock, you have to reiterate the new coordinates of each ball.
To make a ball stay in one place, simply do not change its coordinates.
To change the size of a ball, draw it with a larger radius. This means that you also have to remember the radius of each ball. To give it a 10-second lifetime, keep a "lifespan" for each ball; decrement it on each tick of the game clock.
Bascially, you need a Ball object (make a class Ball); instantiate a new object for each ball you need. Write methods to change the position, size, and life span of each ball.

Related

Python cleaning and visual improvement

I'm just starting to learn python, specifically pygame, and am trying to make a simple jumping game. I made a basic movement script as a test, but the animations are really choppy. Whenever the block moves, there's an afterimage, and it looks like its just breaking down. Also, if you have any suggestions for cleaning up the script, that'd be great.
import pygame
from pygame.locals import *
SIZE = 800, 600
RED = (255, 0, 0)
GRAY = (150, 150, 150)
x = 50
y = 50
pygame.init()
screen = pygame.display.set_mode(SIZE)
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
pressed = pygame.key.get_pressed()
if pressed[pygame.K_RIGHT]:
x += 3
if pressed[pygame.K_LEFT]:
x -= 3
if pressed[pygame.K_UP]:
y -= 3
if pressed[pygame.K_DOWN]:
y += 3
rect = Rect(x, y, 50, 50)
screen.fill(GRAY)
pygame.draw.rect(screen, RED, rect)
pygame.display.flip()
pygame.quit()
In PyGame, you have to manage FPS in order to keep your game constant. For example, if you have a really fast computer you will have like 200 or 300 FPS and on a little scene like you did, every second your player will move by 200 times the speed, so this is quite fast, otherwise your computer is a really old one, you'll get like 30 FPS, and your player will move by only 30 times your speed every second, and that's obviously way slower.
What I want to explain to you is that FPS are essential so your game can have constant moves and velocity.
So I added just to lines to configure FPS, I set 60 and changed the speed to 10 but you can easily adapt these values for your computer.
import pygame
from pygame.locals import *
SIZE = 800, 600
RED = (255, 0, 0)
GRAY = (150, 150, 150)
x = 50
y = 50
pygame.init()
screen = pygame.display.set_mode(SIZE)
# creating a clock
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
pressed = pygame.key.get_pressed()
if pressed[pygame.K_RIGHT]:
x += 10
if pressed[pygame.K_LEFT]:
x -= 10
if pressed[pygame.K_UP]:
y -= 10
if pressed[pygame.K_DOWN]:
y += 10
rect = Rect(x, y, 50, 50)
screen.fill(GRAY)
pygame.draw.rect(screen, RED, rect)
# setting the fps to 60, depending on your machine, 60 fps is great in my opinion
clock.tick(60)
pygame.display.flip()
pygame.quit()

Image rotation not working as expected

I am very new to python/pygame, and would like some help. I am trying to make two cars automatically move forward(which I have completed successfully) however I cannot manage to make the cars turn left/right when a certain key is pressed. I would love someone to help me with this. As I said, I am new to this, so if anyone was kind enough to help, please can you edit my code so it is successful as well as an explanation to what is going wrong, thank you so very much in advance. https://i.stack.imgur.com/zrlUT.png
https://i.stack.imgur.com/q6Hb9.png
https://i.stack.imgur.com/MGR3N.jpg
P.S. There is no error message to my code, as there is no wrong in it, the rotate function is simply not working
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((1150, 800))
pygame.display.set_caption("Car Football")
degrees = 180
x = 70
y = 70
x1 = 1000
y1 = 400
width = 70
height = 70
vel = 15
vel1 = 15
def rotatedleft():
pygame.transform.rotate(redcar, (15))
def rotatedright():
pygame.transform.rotate(redcar, (-15))
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
screen.fill((0, 0, 0))
bgImg = pygame.image.load("Football_pitch.png").convert()
screen.blit(bgImg, [0,0])
redcar = pygame.image.load("redcar.png")
screen.blit(redcar, (x, y))
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
rotatedleft = True
if run:
x += vel
if keys[pygame.K_RIGHT]:
rotatedright = True
pygame.display.flip()
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if run:
x1 -= vel1
if keys[pygame.K_d] and x1 < 1150:
x1 += vel1
if keys[pygame.K_w]:
y1 -= vel1
if keys[pygame.K_s]:
y1 += vel1
bluecar = pygame.image.load("Bluecarss.png")
screen.blit(bluecar, (x1, y1))
circleball = pygame.draw.circle(screen, (255, 255, 255), (300, 140), 50, 0)
pygame.display.update()
pygame.display.flip()
pygame.quit()
sys.exit()
You need to know trigonometry or vectors if you want to rotate a car in your game and move it in the direction it is facing (I'm using vectors in the following example). The position and the velocity should be vectors and you have to add the vel to the pos vector every frame to move the car forward. You also need a pygame.Rect which is used as the blit position (the rect makes it easier to center the car and can be used for collision detection).
When the user presses ← or →, you have to rotate the angle and the vel vector (vel is also the direction) and then use the angle to rotate the image/pygame.Surface. As for the image rotation, you should keep a reference to the original image in order to preserve the quality of the image. Pass it to pygame.transform.rotate together with the current angle of the car and you'll get a rotated surface. This surface will have different dimensions, so you need to create a new rect (with pygame.Surface.get_rect) to update the blit position (top left coordinates).
import pygame
from pygame.math import Vector2
pygame.init()
screen = pygame.display.set_mode((1150, 800))
clock = pygame.time.Clock() # A clock to limit the frame rate.
# Load your images once at the beginning of the program.
REDCAR_ORIGINAL = pygame.Surface((50, 30), pygame.SRCALPHA)
pygame.draw.polygon(
REDCAR_ORIGINAL, (200, 0, 0), [(0, 0), (50, 10), (50, 20), (0, 30)])
redcar = REDCAR_ORIGINAL
# Use vectors for the position and the velocity.
pos = Vector2(70, 70) # Center position of the car.
vel = Vector2(2, 0)
# This rect serves as the blit position of the redcar image.
rect = redcar.get_rect(center=pos)
angle = 0 # Current angle of the car.
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
# When a key gets pressed, increment the angle, rotate
# the vector and create a new rotated car image.
# The angle is rotated in the opposite direction because
# pygame's y-axis is flipped.
angle += 3
vel.rotate_ip(-3)
redcar = pygame.transform.rotate(REDCAR_ORIGINAL, angle)
# Also, get a new rect because the image size was changed.
# Pass the pos vector as the `center` argument to keep the
# image centered.
rect = redcar.get_rect(center=pos)
elif keys[pygame.K_RIGHT]:
angle -= 3
vel.rotate_ip(3)
redcar = pygame.transform.rotate(REDCAR_ORIGINAL, angle)
rect = redcar.get_rect(center=pos)
# Move the car by adding the velocity to the position.
pos += vel
rect.center = pos # Update the rect as well.
screen.fill((30, 30, 30))
screen.blit(redcar, rect) # Blit the car at the `rect.topleft` coords.
pygame.display.flip()
clock.tick(60) # Limit the frame rate to 60 FPS.
pygame.quit()
if keys[pygame.K_LEFT]:
rotatedleft = True
You're assigning True to rotatedleft, which you've previously defined as a function, try calling the function, like so:
if keys[pygame.K_LEFT]:
rotatedleft()
Now it's kinda turning, I'm pretty sure it's still not quite what you're looking for but hey, baby steps. Best of luck with your game.
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((1150, 800))
pygame.display.set_caption("Car Football")
degrees = 180
x = 70
y = 70
x1 = 1000
y1 = 400
width = 70
height = 70
vel = 15
vel1 = 15
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
screen.fill((0, 0, 0))
bgImg = pygame.image.load("Football_pitch.png").convert()
screen.blit(bgImg, [0,0])
redcar = pygame.image.load("redcar.png")
screen.blit(redcar, (x, y))
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
redcar = pygame.transform.rotate(redcar, 15)
screen.blit(redcar, (x, y))
if run:
x += vel
if keys[pygame.K_RIGHT]:
redcar = pygame.transform.rotate(redcar, -15)
screen.blit(redcar, (x, y))
pygame.display.flip()
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if run:
x1 -= vel1
if keys[pygame.K_d] and x1 < 1150:
x1 += vel1
if keys[pygame.K_w]:
y1 -= vel1
if keys[pygame.K_s]:
y1 += vel1
bluecar = pygame.image.load("Bluecarss.png")
screen.blit(bluecar, (x1, y1))
circleball = pygame.draw.circle(screen, (255, 255, 255), (300, 140), 50, 0)
pygame.display.update()
pygame.display.flip()
pygame.quit()
sys.exit()

Pygame's rect object 'stretches' instead of moving [duplicate]

This question already has answers here:
How can I move the ball instead of leaving a trail all over the screen in pygame?
(1 answer)
Why is nothing drawn in PyGame at all?
(2 answers)
Closed 2 years ago.
I am currently creating my first Python game using pygame and have now come across something that baffles me so I would appreciate your help.
In the current statues of the game, all that there is on the screen is an image of a space ship over a white background (gameDisplay.fill(white)) that can only move up and down, located at the left side of the screen. When clicking on the space bar, the space ship shoots two laser beams (or basically creates two thin rects that move from left to right, changing x position but keeping the y position so that the movement would be only horizontal).
The problem that I have is that instead of moving from left to right, it seems as though the 'lasers' stretch out to the right, so that the left side of the rect stays near the space ship image on the left of the screen while the right side of the rect moves to toward the right side of the screen.
As shown in the image below:
Laser stretching out
After playing around with the problem, I found that if I use an image as a background instead of filling the background with the color white, everything works as it should.
In the image below you can see how it looks when I use a plain white picture as a background image (Using bg = pygame.image.load("img\white_background.png" and then blitting it inside the game loop before all other drawings):
Laser working fine
I currently have 4 files that make up the game:
1 main.py:
import time
import pygame
from first_game.game_loop import game_loop
from first_game.space_ship import space_ship
pygame.init()
display_width = 800
display_height = 600
colors = {
'black':(0, 0, 0),
'white':(255, 255, 255),
'red':(255, 0, 0)
}
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('First game')
clock = pygame.time.Clock()
gameDisplay.fill(colors['white'])
player = space_ship("img\\space_ship.png","player",103,103)
game_loop(gameDisplay,display_width,display_height,clock, player, bg)
2 game_loop.py:
import pygame
import first_game.methods
def game_loop(gameDisplay, display_width, display_height, clock, space_ship, bg):
space_ship_x = (display_width * 0.05)
space_ship_y = (display_height * 0.45)
space_ship_y_change = 0
both_laser_x = 0
top_laser_y = 0
bottom_laser_y = 0
both_laser_width = 50
both_laser_height = 5
laser_speed = 15
laser_adjustment_x = 70
laser_adjustment_y = 18
laser_fired = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
space_ship_y_change = -5
if event.key == pygame.K_DOWN:
space_ship_y_change = 5
if event.key == pygame.K_SPACE:
top_laser_y = space_ship_y + laser_adjustment_y
bottom_laser_y = space_ship_y + space_ship.height - laser_adjustment_y
both_laser_x = space_ship_x + space_ship.width - laser_adjustment_x
laser_fired = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
space_ship_y_change = 0
if both_laser_x>display_width:
laser_fired=False
first_game.methods.space_ship(space_ship.img_location, space_ship_x, space_ship_y, gameDisplay)
if laser_fired == True:
first_game.methods.laser(gameDisplay,both_laser_x, top_laser_y,bottom_laser_y,both_laser_width,both_laser_height)
both_laser_x += laser_speed
if space_ship_y == -20:
if space_ship_y_change<0:
space_ship_y_change=0
if space_ship_y+space_ship.height>=display_height+20:
if space_ship_y_change>0:
space_ship_y_change=0
space_ship_y = space_ship_y + space_ship_y_change
pygame.display.update()
clock.tick(60)
3 methods.py:
def space_ship(space_ship_location, x, y, gameDisplay):
space_ship_img = pygame.image.load(space_ship_location)
gameDisplay.blit(space_ship_img, (x, y))
def laser(gameDisplay,x,y1,y2,w,h):
pygame.draw.rect(gameDisplay, (255,0,0), [x, y1, w, h])
pygame.draw.rect(gameDisplay, (255,0,0), [x, y2, w, h])
4 space_ship.py
class space_ship():
def __init__(self,img_location, type, width, height):
self.img_location = img_location
self.type = type
self.width = width
self.height = height

How can I stop a character in pygame from leaving the edge of the screen?

I have created a small program in pygame where the player controls a blue square moving around the screen, but I want to stop the player from moving past the edge of the screen. Here is the code I have so far, how can I do this?
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
done = False
x = 30
y = 30
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
is_blue = not is_blue
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]: y -= 5
if pressed[pygame.K_DOWN]: y += 5
if pressed[pygame.K_LEFT]: x -= 5
if pressed[pygame.K_RIGHT]: x += 5
screen.fill((0, 0, 0))
color = (0, 128, 255)
pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))
pygame.display.flip()
clock.tick(60)
pygame.Rects have a clamp (and clamp_ip) method which you can use to limit the movement area. So create a rect with the size of the screen (called screen_rect here) and a rect for the player (player_rect) and call the clamp_ip method after each movement to keep it inside of the screen area.
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
BG_COLOR = pg.Color(30, 30, 50)
def main():
clock = pg.time.Clock()
image = pg.Surface((50, 30))
image.fill(pg.Color('dodgerblue'))
pg.draw.rect(image, pg.Color(40, 220, 190), (0, 0, 49, 29), 2)
player_rect = image.get_rect(topleft=(200, 200))
# This pygame.Rect has the dimensions of the screen and
# is used to clamp the player_rect to this area.
screen_rect = screen.get_rect()
speed = 5
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
return
pressed = pg.key.get_pressed()
if pressed[pg.K_UP]:
player_rect.y -= speed
if pressed[pg.K_DOWN]:
player_rect.y += speed
if pressed[pg.K_LEFT]:
player_rect.x -= speed
if pressed[pg.K_RIGHT]:
player_rect.x += speed
# Clamp the rect to the dimensions of the screen_rect.
player_rect.clamp_ip(screen_rect)
screen.fill(BG_COLOR)
screen.blit(image, player_rect)
pg.display.flip()
clock.tick(60)
if __name__ == '__main__':
main()
pg.quit()
This should work
if pressed[pygame.K_UP] and y > 0: y -= 5
if pressed[pygame.K_DOWN] and y < 600 - 60: y += 5
if pressed[pygame.K_LEFT] and x > 0: x -= 5
if pressed[pygame.K_RIGHT] and x < 800 - 60: x += 5
Where 600 and 800 is the screen size and 60 the size of your rectangle
Something like:
if pressed[pygame.K_UP]:
if not (y > maxwidth or y < 0):
y += 5
And so on for the others. the maxwidth looks like 600 in your code but I'd put it at the top of your code so you dont keep having to change it in different places.
What you are trying to do is called edge detection, as in detect if you are at an edge, in this case you want the edges to be the screen's edges. what you should do, is check if your x or y are at an edge, if so don't go any further.
if pressed[pygame.K_UP]:
if 0 < y-5 < 600: #0 and 600 being the edges of your screen, you can use a variable to change it dynamically later one
y -= 5
Note this will only detect if the top left's square is going out of bounds, since x and y is the top and left coords for the rectangle, meaning the bottom right of the square will be able to still go out of bounds,
If you want to check the whole square, you will have to make adjustment calculations in the if statement, or base your x and y on the center (which you will still have to modify the if statement to something like below. (note I'm altering based on your current code for x and y being top left.
if pressed[pygame.K_UP]:
if (0 < y-5 < 600) or (0< y+60-5 <600) #0 and 600 being the edges of your screen, you can use a variable to change it dynamically later one
y -= 5
This checks the other side of the square. Note for x you will check for the horizontal limits which in this case is 800. Also we are checking including the -5 because we want to see where we are going, not where we are at.

How to make the object move during a while infinite loop?

I've been trying to create a game. In the game there is a jet that would fly into the recursive background rectangles. The rectangles are created through an infinite loop so once it enters the loop rest of the functions don't work for example the object. My code is below and the problem arises in the main loop. I want the object to move with the recursive rectangles but it freezes when the rectangles start being drawn in the loop. PS help to fix this as I've tried almost every code sample out there to fix it. Thank you
EDIT: the main function of the game is to make the jet go through what seems like recursive like rectangles (there are two of them and the while loop makes it simultaneously move up and down giving the feeling that the jet is going into the screen.). But since the jet is drawn first, when the program enters the rectangle loop the jet freezes and wont be able to move. I want the jet to move while the background is also moving.
import pygame
import random
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
Blue = (2,55,55)
black=(0,0,0)
end_it=False
def recursive_draw(x, y, width, height):
""" Recursive rectangle function. """
pygame.draw.rect(screen, WHITE,
[x, y, width, height],
1)
speed = [10,0]
rect_change_x = 10
rect_change_y = 10
# Is the rectangle wide enough to draw again?
if (width > 25):
# Scale down
x += width * .1
y += height * .1
width *= .8
height *= .8
# Recursively draw again
recursive_draw(x, y, width, height)
def recursive_draw2(x, y, width, height):
""" Recursive rectangle function. """
pygame.draw.rect(screen, Blue,
[x, y, width, height],
1)
speed = [10,0]
rect_change_x = 10
rect_change_y = 10
# Is the rectangle wide enough to draw again?
if (width > 25):
x += width * .1
y += height * .1
width *= .8
height *= .8
# Recursively draw again
recursive_draw2(x, y, width, height)
'''
def timer(self):
screen.fill(black)
myfont=pygame.font.SysFont("Britannic Bold", 40)
label2=myfont.render("Ready?", 1, (255, 0, 0))
screen.blit(label2, (350,250))
self =3
nlist=[]
for i in range (2):
score = myfont.render(str(self),1,(255,0,0))
screen.blit((score), (350,250))
self = self - 1
nlist.append(self)
pygame.display.flip()
'''
pygame.init()
#rectanglelist = [big()]
# Set the height and width of the screen
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()
USEREVENT = 0
pygame.time.set_timer(USEREVENT+1, 10)
milliseconds = 0
seconds = 0
start_it = False
while (end_it==False):
screen.fill(black)
myfont=pygame.font.SysFont("Britannic Bold", 40)
nlabel=myfont.render("Welcome to "+ " Jet shooter ", 1, (255, 0, 0))
label=myfont.render("Click on the mouse to start ", 1, (255, 0, 0))
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
end_it=True
screen.blit(nlabel,(200, 100))
screen.blit(label, (170,300))
pygame.display.flip()
while (start_it==False):
screen.fill(black)
myfont2=pygame.font.SysFont("Britannic Bold", 40)
label2=myfont2.render("Ready?", 1, (255, 0, 0))
screen.blit(label2, (300,250))
pygame.display.flip()
pygame.time.wait(3000)
start_it = True
fall = False
while (fall==False):
nlist = [3,2,1]
for i in (nlist):
screen.fill(black)
n = str(i)
myfont3=pygame.font.SysFont("Britannic Bold", 40)
score = myfont3.render(n,1,(255,0,0))
screen.blit((score), (350,250))
pygame.display.flip()
pygame.time.wait(1000)
screen.fill(black)
myfont4=pygame.font.SysFont("Britannic Bold", 40)
label4=myfont3.render("GOOO!!!", 1, (255, 0, 0))
screen.blit(label4, (300,250))
pygame.display.flip()
pygame.time.wait (1000)
fall = True
b = 0
flip = 1
a = 0
time = 100
x_speed = 0
y_speed = 0
x_coord = 320
y_coord = 400
image = pygame.image.load("spaceship.gif").convert()
# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# User pressed down on key
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_speed = -10
if event.key == pygame.K_RIGHT:
x_speed = 10
if event.key == pygame.K_UP:
y_speed = -10
if event.key == pygame.K_DOWN:
y_speed = 10
# User let go of key
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
x_speed = 0
if event.key == pygame.K_RIGHT:
x_speed = 0
if event.key == pygame.K_UP:
y_speed = 0
if event.key == pygame.K_DOWN:
y_speed = 0
x_coord += x_speed
y_coord += y_speed
# Set the screen background
screen.fill(BLACK)
screen.blit(image, [x_coord,y_coord])
pygame.display.flip()
clock.tick(60)
# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
# Go ahead and update the screen with what we've drawn.
# Limit to 60 frames per second
# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
while a == 0 :
if flip == 1 :
recursive_draw(35,25,625,450)
recursive_draw2(0, 0, 700, 500)
flip = flip + 1
pygame.display.flip()
clock.tick(60)
if flip == 2 :
recursive_draw(0, 0, 700, 500)
recursive_draw2(35, 25, 625, 450)
flip = flip - 1
pygame.display.flip()
clock.tick(60)
pygame.quit()
As #Paul Rooney has stated, you'll want to use threads. Here's how you would
import thread
.
.
.
# Instead of calling the function as you are, run it on a new thread
thread.start_new_thread(drawRectanglesFunction, ())
From what I can tell is that you're drawing things in the incorrect order, and I believe that while loop is not needed. (while a == 0). Another thing is that you're flipping the display too often it is hard to keep track of what gets drawn first, and what gets drawn afterwards. My suggestion would be to quickly rewrite your program so that it looks something similar to this:
flip = 1
while not done:
##Catch and handle events()
screen.fill(BLACK)
if flip == 1 :
recursive_draw(35,25,625,450)
recursive_draw2(0, 0, 700, 500)
flip = flip + 1
elif flip == 2 :
recursive_draw(0, 0, 700, 500)
recursive_draw2(35, 25, 625, 450)
flip = flip - 1
screen.blit(image, [x_coord,y_coord])
pygame.display.flip()
clock.tick(60);
I hope this helps out a little.
(Edit: I did this on my own and got the program to run)

Categories