Pygame: display doesn't update - python

I am having an issue where the display doesn't update for some reason. I have confirmed that x goes up but the display doesn't show it for some reason.
Code:
import pygame
SIZE = (500, 500)
CENTER = (SIZE[0] / 2, SIZE[1] / 2)
FPS = 60
COLORS = {
"white": (255, 255, 255),
"red": (255, 0, 0),
"green": (0, 255, 0),
"blue": (0, 0, 255),
"black": (0, 0, 0)
}
WIN = pygame.display.set_mode(SIZE)
pygame.display.set_caption("what da dog doing?")
def main():
clock = pygame.time.Clock()
run = True
player = pygame.draw.rect(WIN, COLORS.get(
"white"), (CENTER[0] - 400 / 2, CENTER[1] - 70 / 2, 400, 70), border_radius=10)
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
player.x += 1
pygame.display.update()
pygame.quit()
if __name__ == "__main__":
main()
Any help is appreciated.

you need to place stuff that is supposed to be updated in the main loop, also you need to fill the screen with some color (or blit an image that is large enough to cover the area you need) to draw over the previously drawn stuff
def main():
clock = pygame.time.Clock()
run = True
player = pygame.draw.rect(WIN, COLORS.get(
"white"), (CENTER[0] - 400 / 2, CENTER[1] - 70 / 2, 400, 70), border_radius=10)
while run:
clock.tick(FPS)
WIN.fill((0, 0, 0))
pygame.draw.rect(WIN, COLORS.get('white'), player, border_radius=10)
player.x += 1
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.update()
pygame.quit()

Related

How to draw circle count down in pygame? [duplicate]

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()

Pyinstaller pygame window closes with no error message [duplicate]

