I tried to build a simple game in python using pygame. At first my problem was to make the movement more smooth, because about every second the movement of the rectangles stuck for a few milliseconds. Then I found an solution by adding "os.environ['SDL_VIDEODRIVER'] = 'directx'" in to my code and changing the display mode to "FULLSCREEN" and "DOUBLEBUFF". The movement is more fluid now, but whenever I Alt + Tab out of the fullscreen game, i get this error:
Traceback (most recent call last):
File "C:\Users\L-Tramp-GAMING\Documents\Python\Game\Main_Game.py", line 64, in <module>
screen.fill(BG_COLOR)
pygame.error: IDirectDrawSurface3::Blt: Surface was lost
I don't know how to bypass this problem. I am also wondering if i can somehow run the game in windowed mode with the directx line added in normal speed. At the moment the game runs in much higher speed when it is in windowed mode. I hope some of you guys can help me. Thank you, Paul
import pygame
import random
import os
#Variables
WIDTH = 1280
HEIGHT = 720
GAME_OVER = False
BG_COLOR = (0, 0, 20)
playerWidth = 50
playerHeight = 50
playerPosX = WIDTH / 2 - playerWidth / 2
playerPosY = HEIGHT - (playerHeight + 75)
playerSpeed = 10
enemieWidth = 75
enemieHeight = 75
enemiePosX = random.randint(0, WIDTH - enemieWidth)
enemiePosY = 0
enemieSpeed = 5
enemieCounter = 1
####################################################################################################
os.environ['SDL_VIDEODRIVER'] = 'directx'
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN | pygame.DOUBLEBUF)
pygame.display.set_caption("Game")
pygame.key.set_repeat(1, 10)
clock = pygame.time.Clock()
#GameLoop
while not GAME_OVER:
for e in pygame.event.get():
if e.type == pygame.QUIT:
GAME_OVER = True
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_a:
playerPosX -= playerSpeed
print(hex(screen.get_flags() & 0xFFFFFFFF))
if e.key == pygame.K_d:
playerPosX += playerSpeed
#Graphics
screen.fill(BG_COLOR)
player = pygame.draw.rect(screen, (0, 255, 0), (playerPosX, playerPosY, playerWidth, playerHeight))
if enemiePosY < HEIGHT:
enemie = pygame.draw.rect(screen, (255, 0, 0), (enemiePosX, enemiePosY, enemieWidth, enemieHeight))
enemiePosY += enemieSpeed
else:
enemieCounter += 1
enemiePosY = 0
enemiePosX = random.randint(0, WIDTH - enemieWidth)
if (enemieCounter + 1) % 2 == 0:
pass
#End Graphics
pygame.display.flip()
Your movement lag was caused by pygame.key.set_repeat. To allow the player to hold down a and d to move you can update the players position in your game loop instead of using set_repeat by keeping track of a speed variable. If you wanted to use os.environ for another reason besides fixing the lag then this won't work but otherwise this should be fine.
import pygame
import random
import os
#Variables
WIDTH = 1280
HEIGHT = 720
GAME_OVER = False
BG_COLOR = (0, 0, 20)
playerWidth = 50
playerHeight = 50
playerPosX = WIDTH / 2 - playerWidth / 2
playerPosY = HEIGHT - (playerHeight + 75)
playerSpeed = 10
enemieWidth = 75
enemieHeight = 75
enemiePosX = random.randint(0, WIDTH - enemieWidth)
enemiePosY = 0
enemieSpeed = 5
enemieCounter = 1
####################################################################################################
#os.environ['SDL_VIDEODRIVER'] = 'directx'
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Game")
#pygame.key.set_repeat(1, 10) <----- This line is the problem
clock = pygame.time.Clock()
#GameLoop
speed = 0
while not GAME_OVER:
for e in pygame.event.get():
if e.type == pygame.QUIT:
GAME_OVER = True
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_a:
speed = -playerSpeed
if e.key == pygame.K_d:
speed = +playerSpeed
playerPosX += speed
#Graphics
screen.fill(BG_COLOR)
player = pygame.draw.rect(screen, (0, 255, 0), (playerPosX, playerPosY, playerWidth, playerHeight))
if enemiePosY < HEIGHT:
enemie = pygame.draw.rect(screen, (255, 0, 0), (enemiePosX, enemiePosY, enemieWidth, enemieHeight))
enemiePosY += enemieSpeed
else:
enemieCounter += 1
enemiePosY = 0
enemiePosX = random.randint(0, WIDTH - enemieWidth)
if (enemieCounter + 1) % 2 == 0:
pass
#End Graphics
pygame.display.flip()
Can the code handle the error, and then try re-creating the screen object ?
This is the same sort of process as when switching from full-screen to windowed.
EDIT: Added some code from the PyGame Wiki: https://www.pygame.org/wiki/toggle_fullscreen to hopefully work around further issues from OP's comment.
try:
screen.fill(BG_COLOR)
except pygame.error as e:
# Get the size of the screen
screen_info= pygame.display.Info()
cursor = pygame.mouse.get_cursor() # Duoas 16-04-2007
new_width = screen_info.current_w
new_height = screen_info.current_h
# re-initialise the display, creating a re-sizable window
pygame.display.quit()
pygame.display.init()
screen = pygame.display.set_mode( ( new_width, new_height ), pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE )
pygame.key.set_mods( 0 ) # HACK: work-a-round for a SDL bug??
pygame.mouse.set_cursor( *cursor ) # Duoas 16-04-2007
# did it work?
screen.fill(BG_COLOR)
Related
So I'm working on a pong copy using pygame. So far everything was working fine with pygame and everything was rendering. I wanted to add the player score to the screen, and I can't get it up. I'm not actually familiar with pygame that much so I pretty muched copied the text code from the docs and other sources. However they would not render, but when I opened a standalone, python file, it worked fine. Here is my main.py file where I render text and a link to the demo using replit: https://replit.com/#Glitchez/Pong-demo?v=1
import pygame
from paddles import *
from controls import *
from ball import *
pygame.font.init()
# SCREEN INIT
pygame.init()
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong")
# VARIABLES
ball_radius = 7
paddle_speed = 5
paddle_length = 100
FPS = 60
# DEFINE OBJECTS
paddle1 = Paddle(paddle_length, 15, 100, paddle_speed, True, WHITE)
paddle2 = Paddle(paddle_length, 970, 100, paddle_speed, False, WHITE)
ball = Ball(WIDTH // 2, HEIGHT // 2, ball_radius)
font = pygame.font.SysFont(None, 24)
# COLLISION MANAGEMENT
def handle_collision(ball, paddle1, paddle2):
if ball.y + ball.radius >= HEIGHT:
ball.y_vel *= -1
elif ball.y - ball.radius <= 0:
ball.y_vel *= -1
if ball.x_vel < 0:
if paddle1.y <= ball.y <= paddle1.y + paddle1.height:
if ball.x - ball.radius <= paddle1.x + paddle1.width:
ball.x_vel *= -1
middle_y = paddle1.y + paddle1.height / 2
difference_in_y = middle_y - ball.y
reduction_factor = (paddle1.height / 2) / ball.MAX_VEL
y_vel = difference_in_y / reduction_factor
ball.y_vel = -1 * y_vel
else:
if paddle2.y <= ball.y <= paddle2.y + paddle2.height:
if ball.x + ball.radius >= paddle2.x:
ball.x_vel *= -1
middle_y = paddle2.y + paddle2.height / 2
difference_in_y = middle_y - ball.y
reduction_factor = (paddle2.height / 2) / ball.MAX_VEL
y_vel = difference_in_y / reduction_factor
ball.y_vel = -1 * y_vel
# HANDLE ALL GRAPHICS
def graphics(screen):
screen.fill(BLACK)
paddle1.draw(screen)
paddle2.draw(screen)
ball.draw(screen)
# DRAWS DOTTED LINE
for i in range(10, HEIGHT, HEIGHT // 20):
if i % 2 == 1:
continue
pygame.draw.rect(screen, WHITE, (WIDTH // 2 - 5, i, 8, HEIGHT // 40))
# GAME LOOP
def main():
run = True
clock = pygame.time.Clock()
P1_SCORE, P2_SCORE = 0, 0
#ISSUE HERE!!!
my_font = pygame.font.SysFont('Comic Sans MS', 30)
text_surface = my_font.render(str(P1_SCORE), False, (255, 255, 255))
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
win.blit(text_surface, (250,250))
paddle1.move()
paddle2.move()
ball.move()
handle_collision(ball, paddle1, paddle2)
P1_SCORE, P2_SCORE = ball.check_win(P1_SCORE, P2_SCORE)
graphics(win)
pygame.display.update()
print(f"player 1: {P1_SCORE}, player 2: {P2_SCORE}")
pygame.quit()
if __name__ == '__main__':
main()
The code is rendering the score correctly, blit()ing it to the window perfectly... but then erasing everything when the screen is painted in graphics().
So, you have a function graphics(), move the score-drawing into there.
# HANDLE ALL GRAPHICS
def graphics(screen, font, p1_score, p2_score):
screen.fill(BLACK)
paddle1.draw(screen)
paddle2.draw(screen)
ball.draw(screen)
# DRAWS DOTTED LINE
for i in range(10, HEIGHT, HEIGHT // 20):
if i % 2 == 1:
continue
pygame.draw.rect(screen, WHITE, (WIDTH // 2 - 5, i, 8, HEIGHT // 40))
# DRAWS THE SCORE
# PLAYER 1 (LEFT)
text_surface = my_font.render(str(p1_score), False, (255, 255, 255))
screen.blit(text_surface, (250,250))
# PLAYER 2 (RIGHT)
text_surface = my_font.render(str(p2_score), False, (255, 255, 255))
screen.blit(text_surface, (WIDTH-WIDTH//4,250)) # 25% from the right-side
# GAME LOOP
def main():
run = True
clock = pygame.time.Clock()
P1_SCORE, P2_SCORE = 0, 0
my_font = pygame.font.SysFont('Comic Sans MS', 30)
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
paddle1.move()
paddle2.move()
ball.move()
handle_collision(ball, paddle1, paddle2)
P1_SCORE, P2_SCORE = ball.check_win(P1_SCORE, P2_SCORE)
graphics(win, my_font, P1_SCORE, P2_SCORE)
pygame.display.update()
print(f"player 1: {P1_SCORE}, player 2: {P2_SCORE}")
pygame.quit()
NOTE: This is not tested code, errors and omissions should be expected.
If the text-rendering becomes slow, you could also pre-render all the scores to an array of surfaces on start-up. Then just blit the one that matches the score.
I am a noob in pygame and i have a problem. Pygame logo changes after a while. I have two images. Pls help! First image is how the window should look like and the second image is my window after 20 sec. What schould i do? I never had this problem and i tried so many things but i can't do it.
import pygame
import random
# initialize idk pygame.init()
# size Width = 800 Height = 600 white = (255, 255, 255) icon = pygame.image.load('sunflower.png') player_img =
pygame.image.load('cat.png') enemy1_img = pygame.image.load('dog.png')
FPS = 120 Vel = 5
# enemy random coordinates enemy1_X = random.randint(64, 736) enemy1_Y = random.randint(50, 150)
# screen def screen_f(p_rect, e_rect):
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('dog destroyer')
icon = pygame.image.load('sunflower.png')
pygame.display.set_icon(icon)
backgroud = pygame.image.load('backg.png')
screen.blit(backgroud, (0, 0))
screen.blit(player_img, (p_rect))
screen.blit(enemy1_img, (e_rect))
# player def player_movement(key_pressed, p_rect):
if key_pressed[pygame.K_RIGHT]:
p_rect.x += Vel
if key_pressed[pygame.K_LEFT]:
p_rect.x -= Vel
if key_pressed[pygame.K_UP]:
p_rect.y -= Vel
if key_pressed[pygame.K_DOWN]:
p_rect.y += Vel
def borders(p_rect):
if p_rect.x < 0:
p_rect.x = 0
elif p_rect.x > 735:
p_rect.x = 735
elif p_rect.y < 0:
p_rect.y = 0
elif p_rect.y > 535:
p_rect.y = 535
# main def main():
Vel_e = 4 # enemy velocity
player_rect = pygame.Rect(368, 500, 64, 64)
enemy_rect = pygame.Rect(enemy1_X, enemy1_Y, 64, 64)
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
key_pressed = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
enemy_rect.x += Vel_e
if enemy_rect.x >= 736:
Vel_e = -4
enemy_rect.y += 50
if enemy_rect.x < 0:
Vel_e = 4
enemy_rect.y += 50
borders(player_rect)
player_movement(key_pressed, player_rect)
screen_f(player_rect, enemy_rect)
pygame.display.update()
if __name__ == "__main__":
main()
Before
After 20 seconds
your code is not clearly visible but i think i know how to fix it.
you usually want to set your screen and other important stuf right at the beginning of your file, not in a def that has to be called.
try it like this:
import pygame
pygame.init()
width = ...
height = ...
fps = ...
#set any colors
#load all you pictures
screen = pygame.display.set_mode((width, height))
# you would also want to set your caption and icon here so:
pygame.display.set_caption('your caption')
pygame.display.set_icon(icon)
#all your defs
#and when its all set you go to a main loop.
#(at the bottom of your file)
main()
# and quit for if the user quits and run gets set to False
pygame.quit()
quit()
import pygame
Red = 255, 0, 0
Black= 0,0,0
rectXpos = 2
rectypos = 2
speed = 2
screenedgex = 500
pygame.init()
window = pygame.display.set_mode(size=(500, 500))
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.update()
window.fill(Black)
square = pygame.draw.rect(window, Red, [rectXpos, rectypos, 50, 50],2)
rectXpos += 2
if rectXpos < 500:
rectXpos -= 2
clock.tick(60)
print(rectXpos)`enter code here`
so what am i doing wrong? i tried making a if statment to stop the ball and reverse it but it keeps the ball at the edge of the window
This is complete code, I separated the x and y bounces, so you can use either one, also updated the code a bit more, plus some extra formatting.
# Imports
import pygame
# Vars
Red = 255, 0, 0
Black= 0,0,0
rectXpos = 2
rectYpos = 2
rect_width = 50
rect_height = 50
screen_width = 500
screen_height = 500
block_x_direction = 1
block_y_direction = 1
# Setup Code
pygame.init()
window = pygame.display.set_mode(size=(screen_width, screen_height))
clock = pygame.time.Clock()
running = True
# Game Loop
########################################################
while running:
# Event Loop
########################################################
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Game Code - Update
########################################################
# Game Code - Update - Rect X Bounce
if rectXpos + (rect_width)>= screen_width:
block_x_direction = block_x_direction * -1
rectXpos += 2 * block_x_direction
# Game Code - Update - Rect Y Bounce
if rectYpos + (rect_height)>= screen_height:
block_y_direction = block_y_direction * -1
rectYpos += 2 * block_y_direction
# - Tick Game
clock.tick(60)
# Game Code - Render
########################################################
window.fill(Black)
square = pygame.draw.rect(window, Red, [rectXpos, rectYpos, rect_width, rect_height],2)
pygame.display.update()
# Game Code - Debug Code
########################################################
print(clock.tick)
I assume you want to move rectangle to and fro when mouse is moving.
There are 2 things you are doing wrong here:
1. correct this:
if rectXpos > 500: as you have to decrease X when it will reach 500
2. when reach rectXpos 501 it should change its direction till it reach rectXpos 0
but you have decreased position till it is greater than 500 so it will then stuck in between 499 to 501
correct code:
import pygame
Red = 255, 0, 0
Black= 0,0,0
rectXpos = 2
rectypos = 2
speed = 2
screenedgex = 500
pygame.init()
window = pygame.display.set_mode(size=(500, 500))
clock = pygame.time.Clock()
running = True
k=1 #here is k used to indicate direction
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.update()
window.fill(Black)
square = pygame.draw.rect(window, Red, [rectXpos, rectypos, 50, 50],2)
rectXpos += 2*k #here is addition of 2 in given direction
if (rectXpos > 500) or (rectXpos < 0): #here is condition to change direction
k=-k
clock.tick(60)
print(rectXpos)
You should add speed to position and when you touch border then you should change speed to -speed.
You could also use pygame.Rect() to keep position and size - it has properties .left and .right (and other) which can be very useful. And you can use Rect to draw pygame.draw.rect() (or to check collision with other Rect)
import pygame
# --- constants --- (UPPER_CASE_NAMES)
RED = (255, 0, 0)
BLACK = (0, 0, 0)
WIDTH = 500
HEIGHT = 500
# --- main ---
speed = 10
pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
item = pygame.Rect(0, 0, 50, 50)
clock = pygame.time.Clock()
running = True
while running:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# - updates - (without draws)
item.x += speed
if item.right >= WIDTH:
speed = -speed
if item.left <= 0:
speed = -speed
# - draws - (without updates)
window.fill(BLACK)
pygame.draw.rect(window, RED, item, 2)
pygame.display.update()
clock.tick(60)
# - end -
pygame.quit()
I'm writing code for a one paddle pong game in pygame where the ball will bounce off of the 3 walls the paddle is not on, and when it does hit the paddle's wall instead of the paddle, it makes you lose a life. My problem is that I cannot figure out the collision detection to do this. Here is what I've done so far:
import pygame, sys
from pygame.locals import *
pygame.init()
screen_width = 640
screen_height = 480
Display = pygame.display.set_mode((screen_width, screen_height), 0, 32)
pygame.display.set_caption('Lonely Pong')
back = pygame.Surface((screen_width, screen_height))
background = back.convert()
background.fill((255, 255, 255))
paddle = pygame.Surface((80, 20))
_paddle = paddle.convert()
_paddle.fill((128, 0, 0))
ball = pygame.Surface((15, 15))
circle = pygame.draw.circle(ball, (0, 0, 0), (7, 7), 7)
_ball = ball.convert()
_ball.set_colorkey((0, 0, 0))
_paddle_x = (screen_width / 2) - 40
_paddle_y = screen_height - 20
_paddlemove = 0
_ball_x, _ball_y = 8, 8
speed_x, speed_y, speed_circle = 250, 250, 250
Lives = 5
clock = pygame.time.Clock()
font = pygame.font.SysFont("verdana", 20)
paddle_spd = 5
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
if event.type == KEYDOWN:
if event.key == K_RIGHT:
_paddlemove = paddle_spd
elif event.key == K_LEFT:
_paddlemove = -paddle_spd
elif event.type == KEYUP:
if event.key == K_RIGHT:
_paddlemove = 0
elif event.key == K_LEFT:
_paddlemove = 0
Livespr = font.render(str(Lives), True, (0, 0, 0))
Display.blit(background, (0, 0))
Display.blit(_paddle, (_paddle_x, _paddle_y))
Display.blit(_ball, (_ball_x, _ball_y))
Display.blit(Livespr, ((screen_width / 2), 5))
_paddle_x += _paddlemove
passed = clock.tick(30)
sec = passed / 1000
_ball_x += speed_x * sec
_ball_y += speed_y * sec
pygame.display.update()
Another problem I've been having is that when I start it up, the ball doesn't appear at all. Could somebody please point me in the right direction?
first things first, the ball doesn't appear because you are not filling the surface, you are setting the color_key:
_ball.set_colorkey((0, 0, 0))
should be
_ball.fill((0, 0, 0))
Second, for collision detection, pygame offers some functions such as collidepoint and colliderect.
https://www.pygame.org/docs/ref/rect.html#pygame.Rect.collidepoint
which means you will need the rectangles of the surfaces. do this by:
my_surface.get_rect()
https://www.pygame.org/docs/ref/surface.html#pygame.Surface.get_rect
In order to collide with the edges of the screen, you can always do
if _ball_x <= 0 or _ball_y <= 0 or _ball_x >= 640 or _ball_y >= 480:
# collision detected
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)