I have code that draws a line from 2 points; One on the middle bottom of the screen, and the other to the mouse pointer. I am trying to constrain the point by not exceeding a length parameter that I set. Heres the code:
import pygame
import Resources as r
import math as m
pygame.init()
class Segment():
def __init__(self, _screen, _id, _start_pos, _length):
self.screen = _screen
self.id = _id
self.start_pos = _start_pos
self.length = _length
def update(self):
if self.id == 1:
mouse_pos = pygame.mouse.get_pos()
self.angle = m.atan2(mouse_pos[1]-self.start_pos[1],mouse_pos[0]-self.start_pos[0])
self.a = self.start_pos
self.b = (m.cos(self.angle)*self.length, m.sin(self.angle)*self.length)
self.draw_line(self.a, self.b, r.black, 4)
def draw_line(self, start, end, color, width):
if self.id == 1:
pygame.draw.line(self.screen, color, start, end, width)
def get_data(self):
return (self.start_pos, self.end_)
I am seeing very different results when I run this that I would expect, it doesnt line up with my mouse and often just oscillates back and forth when the mouse is moved.
self.b is calculated based on origin 0, 0, not self.start_pos.
Add coordinates in self.a to self.b.
EDIT: as skrx pointed out in comment: mouse position doesn't have to be converted to Vector2 because tuple-Vector2 gives Vector2.
You can do the same with python.math.Vector2
Your start point on the middle bottom of the screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen_rect = screen.get_rect()
start = pygame.math.Vector2(screen_rect.centerx, screen_rect.bottom)
And end point using mouse positon and length
#mouse = pygame.math.Vector2(pygame.mouse.get_pos()) # edited
mouse = pygame.mouse.get_pos()
end = start + (mouse - start).normalize() * length
And now you can draw
pygame.draw.line(screen, (255,0,0), start, end)
Working example
import pygame
# === CONSTANS === (UPPER_CASE names)
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 400
# === MAIN === (lower_case names)
# --- init ---
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen_rect = screen.get_rect()
# --- objects ---
start = pygame.math.Vector2(screen_rect.centerx, screen_rect.bottom)
end = start
length = 150
# --- 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
elif event.type == pygame.MOUSEMOTION:
#mouse = pygame.math.Vector2(pygame.mouse.get_pos()) # edited
mouse = pygame.mouse.get_pos()
end = start + (mouse - start).normalize() * length
# --- objects events ---
# empty
# --- updates ---
# empty
# --- draws ---
screen.fill(BLACK)
pygame.draw.line(screen, RED, start, end)
pygame.display.update()
# --- FPS ---
clock.tick(25)
# --- the end ---
pygame.quit()
Red line has always the same length and it shows direction to cursor.
Related
I have this bullet which is shot by a tank. The cam should follow this shot and like zoom into it. How can I do this?
https://youtu.be/NLUqaVCyCk4 this is what I have so far
First you could create new surface and draw all objects on this surface, later you can make some modification (like scale for zooming), and finally you can blit it in window. This way you can modify (zoom, move) all objects at once.
To follow player (and keep it in center) you can calculate distance (x,y) between player and center of window. And later you can use it to blit surface in window.
if follow_player:
surface_rect.x = (screen_rect.centerx - player_rect.centerx)
surface_rect.y = (screen_rect.centery - player_rect.centery)
else:
surfac_rect.center = screen_rect.center
To zoom you can use scale surface and later blit it.
if zoom:
scale = 2
surface = pygame.transform.rotozoom(surface, 0, scale)
surface_rect = surface.get_rect()
else:
scale = 1
If you want to use both then you may need to use scale when you calculate distance
surface_rect.x = (screen_rect.centerx - player_rect.centerx * scale)
surface_rect.y = (screen_rect.centery - player_rect.centery * scale)
Minimal working code.
Face is moving randomly all time.
Use SPACE to switch follow_player, and ENTER to switch zoom
import pygame
import random
# --- constants --- (UPPER_CASE_NAMES)
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 25
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# --- main ---
pygame.init()
screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT) )
screen_rect = screen.get_rect()
surface = pygame.surface.Surface( (SCREEN_WIDTH, SCREEN_HEIGHT) )
# --- objects ---
bg_image = pygame.image.load('lenna.png').convert()
bg_rect = bg_image.get_rect(center=screen_rect.center)
player_image = pygame.image.load("face.png").convert()
player_rect = player_image.get_rect(center=screen_rect.center)
# --- mainloop ---
clock = pygame.time.Clock()
follow_player = False
zoom = False
#number = 0 # to generate images for animated `gif`
# `ffmpeg -i image-%03d.jpg -vf scale=250:200 video.gif`
running = True
while running:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYUP:
if event.key == pygame.K_ESCAPE:
running = False
elif event.key == pygame.K_SPACE:
follow_player = not follow_player
elif event.key == pygame.K_RETURN:
zoom = not zoom
# --- changes/moves/updates ---
move_x = random.randint(-5, 5)
move_y = random.randint(-5, 5)
player_rect.move_ip(move_x, move_y)
# --- draw on surface ---
surface.fill(BLACK)
surface.blit(bg_image, bg_rect)
surface.blit(player_image, player_rect)
# --- modify surface ---
surface_mod = surface.copy()
surface_mod_rect = surface_mod.get_rect()
if zoom:
scale = 2
surface_mod = pygame.transform.rotozoom(surface_mod, 0, scale)
surface_mod_rect = surface_mod.get_rect()
else:
scale = 1
if follow_player:
surface_mod_rect.x = (screen_rect.centerx - player_rect.centerx*scale)
surface_mod_rect.y = (screen_rect.centery - player_rect.centery*scale)
else:
surface_mod_rect.center = screen_rect.center
# --- draw surface on screen ---
screen.fill(BLACK)
screen.blit(surface_mod, surface_mod_rect)
pygame.display.flip()
clock.tick(FPS)
#pygame.image.save(screen, f"image-{number:03}.jpg")
#number += 1
# --- end ---
pygame.quit()
lenna.png (from Wikipedia: Lenna)
face.png
I did a lot of research on how to delete a drawing on the screen after clicking it, and I couldn't do that
Try1 how to remove draw objects from pygame window?
Try2 How to remove a drawn circle in pygame? (without "going over" other things)
When clicked on the circle it will remove itself, and thus create another circle to be able to click.
import pygame, sys
from pygame.locals import *
from pygame import mixer
pygame.init()
musica = 'circles.mp3'
mixer.music.load(musica)
mixer.music.play()
pygame.init()
screen = pygame.display.set_mode((500, 500))
pygame.display.set_caption("OSU DA DEEP WEB")
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
screen.fill(WHITE)
#posição
width = 500 -30
height = 500 - 30
widthposition = random.randrange(width)
heightposition = random.randrange(width)
#sistema de pontos
points = 0
circle = pygame.draw.circle(screen, (0, 0, 0), (400, 300), 25)
def draw():
print('CLicked')
circle = pygame.draw.circle(screen, (0, 0, 0), (400, 300), 25)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.display.flip()
You have to check event to catch when left button was click and then you can draw white background and draw circle
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == pygame.BUTTON_LEFT:
screen.fill(WHITE)
draw(screen)
But this still doesn't check if you clicked on circle.
Minimal working code.
import sys
import random
import pygame
# --- constants ---
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
WIDTH = 500
HEIGHT = 500
# --- functions ---
def draw(screen):
print('Clicked')
x = random.randrange(30, WIDTH-30)
y = random.randrange(30, HEIGHT-30)
pygame.draw.circle(screen, (0, 0, 0), (x, y), 25)
# --- main ---
musica = 'circles.mp3'
pygame.init()
pygame.mixer.music.load(musica)
pygame.mixer.music.play()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
screen.fill(WHITE)
draw(screen)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == pygame.BUTTON_LEFT:
screen.fill(WHITE)
draw(screen)
pygame.display.flip()
draw.circle gives object pygame.Rect() with rectangle area used by circle and you could use it to "check collision" with mouse position
circle_rect = pygame.draw.circle(...)
#... code ...
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == pygame.BUTTON_LEFT:
if circle_rect.collidepoint(even.pos):
screen.fill(WHITE)
draw(screen)
and it check position in rectangle area so it works better but not ideal
import sys
import random
import pygame
# --- constants ---
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
WIDTH = 500
HEIGHT = 500
# --- functions ---
def draw(screen):
print('Clicked')
x = random.randrange(30, WIDTH-30)
y = random.randrange(30, HEIGHT-30)
circle_rect = pygame.draw.circle(screen, (0, 0, 0), (x, y), 25)
return circle_rect
# --- main ---
musica = 'circles.mp3'
pygame.init()
pygame.mixer.music.load(musica)
pygame.mixer.music.play()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
screen.fill(WHITE)
circle_rect = draw(screen)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == pygame.BUTTON_LEFT:
if circle_rect.collidepoint(event.pos):
screen.fill(WHITE)
circle_rect = draw(screen)
pygame.display.flip()
There is function to check collicion in cicle area but it works for two pygame.sprite.Sprite, not for single pygame.Rect and mouse position (single point). You would have to convert mouse position and pygame.Rect to pygame.sprite.Sprite but it is to complex for this problem.
Doc: pygame.sprite.collide_circle()
OR you can use pygame.math.Vector2.distance_to() to calculate distance between mouse position and center of circle - it has to be equal or smaller then 25
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == pygame.BUTTON_LEFT:
pos = pygame.math.Vector2(event.pos)
if pos.distance_to(circle_rect.center) <= 25:
screen.fill(WHITE)
circle_rect = draw(screen)
import sys
import random
import pygame
# --- constants ---
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
WIDTH = 500
HEIGHT = 500
# --- functions ---
def draw(screen):
print('Clicked')
x = random.randrange(30, WIDTH-30)
y = random.randrange(30, HEIGHT-30)
circle_rect = pygame.draw.circle(screen, (0, 0, 0), (x, y), 25)
return circle_rect
# --- main ---
musica = 'circles.mp3'
pygame.init()
pygame.mixer.music.load(musica)
pygame.mixer.music.play()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
screen.fill(WHITE)
circle_rect = draw(screen)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == pygame.BUTTON_LEFT:
pos = pygame.math.Vector2(event.pos)
if pos.distance_to(circle_rect.center) <= 25:
screen.fill(WHITE)
circle_rect = draw(screen)
pygame.display.flip()
EDIT:
If you will want to add other object which will move then you will have to organize it in different way. In while True in every loop you will have to clear screen and draw again all object. And this needs more changes
import sys
import random
import pygame
# --- constants ---
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
WIDTH = 500
HEIGHT = 500
FPS = 25
# --- classes ---
class Circle():
def __init__(self, x, y, r, color, random=False):
self.x = x
self.y = y
self.r = r
self.color = color
# vector to check collision
self.center = pygame.math.Vector2((x, y))
if random:
self.set_random_position()
def draw(self, screen):
#pygame.draw.circle(screen, self.color, (self.x, self.y), self.r)
pygame.draw.circle(screen, self.color, self.center, self.r)
def check_collision(self, position):
return self.center.distance_to(position) <= self.r
def set_random_position(self):
self.x = random.randint(30, WIDTH-30) # `randint` better then `randrange`
self.y = random.randint(30, HEIGHT-30) # `randint` better then `randrange`
# vector to check collision
self.center = pygame.math.Vector2(self.x, self.y)
def move_random(self):
dx = random.randint(-5, 5) # `randint` better then `randrange`
dy = random.randint(-5, 5) # `randint` better then `randrange`
self.x += dx
self.y += dy
if self.x < self.r:
self.x = self.r
if self.x > WIDTH-self.r:
self.x = WIDTH-self.r
if self.y < self.r:
self.y = self.r
if self.y > HEIGHT-self.r:
self.y = HEIGHT-self.r
self.center = pygame.math.Vector2(self.x, self.y)
# --- functions ---
# ... empty ...
# --- main ---
musica = 'circles.mp3'
pygame.init()
#pygame.mixer.music.load(musica)
#pygame.mixer.music.play()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# create circle
circle = Circle(0, 0, 25, RED, random=True)
# create other objects and keep on list
others = [Circle(0, 0, 10, GREEN, random=True) for _ in range(100)]
clock = pygame.time.Clock()
while True:
# - events - (without draws)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == pygame.BUTTON_LEFT:
if circle.check_collision(event.pos):
# only change `x,y` without drawing
circle.set_random_position()
# - updates - (without draws)
# move other objects from list
for item in others:
item.move_random()
# - draws - (without events and updates)
# clear screen
screen.fill(WHITE)
# draw circle
circle.draw(screen)
# draw other objects from list
for item in others:
item.draw(screen)
# send on monitor
pygame.display.flip()
# - FPS -
# to keep the same speed on different computers (with different CPU speed)
clock.tick(FPS)
I want to make some sort of typing game in python using pygame. So, if the key pressed character is the same as the character in the word, it should return true... Is there any way to do this in python?
For example:
the word is "cat", if the user presses the key 'c', then it returns true... and so on for the rest of the characters.
here's my main.py file
from time import sleep
import pygame
import random
import winsound
from words import Words
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255, 0)
RED = (255, 0, 0)
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
done = False
clock = pygame.time.Clock()
screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
w1 = Words(screen) #making a single word (for now) to see if typing works
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(WHITE)
w1.draw()
#attempting to write code here to compare word and user input
pygame.display.flip()
clock.tick(60)
pygame.init()
exit()
here's my words.py file
from random_words import RandomWords
import pygame
import random
from queue import *
rw = RandomWords()
class Words():
def __init__(self, screen):
self.screen = screen
self.x_point = 400
self.y_point = 400
self.word = rw.random_word() #generates a random word
self.queue = Queue() #was hoping to use the queue so that if the user types the char correctly in the right order, then the letter would change color or something (but that's further down the line)
for c in self.word: #iterate through randomized word..
self.queue.put(c) #add each char in randomized word to queue, for typing reasons
def getY(self):
return self.y_point
def draw(self):
#creates a new object
myfont = pygame.font.SysFont('Comic Sans MS' ,30)
#creates a new surface with text drawn on it
textsurface = myfont.render(self.word, False, (0,0,0))
self.screen.blit(textsurface,(self.x_point,self.y_point))
Event KEYDOWN has event.unicode, event.key, event.mod
You can compare
if event.type == pygame.KEYDOWN:
if event.unicode == "a":
or even
if event.type == pygame.KEYDOWN:
if event.unicode.lower() == "a":
to check "a" and "A"
To check char in word
if event.type == pygame.KEYDOWN:
if event.unicode.lower() in your_word.lower():
Example code use event.unicode to render text with pressed keys.
BTW: It is not some Entry widget so it doesn't delete char when you press backspace.
import pygame
# --- constants ---
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255, 0)
RED = (255, 0, 0)
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 200
FPS = 5 # `FPS = 25` is enough for human eye to see animation.
# If your program don't use animation
# then `FPS = 5` or even `FPS = 1` can be enough
# --- main ---
# - init -
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
screen_rect = screen.get_rect()
# - objects -
font = pygame.font.SysFont(None, 30)
text = ""
text_image = font.render(text, True, GREEN)
text_rect = text_image.get_rect() # get current size
text_rect.center = screen_rect.center # center on screen
# - mainloop -
clock = pygame.time.Clock()
done = False
while not done:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
text += event.unicode
text_image = font.render(text, True, GREEN)
text_rect = text_image.get_rect() # get current size
text_rect.center = screen_rect.center # center on screen
# - draws -
screen.fill(BLACK)
screen.blit(text_image, text_rect)
pygame.display.flip()
clock.tick(FPS)
# - end -
pygame.quit() # <-- quit(), not init()
I am trying to make a moving platform so when the platforms reaches a curtain point it is supposed to reverse direction and go back but from what I can see it looks like it is vibrating back and fort
program link: https://drive.google.com/file/d/0BzvvQCByWwmAQThfdkEtSlRKa1k/view?usp=sharing
here is my code:
class lbuild(pygame.sprite.Sprite):
#This class represents alevel builder. It derives from the "Sprite" class in Pygame.
def __init__(self, color, width, height,x,y):
# Call the parent class (Sprite) constructor
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
# Draw the car (a rectangle!)
pygame.draw.rect(self.image, color, [0, 0, width, height])
# Fetch the rectangle object that has the dimensions of the image.
self.rect = self.image.get_rect()
self.rect.x=x
self.rect.y=y
all_sprites_list = pygame.sprite.Group()
movblock=pygame.sprite.Group()#sprite group
def level1():
global all_sprites_list
global movblock
xpos=0
for x in range(50):
all_sprites_list.add(lbuild(GREY,20,20,xpos,680))
xpos =xpos+20
ypos=660
xpos2 =40
for x in range(2):
all_sprites_list.add(lbuild(black,60,20,xpos2,ypos))
ypos=ypos-20
mblk=lbuild(RED,100,20,120,600)#draws the block
movblock.add(mblk)#adds it to the sprite group
clock=pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
#Game Logic
all_sprites_list.update()
#Drawing on Screen
screen.fill(WHITE)
#Draw The Road
spd=5
if mblk.rect.x>200:#supposed to cheak if the block x postion a has reached 200 and the reverse its direction but instead it looks like it is vibrating
spd= -spd
if mblk.rect.x<100:
spd= -spd
mblk.rect.x+=spd
#Now let's draw all the sprites in one go. (For now we only have 1 sprite!)
all_sprites_list.draw(screen)
movblock.draw(screen)
#Refresh Screen
pygame.display.flip()
#Number of frames per secong e.g. 60
clock.tick(60)
Your problem is spd = 5 inside while True.
You change direction using
spd = -spd
but after that you overwrite it using
spd = 5
You have to use spd = 5 before while True
Full version with other modifications.
import pygame
import sys
# --- constants --- (UPPER_CASE names)
WHITE = (255, 255, 255)
GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
BLACK = (0,0,0)
SCREEN_WIDTH=1000
SCREEN_HEIGHT=700
# --- classes --- (CamelCase names)
class LBuild(pygame.sprite.Sprite):
def __init__(self, color, width, height, x, y):
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
# Draw the car (a rectangle!)
pygame.draw.rect(self.image, color, [0, 0, width, height])
# Fetch the rectangle object that has the dimensions of the image.
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# --- functions --- (lower_case names)
def level_1(screen, all_sprites_list, movblock):
x = 0
for _ in range(50):
all_sprites_list.add(LBuild(GREY, 20, 20, x, 680))
x += 20
y = 660
x2 = 40
for _ in range(2):
all_sprites_list.add(LBuild(BLACK, 60, 20, x2, y))
y -= 20
mblk = LBuild(RED, 100, 20, 120, 600)
movblock.add(mblk)
spd = 5
# - mainloop -
clock = pygame.time.Clock()
#current_time = pygame.time.get_ticks()
# change something after 2s
#change_time = current_time + 2000 # 2000ms = 2s
while True:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
# False = exit game
return False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
# True = go to next level
return True
# - updates (without draws) -
#current_time = pygame.time.get_ticks()
#if current_time >= change_time:
# TODO: change something
# # change something again after 2s
# change_time = current_time + 2000
all_sprites_list.update()
if mblk.rect.x > 200:
spd = -spd
if mblk.rect.x < 100:
spd = -spd
mblk.rect.x += spd
# - draws (without updates) -
screen.fill(WHITE)
all_sprites_list.draw(screen)
movblock.draw(screen)
pygame.display.flip()
# - FPS -
clock.tick(60)
# --- main ---
# - init -
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Car Racing")
# - game -
all_sprites_list = pygame.sprite.Group()
movblock = pygame.sprite.Group()
goto_next_level = level_1(screen, all_sprites_list, movblock)
#if goto_next_level:
# goto_next_level = level_2(screen, all_sprites_list, movblock)
#if goto_next_level:
# goto_next_level = level_3(screen, all_sprites_list, movblock)
# - exit -
pygame.quit()
sys.exit()
I'm new to python. I programmed with vb2010, but it's time to try something new. I want to hide a action after 5 seconds after mouse down event(like in start()).
import pygame
import sys
from pygame.locals import *
from time import gmtime, strftime
import threading
import time
white = (255,255,255)
black = (0,0,0)
blue = (0,0,255)
width = 600
height = 400
channel = '0001'
name = 'Channel 3'
class screen(object):
def __init__(self):
pygame.init()
self.font = pygame.font.SysFont('Arial', 25)
pygame.display.set_caption('PyTV')
self.screen = pygame.display.set_mode((width,height), 0, 32)
self.screen.fill((black))
pygame.display.update()
def printData(self):
self.rect = pygame.draw.rect(self.screen, (blue), (0, 0, width, height - 350), 0)
self.screen.blit(self.font.render(channel, True, white), (width - 590, 0))
self.screen.blit(self.font.render(name, True, white), (height - 335, 0))
self.screen.blit(self.font.render(strftime("%H:%M %d/%m/%Y", gmtime()), True, white), (width - 590, height - 377))
pygame.display.update()
def clean(self):
self.screen.fill((black))
pygame.display.update()
if __name__ == '__main__':
def start():
Pan3.printData()
time.sleep(5)
Pan3.clean()
Pan3 = screen()
threading.Thread(target=start).start()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); sys.exit();
if event.type == pygame.MOUSEBUTTONDOWN:
print 'Event! Mouse Down! Code here....'
A timer may suit your needs, given that you also use threading.
EDIT: Addressing your needs for a more detailed explanation as to how to get it to work, here's some pseudo-code.
if event.type == pygame.MOUSEBUTTONDOWN:
if active_timer:
timer.cancel()
timer = Timer(5.0, show_info_things)
timer.start()
I hope this gets you going well enough.
When you click left mouse first time then it shows date, when you click second time then it hides date. If you don't click second time then it hides automatically after 5 seconds.
The same with key SPACE - first press shows, second hides. If you don't press second time then it hides automatically after 5 seconds.
Key ESC and right click hides too.
import pygame
import sys
import time
# --- constants --- (UPPER_CASE names)
WHITE = (255,255,255)
BLACK = ( 0, 0, 0)
BLUE = ( 0, 0,255)
WIDTH = 600
HEIGHT = 400
# --- classes --- (CamelCase names)
class Screen(object):
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
pygame.display.set_caption('PyTV')
self.font = pygame.font.SysFont('Arial', 25)
self.channel = '0001'
self.name = 'Channel 3'
self.show_data = None
self.current_time = pygame.time.get_ticks()
def draw_data(self):
self.rect = pygame.draw.rect(self.screen, BLUE, (0, 0, WIDTH, HEIGHT-350), 0)
self.screen.blit(self.font.render(self.channel, True, WHITE), (WIDTH-590, 0))
self.screen.blit(self.font.render(self.name, True, WHITE), (HEIGHT-335, 0))
self.screen.blit(self.font.render(time.strftime("%H:%M:%S %d/%m/%Y", time.gmtime()), True, WHITE), (WIDTH-590, HEIGHT-377))
def events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.show_data = None
elif event.key == pygame.K_SPACE:
if self.show_data:
self.show_data = None
else:
self.show_data = self.current_time + 5000
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if self.show_data:
self.show_data = None
else:
self.show_data = self.current_time + 5000
elif event.button == 3:
# hide on right click
self.show_data = None
def update(self):
# if displayed
if self.show_data:
# check time
if self.current_time >= self.show_data:
# hide after time
self.show_data = None
def draw(self):
self.screen.fill(BLACK)
if self.show_data:
self.draw_data()
pygame.display.update()
def run(self): # mainloop
while True:
self.current_time = pygame.time.get_ticks()
if self.events() is False:
break
self.update()
self.draw()
#sys.exit()
# --- fucntions --- (lower_case names)
# empty
# --- main ---
if __name__ == '__main__':
Screen().run()