How to make a circular countdown timer in Pygame? - python

How can i make this kind of countdown in Pygame? (i'm looking for how could i make the circle's perimeter decrease, that's the issue, because displaying the time isn't hard )
Keep in mind that how long the perimeter of the circle is and the displayed time should be in proportion with each other.

Just use pygame.draw.arc and specify the stop_angle argument depending on the counter:
percentage = counter/100
end_angle = 2 * math.pi * percentage
pygame.draw.arc(window, (255, 0, 0), arc_rect, 0, end_angle, 10)
Minimal example:
import pygame
import math
pygame.init()
window = pygame.display.set_mode((200, 200))
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 100)
counter = 100
text = font.render(str(counter), True, (0, 128, 0))
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, 1000)
def drawArc(surf, color, center, radius, width, end_angle):
arc_rect = pygame.Rect(0, 0, radius*2, radius*2)
arc_rect.center = center
pygame.draw.arc(surf, color, arc_rect, 0, end_angle, width)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == timer_event:
counter -= 1
text = font.render(str(counter), True, (0, 128, 0))
if counter == 0:
pygame.time.set_timer(timer_event, 0)
window.fill((255, 255, 255))
text_rect = text.get_rect(center = window.get_rect().center)
window.blit(text, text_rect)
drawArc(window, (255, 0, 0), (100, 100), 90, 10, 2*math.pi*counter/100)
pygame.display.flip()
pygame.quit()
exit()
Sadly the quality of pygame.draw.arc with a width > 1 is poor. However this can be improved, using cv2 and cv2.ellipse:
import pygame
import cv2
import numpy
pygame.init()
window = pygame.display.set_mode((200, 200))
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 100)
counter = 100
text = font.render(str(counter), True, (0, 128, 0))
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, 1000)
def drawArcCv2(surf, color, center, radius, width, end_angle):
circle_image = numpy.zeros((radius*2+4, radius*2+4, 4), dtype = numpy.uint8)
circle_image = cv2.ellipse(circle_image, (radius+2, radius+2),
(radius-width//2, radius-width//2), 0, 0, end_angle, (*color, 255), width, lineType=cv2.LINE_AA)
circle_surface = pygame.image.frombuffer(circle_image.flatten(), (radius*2+4, radius*2+4), 'RGBA')
surf.blit(circle_surface, circle_surface.get_rect(center = center))
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == timer_event:
counter -= 1
text = font.render(str(counter), True, (0, 128, 0))
if counter == 0:
pygame.time.set_timer(timer_event, 0)
window.fill((255, 255, 255))
text_rect = text.get_rect(center = window.get_rect().center)
window.blit(text, text_rect)
drawArcCv2(window, (255, 0, 0), (100, 100), 90, 10, 360*counter/100)
pygame.display.flip()
pygame.quit()
exit()

Related

pygame fully transparent surface

I'm trying to make a color picker that changes color over time. I have the logic but the process is really slow, the idea is to have a square that changes color and overlap a PNG grayscale gradient onto it so that the program can be faster. The problem is that I can't seem to download the gradient with the transparency.
import sys, pygame
pygame.init()
#VARIABLES
width = 255
height = 255
background = (255, 0, 0)
foreground = (230, 100, 45)
mySurf = pygame.Surface((255, 255))
mySurf.set_alpha(0)
mySurf.fill((200,0,200))
#SCREEN
screen = pygame.display.set_mode((width, height))
screen.fill((0, 0, 0))
#CODE
for x in range(255):
s = pygame.Surface((1, 255))
s.set_alpha(255-x)
s.fill((255, 255, 255))
mySurf.blit(s, (x, 0))
for y in range(255):
s = pygame.Surface((255, 1))
s.set_alpha(y)
s.fill((0, 0, 0))
mySurf.blit(s, (0, y))
pygame.image.save(mySurf, "gradient.png")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
You have to create a surface with a format that hast an alpha channel per pixel. Use the SRCALPHA flag:
mysurf = pygame.surface((255, 255))
mySurf = pygame.Surface((255, 255), pygame.SRCALPHA)
Note, with the flag each pixel has its own alpha value (RGBA format), without the flag the surfaces hast just 1 global alpha value and can not store different alpha values for the pixels (RGB format)
Complete example:
import sys, pygame
pygame.init()
#VARIABLES
width = 255
height = 255
background = (255, 0, 0)
foreground = (230, 100, 45)
mySurf = pygame.Surface((255, 255))
mySurf.set_alpha(0)
mySurf.fill((200,0,200))
#SCREEN
screen = pygame.display.set_mode((width, height), pygame.SRCALPHA)
#CODE
s = pygame.Surface((1, 255), pygame.SRCALPHA)
for x in range(255):
s.fill((255, 255, 255, 255-x))
mySurf.blit(s, (x, 0))
s = pygame.Surface((255, 1), pygame.SRCALPHA)
for y in range(255):
s.fill((0, 0, 0, y))
mySurf.blit(s, (0, y))
pygame.image.save(mySurf, "gradient.png")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()

Why doesn't pygame continue through the loop?

I am making a game, and when I want to go through the loop normally, it doesn't work.
it goes through the loop, but for some reason, it backtracks, rather than starting over. When I add a continue statement, the button just disappears.
Why isn't the continue statement working properly?
Here is my code:
import pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((400, 300))
pygame.font.init()
done = False
bro = True
x = 100
y = 100
#button1 = pygame.draw.rect(screen, (0, 0, 255), (200, 200, 30, 30))
#if check <= pos - (w/2) and check >=
pygame.display.set_caption("Auto Maze!")
donk = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
mouse = event.pos
try:
assert button1.collidepoint(mouse)
except AssertionError:
pass
except NameError:
pass
else:
donk = True
pressed = pygame.key.get_pressed()
if pressed[pygame.K_w]:
y -= 5
elif pressed[pygame.K_s]:
y += 5
elif pressed[pygame.K_a]:
x -= 5
elif pressed[pygame.K_d]:
x += 5
screen.fill((0, 0, 0))
"""try:
assert player.colliderect(wall1)
except AssertionError:
pass
except NameError:
pass
else:
death_screen = pygame.display.set_mode((400, 300))
button1 = pygame.draw.rect(death_screen, (0, 0, 255), (200, 200, 30, 30))
if donk:
break"""
player = pygame.draw.rect(screen, (0, 255, 0), (x, y, 60, 60))
wall1 = pygame.draw.rect(screen, (255, 0, 0), (300, 0, 100, 300))
if player.colliderect(wall1):
death_screen = pygame.display.set_mode((400, 300))
myfont = pygame.font.SysFont("Comic Sans MS", 10)
button1 = pygame.draw.rect(death_screen, (0, 0, 255), (175, 100, 60, 30))
text = myfont.render("Try Again", False, (255, 0, 0))
screen.blit(text, (175, 100))
if donk:
screen = pygame.display.set_mode((400, 300))
clock.tick(60)
pygame.display.flip()
quit()
Add a gameover to your application:
gameover = False:
Do different things in the application loop, dependent on the state of gameover:
while not done:
# [...]
if not gameover:
# draw game scene
# [...]
else:
# draw gamover scene (button)
# [...]
Set the gameover state if the player collides:
gameover = player.colliderect(wall1)
Reset the position of the player if the continue button is pressed:
if event.type == pygame.MOUSEBUTTONDOWN:
if gameover:
if button1.collidepoint(event.pos):
gameover = False
x, y = 100, 100
See the example:
import pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption("Auto Maze!")
pygame.font.init()
myfont = pygame.font.SysFont("Comic Sans MS", 10)
x, y = 100, 100
gameover = False
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
if gameover:
if button1.collidepoint(event.pos):
gameover = False
x, y = 100, 100
screen.fill((0, 0, 0))
if not gameover:
pressed = pygame.key.get_pressed()
if pressed[pygame.K_w]:
y -= 5
elif pressed[pygame.K_s]:
y += 5
elif pressed[pygame.K_a]:
x -= 5
elif pressed[pygame.K_d]:
x += 5
player = pygame.draw.rect(screen, (0, 255, 0), (x, y, 60, 60))
wall1 = pygame.draw.rect(screen, (255, 0, 0), (300, 0, 100, 300))
gameover = player.colliderect(wall1)
else:
button1 = pygame.draw.rect(screen, (0, 0, 255), (175, 100, 60, 30))
text = myfont.render("Try Again", False, (255, 0, 0))
screen.blit(text, (175, 100))
pygame.display.flip()
clock.tick(60)
quit()
This does the same as your code, but just cleaned up. Hopefully it solves your problem
import pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((400, 300))
pygame.font.init()
done = False
mouse = None
click = False
state = "main"
myfont = pygame.font.SysFont("Comic Sans MS", 10)
player = pygame.Rect(100,100,60,60)
wall1 = pygame.Rect(300, 0, 100, 300)
button1 = pygame.Rect(175, 100, 60, 30)
pygame.display.set_caption("Auto Maze!")
while not done:
click = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
mouse = event.pos
click = True
screen.fill((0, 0, 0))
if state == "main":
pressed = pygame.key.get_pressed()
if pressed[pygame.K_w]:
player.y -= 5
elif pressed[pygame.K_s]:
player.y += 5
elif pressed[pygame.K_a]:
player.x -= 5
elif pressed[pygame.K_d]:
player.x += 5
#draw player and wall
pygame.draw.rect(screen, (0, 255, 0), player)
pygame.draw.rect(screen, (255, 0, 0), wall1)
if player.colliderect(wall1):
state = "death"
else:
pygame.draw.rect(screen, (0, 0, 255), button1)
text = myfont.render("Try Again", False, (255, 0, 0))
screen.blit(text, (175, 100))
if click:
if button1.collidepoint(mouse):
state = "main"
player.x = 100
player.y = 100
clock.tick(60)
pygame.display.flip()
quit()

Pygame - Moving rect between two points

I'm trying to make a rect move between two points in pygame. I've been able to make it move onto another rect and then stop, but then it won't move backwards, like it should.
I'm not sure what I'm doing wrong, so I decided to ask for help. Here's my code:
import pygame
width, height = 800, 600
gameDisplay = pygame.display.set_mode((width, height))
pygame.display.set_caption("Test")
gameExit = False
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
block_size = 10
def gameloop():
lead_x1, lead_x2 = 1, 100
lead_y1, lead_y2 = 1, 1
velocity = 0.2
gameExit = False
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
block_size = 10
while not gameExit:
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, black, [lead_x1, lead_y1, block_size, block_size])
pygame.draw.rect(gameDisplay, black, [lead_x2, lead_y2, block_size, block_size])
lead_x1 += velocity
if lead_x1 >= lead_x2:
lead_x1 += -velocity
if lead_x1 <= 0:
lead_x1 += velocity
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
pygame.display.update()
pygame.quit()
quit()
gameloop()
I think you need to place line lead_x1 += velocity inside the else statement, something like this:-
import pygame
width, height = 800, 600
gameDisplay = pygame.display.set_mode((width, height))
pygame.display.set_caption("Test")
gameExit = False
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
block_size = 10
def gameloop():
lead_x1, lead_x2 = 1, 100
lead_y1, lead_y2 = 1, 1
velocity = 0.2
gameExit = False
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
block_size = 10
toogle_flag = 1
while not gameExit:
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, black, [lead_x1, lead_y1, block_size, block_size])
pygame.draw.rect(gameDisplay, black, [lead_x2, lead_y2, block_size, block_size])
lead_x1 += toggle_flag * velocity
if lead_x1 >= lead_x2:
toggle_flag = -1*toggle_flag
if lead_x1 <= 0:
toggle_flag = -1*toggle_flag
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
pygame.display.update()
pygame.quit()
quit()
gameloop()
So what I am doing here is, let's take take a flag called toggle_flag, initialize it to 1.
Out box is at position 1, we add toggle_flag * velocity to our lead_x1. i.e we are basically adding velocity.
Once we touch the second box, we flip the value of toggle_flag to -1.
What will happen is, we keep on adding -velocity to our lead_x1.
Now, once we reach 0. We again flip the value of toggle_flag by multiplying it by -1, which we get us to add velocity to out lead_x1.
Hope this helps!