This question already has answers here:
PyInstaller, spec file, ImportError: No module named 'blah'
(3 answers)
Pyinstaller Unable to access Data Folder
(1 answer)
Python - pygame error when executing exe file
(3 answers)
Closed 2 years ago.
I have been at this for about 2 hours now and I am getting quite frustrated, I have created a pygame file which doesn't use any external fonts or images (which i know is the main issue on why the game screen usually crashes) however I run mine and in the console I get the usual Hello from pygame community and then my game window pops up for roughly a second ad then disappears again with no error messages in the console.
I even installed OBS just to check if the error message was popping up too fast for me to see however there is no error message in sight. I also tried turning on Debug in the .spec file however everything seemed normal (To be fair this is my first time converting a .py to a .exe so i dont really know what I am looking for when it comes to the debug)
I also tried using cx_freeze but I just kept getting this error when building
"TypeError: expected str, bytes or os.PathLike object, not NoneType" and all the fixes I could find were for Pyinstaller not cx_freeze, ideally i would prefer to use cx_freeze but I cant even build an exe with that at least with pyinstaller I have an exe to show (even if it is broken)
This is my command window when I run the exe just before it crashes, nothing more is printed after this
My code is as follows :
import random
import pygame
#import matplotlib.pyplot as plt
from pygame.locals import *
import time
import numpy as np
import sys
import os
pygame.init()
# Window details
windowWidth = 1000
windowHeight = 600
pixSize = 2
FPS = 60
numberofcells = 100
screen = pygame.display.set_mode((windowWidth, windowHeight))
pygame.display.set_caption("Infection Game")
class Cell:
def __init__(self):
self.xPos = random.randrange(1, windowWidth)
self.yPos = random.randrange(1, windowHeight)
self.speed = 2
self.isInfected = False
self.infectionRange = 5
self.move = [None, None]
self.direction = None
def cellDraw(self):
if not self.isInfected:
pygame.draw.rect(screen, (255, 255, 255), (self.xPos, self.yPos, pixSize, pixSize), 0)
else:
pygame.draw.rect(screen, (0, 255, 0), (self.xPos, self.yPos, pixSize, pixSize), 0)
def cellMovement(self):
directions = {"S": ((-1, 2), (1, self.speed)), "SW": ((-self.speed, -1), (1, self.speed)),
"W": ((-self.speed, -1), (-1, 2)), "NW": ((-self.speed, -1), (-self.speed, -1)),
"N": ((-1, 2), (-self.speed, -1)), "NE": ((1, self.speed), (-self.speed, -1)),
"E": ((1, self.speed), (-1, 2)),
"SE": ((1, self.speed), (1, self.speed))} # ((min x, max x)(min y, max y))
directionsName = ("S", "SW", "W", "NW", "N", "NE", "E", "SE") # possible directions
if random.randrange(0, 5) == 2: # move about once every 5 frames
if self.direction is None: # if no direction is set, set a random one
self.direction = random.choice(directionsName)
else:
a = directionsName.index(self.direction) # get the index of direction in directions list
b = random.randrange(a - 1,
a + 2) # set the direction to be the same, or one next to the current direction
if b > len(directionsName) - 1: # if direction index is outside the list, move back to the start
b = 0
self.direction = directionsName[b]
self.move[0] = random.randrange(directions[self.direction][0][0], directions[self.direction][0][1]) + 0.35
self.move[1] = random.randrange(directions[self.direction][1][0], directions[self.direction][1][1]) + 0.35
if self.xPos < 5 or self.xPos > windowWidth - 5 or self.yPos < 5 or self.yPos > windowHeight - 5: # if cell is near the border of the screen, change direction
if self.xPos < 5:
self.direction = "E"
elif self.xPos > windowWidth - 5:
self.direction = "W"
elif self.yPos < 5:
self.direction = "S"
elif self.yPos > windowHeight - 5:
self.direction = "N"
self.move[0] = random.randrange(directions[self.direction][0][0], directions[self.direction][0][1]) + 0.35
self.move[1] = random.randrange(directions[self.direction][1][0], directions[self.direction][1][1]) + 0.35
if self.move[0] is not None: # add the relative coordinates to the cells coordinates
self.xPos += self.move[0]
self.yPos += self.move[1]
def Infect(self, uninfected, uninfected_array):
indices = np.greater(uninfected_array[:, 0], self.xPos - self.infectionRange) * \
np.greater(self.xPos + self.infectionRange, uninfected_array[:, 0]) * \
np.greater(uninfected_array[:, 1], self.yPos - self.infectionRange) * \
np.greater(self.yPos + self.infectionRange, uninfected_array[:, 1])
for i in np.where(indices)[0]:
uninfected[i].isInfected = True
font = pygame.font.SysFont(None, 20)
def drawText(text, font ,colour, surface, x, y):
textobj = font.render(text, 1 , colour)
textrect = textobj.get_rect()
textrect.topleft = (x,y)
surface.blit(textobj,textrect)
def main_menu(numberofcells):
while True:
screen.fill((0,0,0))
drawText('main menu', font, (255, 255, 255), screen, 20, 20)
mx, my = pygame.mouse.get_pos()
button_1 = pygame.Rect(50, 100, 200, 50)
button_2 = pygame.Rect(50, 200, 200, 50)
if button_1.collidepoint((mx, my)):
if click:
gameLoop(numberofcells)
if button_2.collidepoint((mx, my)):
if click:
numberofcells = options(numberofcells)
pygame.draw.rect(screen, (255, 0, 0), button_1)
drawText('start sim', font, (0,0,0), screen, 127, 120)
pygame.draw.rect(screen, (255, 0, 0), button_2)
drawText('options', font, (0,0,0), screen, 130, 220)
click = False
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
click = True
pygame.display.update()
pygame.time.Clock().tick(FPS)
def options(numberofcells):
running = True
while running:
screen.fill((0,0,0))
drawText('options - press ESC to return to menu', font, (255, 255, 255), screen, 20, 20)
mx, my = pygame.mouse.get_pos()
button_1 = pygame.Rect(50, 300, 200, 50)
button_2 = pygame.Rect(50, 400, 200, 50)
pygame.draw.rect(screen, (255, 0, 0), button_1)
drawText('100 cells', font, (0,0,0), screen, 127, 320)
pygame.draw.rect(screen, (255, 0, 0), button_2)
drawText('1000 cells', font, (0,0,0), screen, 127, 420)
if button_1.collidepoint((mx, my)):
if optclick:
numberofcells = 100
pygame.draw.rect(screen, (139, 0, 0), button_1)
if button_2.collidepoint((mx, my)):
if optclick:
numberofcells = 1000
pygame.draw.rect(screen, (139, 0, 0), button_2)
optclick = False
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
optclick = True
pygame.display.update()
pygame.time.Clock().tick(FPS)
return(numberofcells)
def gameLoop(numberofcells):
startTime = time.time()
xgraph = []
ygraph = []
cellList = []
for i in range(numberofcells):
cell = Cell()
cellList.append(cell)
cellList[0].isInfected = True
running = True
while running:
infectList = []
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
screen.fill((0, 0, 0))
for i in cellList:
i.cellDraw()
i.cellMovement()
infected = 0
uninfected = [i for i in cellList if not i.isInfected]
uninfected_array = np.array([[i.xPos, i.yPos] for i in uninfected])
if len(uninfected) > 0:
for i in cellList:
if i.isInfected:
i.Infect(uninfected, uninfected_array)
infected += 1
if infected == 0:
infected = len(cellList) - len(uninfected)
xgraph.append(time.time() - startTime)
ygraph.append(infected)
pygame.display.update() # update display
pygame.time.Clock().tick(FPS) # limit FPS
# figured this is what you wanted to do ;)
#plt.plot(xgraph, ygraph)
#plt.xlabel('time (s)')
#plt.ylabel('infected')
#plt.show()
main_menu(numberofcells)

