how to remove square after 2 seconds - python

I have this code and I don't know how to make the red cube disappear after 2 seconds.
import pygame
import sys
from pygame.locals import *
pygame.init()
a=0
#display
prozor = pygame.display.set_mode((800,800))
FPS = pygame.time.Clock()
FPS.tick(60)
#boje
green=pygame.Color(0 ,255 , 0)
red=pygame.Color(255, 0, 0)
yellow=pygame.Color(255, 255, 0)
blue=pygame.Color(0, 0, 255)
black=pygame.Color(0, 0, 0)
white=pygame.Color(255, 255, 255)
#class
class Cube:
def update(self):
self.cx, self.cy = pygame.mouse.get_pos()
self.square = pygame.Rect(self.cx, self.cy, 50, 50)
def draw(self):
pygame.draw.rect(prozor, (255, 0, 0), self.square)
cube = Cube()
drawing_cube = False
#objekt
for j in range(16):
for i in range(800):
if i%50 == 0:
pygame.draw.rect(prozor, green, ((0+i, a), (50, 50),),1)
a=a+50
#gameloop
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit
if event.type == pygame.MOUSEBUTTONDOWN:
cube.update()
drawing_cube = True
if drawing_cube:
cube.draw()
pygame.display.flip()
pygame.display.update()
Adding it to the draw class will just freeze the game and shut it.
def draw(self):
pygame.draw.rect(prozor, red, self.square)
time.sleep(3)
pygame.draw.rect(prozor, black, self.square
I tried making another class called delete which would delete the cube after 3 seconds using the time module.
def delete(self):
time.sleep(3)
pygame.draw.rect(prozor, black, self.square)
and added it here
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit
if event.type == pygame.MOUSEBUTTONDOWN:
cube.update()
drawing_cube = True
if drawing_cube:
cube.draw()
pygame.display.flip()
**cube.delete**
pygame.display.flip()
pygame.display.update()
but the cube is not disappearing.

Use pygame.time.get_ticks to measure the time in milliseconds. Calculate the time when the cube must disappear again and hide the cube if the current time is greater than the calculated time. You also need to clear the display (prozor.fill(0)) and redraw the scene in each frame:
drawing_cube = False
hide_cube_time = 0
clock = pygame.time.Clock()
run = True
while run:
clock.tick(100)
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
cube.update()
drawing_cube = True
hide_cube_time = current_time + 2000 # 2000 milliseconds == 2 sconds
if current_time > hide_cube_time:
drawing_cube = False
prozor.fill(0)
a=0
for j in range(16):
for i in range(800):
if i%50 == 0:
pygame.draw.rect(prozor, green, (0+i, a, 50, 50), 1)
a=a+50
if drawing_cube:
cube.draw()
pygame.display.update()
pygame.quit()
sys.exit()
Note, the typical PyGame application loop has to:
limit the frames per second to limit CPU usage with pygame.time.Clock.tick
handle the events by calling either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by calling either pygame.display.update() or pygame.display.flip()

Related

Keep text on screen after clicking [duplicate]

I'm currently making a Python clicking game using Pygame. Right now, there is a coin in the center of the screen that you can click. What I want to add now, it a little green "+$10" icon that appears somewhere next to the coin whenever someone clicks it. This is what I want the game to look like whenever someone clicks the coin:
Here is the code of my coin functions:
def button_collide_mouse(element_x, element_y, x_to_remove, y_to_remove):
mouse_x, mouse_y = pygame.mouse.get_pos()
if mouse_x > element_x > mouse_x - x_to_remove and \
mouse_y > element_y > mouse_y - y_to_remove:
return True
def check_events(coin, settings):
for event in pygame.event.get():
# Change button color if mouse is touching it
if button_collide_mouse(coin.image_x, coin.image_y, 125, 125):
coin.image = pygame.image.load('pyfiles/images/click_button.png')
if event.type == pygame.MOUSEBUTTONUP:
settings.money += settings.income
else:
coin.image = pygame.image.load('pyfiles/images/click_button_grey.png')
Using my current code, how can I add that kind of effect?
See How to make image stay on screen in pygame?.
Use pygame.time.get_ticks() to return the number of milliseconds since pygame.init() was called. When the coin is clicked, calculate the point in time after that the text image has to be removed. Add random coordinates and the time to the head of a list:
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
# [...]
if event.type == pygame.MOUSEBUTTONDOWN:
if coin_rect.collidepoint(event.pos):
pos = ... # random position
end_time = current_time + 1000 # 1000 milliseconds == 1 scond
text_pos_and_time.insert(0, (pos, end_time))
Draw the text(s) in the main application loop. Remove the text when the time has expired from the tail of the list:
for i in range(len(text_pos_and_time)):
pos, text_end_time = text_pos_and_time[i]
if text_end_time > current_time:
window.blit(text, text.get_rect(center = pos))
else:
del text_pos_and_time[i:]
break
Minimal example:
import pygame
import random
pygame.init()
window = pygame.display.set_mode((400, 400))
font = pygame.font.SysFont(None, 40)
clock = pygame.time.Clock()
coin = pygame.Surface((160, 160), pygame.SRCALPHA)
pygame.draw.circle(coin, (255, 255, 0), (80, 80), 80, 10)
pygame.draw.circle(coin, (128, 128, 0), (80, 80), 75)
cointext = pygame.font.SysFont(None, 80).render("10", True, (255, 255, 0))
coin.blit(cointext, cointext.get_rect(center = coin.get_rect().center))
coin_rect = coin.get_rect(center = window.get_rect().center)
text = font.render("+10", True, (0, 255, 0))
text_pos_and_time = []
run = True
while run:
clock.tick(60)
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
if coin_rect.collidepoint(event.pos):
pos = pygame.math.Vector2(coin_rect.center) + pygame.math.Vector2(105, 0).rotate(random.randrange(360))
text_pos_and_time.insert(0, ((round(pos.x), round(pos.y)), current_time + 1000))
window.fill(0)
window.blit(coin, coin_rect)
for i in range(len(text_pos_and_time)):
pos, text_end_time = text_pos_and_time[i]
if text_end_time > current_time:
window.blit(text, text.get_rect(center = pos))
else:
del text_pos_and_time[i:]
break
pygame.display.flip()
pygame.quit()
exit()

Trying to delay a specific function for spawning enemy after a certain amount of time

I am making a mole shooter game using pygame. I want my mole to spawn at a random position after every 1 second. I have tried using time.sleep(1.0) but that delays my whole code and thus the game doesn't function properly because of delayed responses. I am moving an aim using the mouse(which also gets affected because of time.sleep) to which i will be adding a click to shoot. I need help with delaying and spawning my mole. I would also like some opinions on how to organize my code to provide various levels of difficulty and a main menu later on.
import pygame
import random
import time
from threading import Timer
pygame.font.init()
win_width = 1000
win_height = 710
FPS = 60
screen = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("Mole Shooter")
white = (255,255,255)
red = (255, 0, 0)
counter, text = 30, 'Time Left: 30'.rjust(3)
pygame.time.set_timer(pygame.USEREVENT, 1000)
font = pygame.font.Font('freesansbold.ttf', 32)
run = True
clock = pygame.time.Clock()
background = pygame.transform.scale(pygame.image.load('back_land.png'), (win_width, win_height))
aim = pygame.image.load("aim.png")
mole = pygame.image.load("mole.png")
def mole_spawn_easy():
molex = random.randint(50, 950)
moley = random.randint(450, 682)
screen.blit(mole, (molex, moley))
while run:
screen.blit(background, [0,0])
ax, ay = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.USEREVENT:
counter -= 1
text = ("Time Left: " + str(counter)).rjust(3)
if counter > 0:
time.sleep(1.0);mole_spawn_easy()
else:
print("game over")
break
screen.blit(aim, ((ax - 32 ),(ay - 32)))
screen.blit(font.render(text, True, (0, 0, 0)), (32, 48))
clock.tick(FPS)
pygame.display.flip()
In pygame exists a timer event. Use pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue.. The time has to be set in milliseconds:
pygame.time.set_timer(pygame.USEREVENT, 1000) # 1 second
Note, in pygame customer events can be defined. Each event needs a unique id. The ids for the user events have to be between pygame.USEREVENT (24) and pygame.NUMEVENTS (32). In this case the value of pygame.USEREVENT is the event id for the timer event.
Receive the event in the event loop:
running = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.USEREVENT:
# [...]
The timer event can be stopped by passing 0 to the time argument of pygame.time.set_timer.
See also Spawning multiple instances of the same object concurrently in python.
Create a list of moles and add a random position to the list in mole_spawn_easy:
moles = []
def mole_spawn_easy():
molex = random.randint(50, 950)
moley = random.randint(450, 682)
moles.append((molex, moley))
Draw the moles in the main application loop:
while run:
# [...]
for pos in moles:
screen.blit(mole, pos)
See the example:
moles = []
def mole_spawn_easy():
molex = random.randint(50, 950)
moley = random.randint(450, 682)
moles.append((molex, moley))
pygame.time.set_timer(pygame.USEREVENT, 1000)
while run:
ax, ay = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.USEREVENT:
counter -= 1
text = ("Time Left: " + str(counter)).rjust(3)
if counter > 0:
mole_spawn_easy()
else:
print("game over")
screen.blit(background, [0,0])
for pos in moles:
screen.blit(mole, pos)
screen.blit(aim, ((ax - 32 ),(ay - 32)))
screen.blit(font.render(text, True, (0, 0, 0)), (32, 48))
pygame.display.flip()
clock.tick(FPS)

How to draw a continuous line in Pygame?

I want to draw a line when mouse clicked and moving in Pygame framework, it will be a line if I move the mouse very slowly. However, if I move the mouse quickly, it's just incontinuous dots. The question is how to draw a continuous line when mouse move? Thanks in advance.
import pygame, sys
from pygame.locals import *
def main():
pygame.init()
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
mouse_position = (0, 0)
drawing = False
screen = pygame.display.set_mode((600, 800), 0, 32)
screen.fill(WHITE)
pygame.display.set_caption("ScratchBoard")
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
if (drawing):
mouse_position = pygame.mouse.get_pos()
pygame.draw.line(screen, BLACK, mouse_position, mouse_position, 1)
elif event.type == MOUSEBUTTONUP:
mouse_position = (0, 0)
drawing = False
elif event.type == MOUSEBUTTONDOWN:
drawing = True
pygame.display.update()
if __name__ == "__main__":
main()
By calling pygame.draw.line with the same argument (mouse_position) twice, you're not drawing a line, you're drawing a single pixel, because start_pos and end_pos are the same.
To get a contiguous line, you need to save the last position and draw a line between it and the next position, like this (changes are the lines with last_pos):
import pygame, sys
from pygame.locals import *
def main():
pygame.init()
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
mouse_position = (0, 0)
drawing = False
screen = pygame.display.set_mode((600, 800), 0, 32)
screen.fill(WHITE)
pygame.display.set_caption("ScratchBoard")
last_pos = None
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
if (drawing):
mouse_position = pygame.mouse.get_pos()
if last_pos is not None:
pygame.draw.line(screen, BLACK, last_pos, mouse_position, 1)
last_pos = mouse_position
elif event.type == MOUSEBUTTONUP:
mouse_position = (0, 0)
drawing = False
elif event.type == MOUSEBUTTONDOWN:
drawing = True
pygame.display.update()
if __name__ == "__main__":
main()
vgel is right, you need to pass the previous position and the current position to pygame.draw.line. You can also calculate the previous position by subtracting the event.rel attribute of the event from the event.pos attribute.
It's also possible get rid of the drawing variable by using the event.buttons attribute. If event.buttons[0] is True then the left mouse button is being pressed.
import pygame
def main():
pygame.init()
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
screen = pygame.display.set_mode((600, 800), 0, 32)
screen.fill(WHITE)
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
elif event.type == pygame.MOUSEMOTION:
if event.buttons[0]: # Left mouse button down.
last = (event.pos[0]-event.rel[0], event.pos[1]-event.rel[1])
pygame.draw.line(screen, BLACK, last, event.pos, 1)
pygame.display.update()
clock.tick(30) # Limit the frame rate to 30 FPS.
if __name__ == "__main__":
main()

How do I check to see if a mouse click is within a circle in pygame?

import pygame
pygame.init()
white = 255,255,255
cyan = 0,255,255
gameDisplay = pygame.display.set_mode((800,600))
pygame.display.set_caption('Circle Click Test')
stop = False
while not stop:
gameDisplay.fill(white)
pygame.draw.circle(gameDisplay,cyan,(400,300),(100))
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
####################################################
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
Here I have a circle on the screen, and I would like to check to see if the user
clicked within the circle. I know how to do this with a rectangle, I would assume it would be similar. Thanks for any help, I am quite new to pygame.
here is what I have for rectangles:
import pygame
pygame.init()
white = 255,255,255
cyan = 0,255,255
gameDisplay = pygame.display.set_mode((800,600))
pygame.display.set_caption('Circle Click Test')
rectangle = pygame.Rect(400,300,200,200)
stop = False
while not stop:
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, cyan,rectangle,4)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
click = rectangle.collidepoint(pygame.mouse.get_pos())
if click == 1:
print 'CLICKED!'
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
Use the distance formula:
################################################################################
# Imports ######################################################################
################################################################################
from pygame.locals import *
import pygame, sys, math
################################################################################
# Screen Setup #################################################################
################################################################################
pygame.init()
scr = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Box Test')
################################################################################
# Game Loop ####################################################################
################################################################################
while True:
pygame.display.update(); scr.fill((200, 200, 255))
pygame.draw.circle(scr, (0, 0, 0), (400, 300), 100)
x = pygame.mouse.get_pos()[0]
y = pygame.mouse.get_pos()[1]
sqx = (x - 400)**2
sqy = (y - 300)**2
if math.sqrt(sqx + sqy) < 100:
print 'inside'
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
################################################################################
################################################################################
################################################################################
you could sample the pixel like this
detect click on shape pygame
otherwise use pythagoras to get the distance from the centre.
As Malik shows, pythagoras works well for circles, but for general solid colour shapes you can do:
if event.type == pygame.MOUSEBUTTONDOWN:
click = gameDisplay.get_at(pygame.mouse.get_pos()) == cyan
if click == 1:
print 'CLICKED!'

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