Pygame buttons not creating working buttons

I am trying to make a hangman game in pygame, but I cannot get buttons to work after they have been created from an event (in my case after pressing enter), they appear on screen but do not work ( rollover or activate events), please help!
from pygame.locals import *
import pygame, sys, eztext
import time
pygame.init()
Black = ( 0, 0, 0)
Grey = (100, 100, 100)
DarkGrey = (70, 70, 70)
White = (255, 255, 255)
Blue = ( 0, 0, 255)
NavyBlue = ( 60, 60, 100)
Cyan = ( 0, 255, 255)
Purple = (255, 0, 255)
Red = (255, 0, 0)
DarkRed = (180, 0, 0)
Orange = (255, 128, 0)
Yellow = (255, 255, 0)
Green = ( 0, 255, 0)
DarkGreen = ( 0, 180, 0)
LightBlue = ( 90, 164, 213)
Magenta = (153, 0, 76)
screen = pygame.display.set_mode((1000,600),0,32)
screen.fill(Orange)
txtbx = eztext.Input(maxlength=45, color=(0,0,0), prompt='Enter username: ')
def text_objects(text, font):
textSurface = font.render(text, True, Black)
return textSurface, textSurface.get_rect()
smallText = pygame.font.Font("freesansbold.ttf",20)
def button(msg,x,y,w,h,ic,ac,action=None):
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(screen, ac,(x, y, w, h))
if click [0] == 1 and action!= None:
if action == "Quit":
pygame.quit()
if action == "Single player":
pygame.draw.rect(screen, Green,(10, 10, 500, 500))
else:
pygame.draw.rect(screen, ic,(x, y, w, h))
smallText = pygame.font.Font("freesansbold.ttf",20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ((x+(w/2)), (y + (h/2)))
screen.blit(textSurf, textRect)
while True:
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
string1 = txtbx.value
pygame.display.update()
time.sleep(0.02)
pygame.draw.rect(screen, Green,(10, 100, 500, 50))
clock = pygame.time.Clock()
clock.tick(30)
events = pygame.event.get()
txtbx.set_pos(10,110)
label = smallText.render("Enter you user name and then press enter!", 1, (0,0,0))
screen.blit(label, (10, 10))
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_KP_ENTER or event.key == pygame.K_RETURN:
button("Single player",10, 400, 150, 50, Green, DarkGreen,"Single player")
if string1 in open('Users.txt').read():
username = string1
Welcomeold1 = smallText.render('Welcome back', 1, (0,0,0))
screen.blit(Welcomeold1, (10, 200))
Welcomeold2 = smallText.render(username, 1, (0,0,0))
screen.blit(Welcomeold2, (160, 200))
else:
username = string1
f = open('Users.txt','a')
string1 = txtbx.value
f.write(string1)
f.write('\n')
f.close()
Welcomenew1 = smallText.render('Welcome to my game', 1, (0,0,0))
screen.blit(Welcomenew1, (10, 200))
Welcomenew2 = smallText.render(username, 1, (0,0,0))
screen.blit(Welcomenew2, (230, 200))
if event.key == pygame.K_BACKSPACE:
screen.fill(Orange)
txtbx.update(events)
txtbx.draw(screen)
pygame.display.flip()
if __name__ == '__main__': main()
button function is inside event.key so it will work only when RETURN is pressed, released, and pressed again, and released again, etc.
You should create class with method draw and handle_event to use this method in mainloop in different places. You can create button in event.key but you have to check button pressed in different place.
-
Simple button. Full working example.
When you press button function do_it is called and background changed color.
#
# pygame (simple) template - by furas
#
# ---------------------------------------------------------------------
import pygame
import pygame.gfxdraw
import random
# === CONSTANS === (UPPER_CASE names)
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
CYAN = ( 0, 255, 255)
MAGENTA = (255, 0, 255)
YELLOW = (255, 255, 0)
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# === CLASSES === (CamelCase names)
class Button():
def __init__(self, text, x, y, width, height, on_click=None, fg_color=RED, bg_color=WHITE, font_size=35):
self.text = text
font = pygame.font.SysFont(None, font_size)
# rectangle - without position, to put text in correct place
self.rect = pygame.Rect(0, 0, width, height)
# normal button - fill background
self.normal_image = pygame.surface.Surface( self.rect.size )
self.normal_image.fill(bg_color)
# normal button - add text
text_image = font.render(text, True, fg_color)
text_rect = text_image.get_rect(center=self.rect.center)
self.normal_image.blit(text_image, text_rect)
# hover button - fill background
self.hover_image = pygame.surface.Surface( self.rect.size )
self.hover_image.fill(fg_color)
# hover button - add text
text_image = font.render(text, True, bg_color)
text_rect = text_image.get_rect(center=self.rect.center)
self.hover_image.blit(text_image, text_rect)
# set position
self.rect.x = x
self.rect.y = y
# other
self.on_click = on_click
self.hover = False
def draw(self, surface):
# draw normal or hover image
if self.hover:
surface.blit(self.hover_image, self.rect)
else:
surface.blit(self.normal_image, self.rect)
def event_handler(self, event):
# is mouse over button ?
if event.type == pygame.MOUSEMOTION:
self.hover = self.rect.collidepoint(event.pos)
# is mouse clicked ? run function.
if event.type == pygame.MOUSEBUTTONDOWN:
if self.hover and self.on_click:
self.on_click()
# === FUNCTIONS === (lower_case names)
def do_it():
global background_color
if background_color == BLACK:
background_color = RED
elif background_color == RED:
background_color = GREEN
else:
background_color = BLACK
print("Button pressed")
# === MAIN ===
# --- init ---
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen_rect = screen.get_rect()
# --- objects ---
# create button
button = Button('CHANGE COLOR', 0, 0, 300, 50, on_click=do_it)
# add function later
#button_quit.on_click = do_it
# center button
button.rect.center = screen_rect.center
# default bacground color - changed in do_it()
background_color = BLACK
# --- mainloop ---
clock = pygame.time.Clock()
is_running = True
while is_running:
# --- events ---
for event in pygame.event.get():
# --- global events ---
if event.type == pygame.QUIT:
is_running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
is_running = False
# --- objects events ---
button.event_handler(event)
# --- updates ---
# empty
# --- draws ---
# clear buffer
screen.fill(background_color)
# draw all objects - widgets (buttons, labels)
button.draw(screen)
clock.tick(25)
# send buffer to video card
pygame.display.update()
# --- the end ---
pygame.quit()

Why does the game lag when I load an image and when I display pygame shapes?

Just out of curiosity, why does a game lag when I load an image as well as display pygame shapes for example rectangles, circles and ellipses. I have this code where you shoot the ghosts that fall down (I'm still working on the shooting part). I made the cannon out of pygame shapes. But when I run it the images of the ghosts are prefect but the images of the cannons lag and disappears and reappear and so on. Is there any way to stop this lag or disappear and reappear thing? I'm running python 2.6 with windows vista.
import pygame, sys, random, math
from pygame.locals import *
WINDOWHEIGHT = 600
WINDOWWIDTH = 600
FPS = 30
BACKGROUNDCOLOR = (255, 255, 255)
TEXTCOLOR = (0, 0, 0)
WHITE = (255, 255, 255)
BLACK = ( 0, 0, 0)
BROWN = (139, 69, 19)
DARKGRAY = (128, 128, 128)
BGCOLOR = WHITE
GHOSTSPEED = 10
GHOSTSIZE = 20
ADDNEWGHOSTRATE = 8
def keyToPlayAgain():
while True:
for event in event.type.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
return
def getAngle(x1, y1, x2, y2):
# Return value is 0 for right, 90 for up, 180 for left, and 270 for down (and all values between 0 and 360)
rise = y1 - y2
run = x1 - x2
angle = math.atan2(run, rise) # get the angle in radians
angle = angle * (180 / math.pi) # convert to degrees
angle = (angle + 90) % 360 # adjust for a right-facing sprite
return angle
def Text(text, font, surface, x, y):
textobj = font.render(text, 2, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
pygame.init()
mainClock = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWHEIGHT, WINDOWWIDTH))
pygame.display.set_icon(pygame.image.load('s.icon'))
pygame.display.set_caption('Ghost Invasion Pacfighters')
pygame.mouse.set_visible(False)
font = pygame.font.SysFont(None, 48)
gameOverSound = pygame.mixer.Sound('gameover.wav')
pygame.mixer.music.load('background.mid')
ghostImage = pygame.image.load('ghosts.png')
dotImage = pygame.image.load('dot.png')
dotRect = dotImage.get_rect()
creditsPage = pygame.image.load('credits.png')
titlePage = pygame.image.load('title.png')
pygame.time.wait(10000)
DISPLAYSURF.blit(creditsPage, (0, 0))
pygame.time.wait(10000)
DISPLAYSURF.blit(titlePage, (0, 0))
pygame.display.update()
cannonSurf = pygame.Surface((100, 100))
cannonSurf.fill(BGCOLOR)
pygame.draw.circle(cannonSurf, DARKGRAY, (20, 50), 20)
pygame.draw.circle(cannonSurf, DARKGRAY, (80, 50), 20)
pygame.draw.rect(cannonSurf, DARKGRAY, (20, 30, 60, 40))
pygame.draw.circle(cannonSurf, BLACK, (80, 50), 15)
pygame.draw.circle(cannonSurf, BLACK, (80, 50), 20, 1)
pygame.draw.circle(cannonSurf, BROWN, (30, 70), 20)
pygame.draw.circle(cannonSurf, BLACK, (30, 70), 20, 1)
health = 100
score = 0
topScore = 0
while True:
ghosts = []
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
ghostAddCounter = 0
pygame.mixer.music.play(-1, 0.0)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_x:
bombs()
elif event.type == ESCAPE:
pygame.quit()
sys.exit()
mousex, mousey = pygame.mouse.get_pos()
for cannonx, cannony in ((100, 500), (500, 500)):
degrees = getAngle(cannonx, cannony, mousex, mousey)
rotatedSurf = pygame.transform.rotate(cannonSurf, degrees)
rotatedRect = rotatedSurf.get_rect()
rotatedRect.center = (cannonx, cannony)
DISPLAYSURF.blit(rotatedSurf, rotatedRect)
pygame.draw.line(DISPLAYSURF, BLACK, (mousex - 10, mousey), (mousex + 10, mousey))
pygame.draw.line(DISPLAYSURF, BLACK, (mousex, mousey - 10), (mousex, mousey + 10))
pygame.draw.rect(DISPLAYSURF, BLACK, (0, 0, WINDOWWIDTH, WINDOWHEIGHT), 1)
pygame.display.update()
if not reverseCheat and not slowCheat:
ghostAddCounter += 1
if ghostAddCounter == ADDNEWGHOSTRATE:
ghostAddCounter = 0
newGhost = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-GHOSTSIZE), 0 - GHOSTSIZE, GHOSTSIZE, GHOSTSIZE),
'speed': (GHOSTSIZE),
'surface':pygame.transform.scale(ghostImage, (GHOSTSIZE, GHOSTSIZE)),
}
ghosts.append(newGhost)
for s in ghosts:
if not reverseCheat and not slowCheat:
s['rect'].move_ip(0, s['speed'])
elif reverseCheat:
s['rect'].move_ip(0, -5)
elif slowCheat:
s['rect'].move_ip(0, -1)
for s in ghosts[:]:
if s['rect'].top > WINDOWHEIGHT:
health -= 10
DISPLAYSURF.fill(BACKGROUNDCOLOR)
Text('Score: %s' % (score), font, DISPLAYSURF, 10, 0)
Text('Top score: %s' % (topScore), font, DISPLAYSURF, 10, 40)
Text('Health: %s' % (health), font, DISPLAYSURF, 10, 560)
for s in ghosts:
DISPLAYSURF.blit(s['surface'], s['rect'])
pygame.display.update()
mainClock.tick(FPS)
pygame.mixer.music.stop()
gameOverSound.play()
Text('GAME OVER', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
pygame.display.update()
keyToPlayAgain()
pygame.display.update()
gameOverSound.stop()
The problem is that you draw your cannons, update the display, then clear the display, draw the other stuff, and update the display again. You basically never see the falling ghosts and the cannons at the same time. This results in the flickering you see.
So remove pygame.display.update() from this for loop
for cannonx, cannony in ((100, 500), (500, 500)):
...
pygame.display.update()
and put DISPLAYSURF.fill(BACKGROUNDCOLOR) at the top of your while loop (or at least before you draw anything):
while True:
for event in pygame.event.get():
...
mousex, mousey = pygame.mouse.get_pos()
DISPLAYSURF.fill(BACKGROUNDCOLOR)
for cannonx, cannony in ((100, 500), (500, 500)):
...
It's best to clear the background once at the start of your code that draws everything, and call pygame.display.update() once at the end of that drawing code.

Categories

Resources