I want to blit an image on key press in pygame

I am trying to create a Tic tac toe game in pygame. I want to display an image on screen when a key is pressed. Pressing the escape key allows me to quit game however when I press key 1 to blit the image nothing happens. Here is the code
import pygame
from pygame.locals import (
K_1,
K_2,
K_3,
K_4,
K_5,
K_6,
K_7,
K_8,
K_9,
K_ESCAPE,
K_UP,
KEYDOWN,
QUIT
)
clock = pygame.time.Clock()
pygame.init()
# Constants
display_width = 300
display_height = 300
white = (255, 255, 255)
black = (0, 0, 0)
run = True
# Creating game screen
display = pygame.display.set_mode((300, 300))
pygame.display.set_caption("Tic Tac Toe Game")
display.fill(white)
# importing images to pygame
circle_image = pygame.image.load("resizedimage1.png")
cross_image = pygame.image.load("resizedimage2.png")
# main game loop
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
run = False
elif event.key == K_1:
display.blit(cross_image, (10, 10))
clock.tick(30)
display.fill(white)
pygame.draw.line(display, black, (100, 0), (100, 300))
pygame.draw.line(display, black, (200, 0), (200, 300))
pygame.draw.line(display, black, (0, 100), (300, 100))
pygame.draw.line(display, black, (0, 200), (300, 200))
pygame.display.update()
pygame.quit()
You have to put the line
display.fill(white)
at the top of your while run. Because now you are rendering the picture and in the next frame you paint everything white. So you are not able to see the image.
You also should use the event KEYUP. Because KEYDOWN will be fired multiple times, so it will lead to flickering effects.
Of course you have to draw an blit all the objects after display.fill(), because pygame.Surface.fill fill the Surface with a solid color.
Anyway, I recommend to create a list of images for the nine fields of the game. Init the list by None:
field = [None] * 9
Set the corresponding filed in the list if a button is pressed. Note list indices start at 0:
elif event.key == K_1:
field[0] = cross_image
Draw the fields of the list in a loop. Use enumerate() to iterate through the list. The row of a field can be computed by the // (floor division) operator and the column by the % (modulo) operator (see Binary arithmetic operations):
for i, img in enumerate(field):
if img:
column = i % 3
row = i // 3
display.blit(img, (column * 100 + 10, row * 100 + 10))
Example code:
import pygame
from pygame.locals import (
K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9,
K_ESCAPE, K_UP, KEYDOWN,
QUIT
)
clock = pygame.time.Clock()
pygame.init()
# Constants
display_width = 300
display_height = 300
white = (255, 255, 255)
black = (0, 0, 0)
run = True
# Creating game screen
display = pygame.display.set_mode((300, 300))
pygame.display.set_caption("Tic Tac Toe Game")
display.fill(white)
# importing images to pygame
circle_image = pygame.image.load("resizedimage1.png")
cross_image = pygame.image.load("resizedimage2.png")
field = [None] * 9
# main game loop
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
run = False
elif event.key == K_1:
field[0] = cross_image
display.fill(white)
pygame.draw.line(display, black, (100, 0), (100, 300))
pygame.draw.line(display, black, (200, 0), (200, 300))
pygame.draw.line(display, black, (0, 100), (300, 100))
pygame.draw.line(display, black, (0, 200), (300, 200))
for i, img in enumerate(field):
if img:
column = i % 3
row = i // 3
display.blit(img, (column * 100 + 10, row * 100 + 10))
pygame.display.update()
pygame.quit()

How to create a pause button in Pygame?

I've been trying to make a game, and everything in there works so far except that the pause button , that when pressed the button P should pause and when pressed S should continue. I kinda understand the problem such that once in enters the while loop in the main code it wont get out. I tried putting the pause function inside the while loop. Please do help or provide tips to fix if possible thank you.
import pygame
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
Blue = (2,55,55)
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 paused():
screen.fill(black)
largeText = pygame.font.SysFont("comicsansms",115)
TextSurf, TextRect = text_objects("Paused", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
#gameDisplay.fill(white)
button("Continue",150,450,100,50,green,bright_green,unpause)
button("Quit",550,450,100,50,red,bright_red,quitgame)
pygame.display.update()
clock.tick(15)
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()
black=(0,0,0)
end_it=False
time = 100
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
pause = 0
b = 0
# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get():
if event.type == pygame.KEYUP:
if event.key==K_p:
pause=True
if pause == True:
screen.fill(black)
font=pygame.font.SysFont("Britannic Bold", 40)
nlabelBB=myfont.render("Pause", 1, (255, 0, 0))
screen.blit(nlabelBB,(200, 100))
pygame.display.flip()
# Set the screen background
screen.fill(BLACK)
flip = 1
a = 0
# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
recursive_draw(0, 0, 700, 500)
recursive_draw2(35,25, 625, 450)
**###I TRIED TO PUT THE PAUSE GAME HERE AND IF PRESSED P PAUSE AND S CONTINUE
while a == 0 :
if flip == 1 :
recursive_draw(35,25,625,450)
recursive_draw2(0, 0, 700, 500)
flip = flip + 1
pygame.display.flip()
if event.type == pygame.KEYUP:
if event.key==K_p:
a = 1
screen.fill(black)
font=pygame.font.SysFont("Britannic Bold", 40)
nlabelBB=myfont.render("Pause", 1, (255, 0, 0))
screen.blit(nlabelBB,(200, 100))
pygame.display.flip()
if event.key==K_s:
a = 0
if flip == 2 :
recursive_draw(0, 0, 700, 500)
recursive_draw2(35, 25, 625, 450)
flip = flip - 1
pygame.display.flip()
if event.type == pygame.KEYUP:
if event.key==K_p:
a = 1
screen.fill(black)
font=pygame.font.SysFont("Britannic Bold", 40)
nlabelBB=myfont.render("Pause", 1, (255, 0, 0))
screen.blit(nlabelBB,(200, 100))
pygame.display.flip()
if event.key==K_s:
a = 0**
if event.type == pygame.QUIT:
done = True
# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Limit to 60 frames per second
clock.tick(20)
# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit()
Just use a single game loop for everything and keep track of the current state (e.g. main menu, pause screen, game scene) of your game..
Here's an example where we keep track of the state by a simple variable called state and act in our game loop accordingly:
import pygame, math, itertools
def magnitude(v):
return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))
def sub(u, v):
return [u[i]-v[i] for i in range(len(u))]
def normalize(v):
return [v[i]/magnitude(v) for i in range(len(v))]
pygame.init()
screen = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
path = itertools.cycle([(26, 43), (105, 110), (45, 225), (145, 295), (266, 211), (178, 134), (250, 56), (147, 12)])
target = next(path)
ball, speed = pygame.rect.Rect(target[0], target[1], 10, 10), 3.6
pause_text = pygame.font.SysFont('Consolas', 32).render('Pause', True, pygame.color.Color('White'))
RUNNING, PAUSE = 0, 1
state = RUNNING
while True:
for e in pygame.event.get():
if e.type == pygame.QUIT: break
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_p: state = PAUSE
if e.key == pygame.K_s: state = RUNNING
else:
screen.fill((0, 0, 0))
if state == RUNNING:
target_vector = sub(target, ball.center)
if magnitude(target_vector) < 2:
target = next(path)
else:
ball.move_ip([c * speed for c in normalize(target_vector)])
pygame.draw.rect(screen, pygame.color.Color('Yellow'), ball)
elif state == PAUSE:
screen.blit(pause_text, (100, 100))
pygame.display.flip()
clock.tick(60)
continue
break
As you can see, the rectangle keeps moving until you press P, which will change the state to PAUSE; and a simple message will now be displayed instead of drawing/moving the rectangle further.
If you press S the state switches back to the normal mode; all done in a single game loop.
Further reading:
Pygame level/menu states
Mulitple Displays in Pygame
Trying to figure out how to track Pygame events and organize the game's functions

my click's counter program wont work

After importing the modules and declaring the variables here is how my code starts:
while True:
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
dibujarCirculo()
cont += 1
contador = texto.render("Clicks: " + str(cont), 1, green)
ventana.blit(contador, CONT_POS)
pygame.display.update()
When i run it i get the screen fill with black, and some text "Clicks :0" and when i click the mouse, instead of turning "Clicks: 1" the 1 stacks over the zero and it becomes a mess.
My intention is simply: when you click somewhere in the window it adds 1 to a click's counter. Also it actually draw a circle but that's not important.
i will post the whole code if you want to give it a look.
import sys
import pygame
from pygame.constants import *
pygame.init()
ventana = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Basics")
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
darkBlue = (0, 0, 128)
white = (255, 255, 255)
black = (0, 0, 0)
pink = (255, 200, 200)
cont = 0
CONT_POS = (50, 100)
texto = pygame.font.SysFont("monospace", 15)
def dibujarCirculo():
pos = pygame.mouse.get_pos()
radius = 10
pygame.draw.circle(ventana, white, pos, radius)
cont = 0
while True:
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
dibujarCirculo()
cont += 1
contador = texto.render("Clicks: " + str(cont), 1, green)
ventana.blit(contador, CONT_POS)
pygame.display.update()
note: it is the second time i am posting these because people is voting down for no reason and also tagging the post as off-topic when i try to explain my problem the best way i know...
You need to clear the screen to avoid drawing on top of the old text
while True:
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
dibujarCirculo()
cont += 1
ventana.fill((0,0,0)) # clear the screen
contador = texto.render("Clicks: " + str(cont), 0, green)
ventana.blit(contador, CONT_POS)
pygame.display.update()
You can add the blit using black in your first function to just overwrite the blit each time.
def dibujarCirculo():
pos = pygame.mouse.get_pos()
radius = 10
pygame.draw.circle(ventana, white, pos, radius)
contador = texto.render("Clicks: " + str(cont), 0, black) # set background to black
ventana.blit(contador, CONT_POS)
while True:
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
dibujarCirculo()
cont += 1
contador = texto.render("Clicks: " + str(cont), 1, green)
ventana.blit(contador, CONT_POS)
pygame.display.update()

Categories