This question already has answers here:
Why is my pygame display not responding while waiting for input?
(1 answer)
How can I create a text input box with Pygame?
(5 answers)
Closed 5 months ago.
So basically what happened is, I am making a reminder app where it rings an alarm at a certain time, the problem is I'm having trouble displaying a time. I've used show text in this code to display the current time, but when I try to display an activity I'm not getting an error but it's not showing.
Code:
from pygame import mixer
from datetime import datetime
import pygame
from pygame.locals import *
pygame.init()
mixer.init()
screen = pygame.display.set_mode((500,500))
pygame.display.set_caption("App")
mixer.music.load("song.mp3")
mixer.music.set_volume(0.7)
global o
o=0
#FUNCTIONS
def show_text(msg, x, y, color, size):
fontobj= pygame.font.SysFont("freesans", size)
msgobj = fontobj.render(msg,False,color)
screen.blit(msgobj,(x, y))
def Session():
session_name = input("What do you want to call your session?")
starttime = input("What time do you want to start? (Example 600 = 6:00)")
endtime = input("What time do you want to end? (Example 700 = 7:00)")
o=1
pygame.display.update()
#VARIABLES
green = (0,255,0)
black = (0,0,0)
white = (255,255,255)
activites = ""
start_time = ""
end_time = ""
counter = 0
hours = 60
#END OF VARIABLES
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
if event.type == MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
if x>239 and x<286 and y> 399 and y<446:
counter = 1
if counter == 1:
Session()
counter = 0
screen.fill(black)
#GETTING TIME
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
#END OF GETTING TIME
#GUI
show_text(str(current_time),220,10,green,20)
if o==1:
show_text(str(session_name), 180,200, white, 75)
show_text("Add Activity",220,375,green,20)
pygame.draw.rect(screen,green,(240,400,45,45))
pygame.draw.rect(screen,white,(260,403,5,40))
pygame.draw.rect(screen,white,(245,420,37,5))
#END OF GUI
pygame.display.update()
I Would appreciate a response on why it was wrong as well as a fixed code, thanks in advance!
Related
This question already has answers here:
How can I add objects to a "pygame.sprite.Group()"?
(1 answer)
Going through sprites in an array and redrawing them when it's time to redraw causes some to blink
(1 answer)
What does pygame.sprite.Group() do
(1 answer)
Closed last month.
I have this code:
import pygame as pg
from pygame.locals import QUIT
pg.init()
pg.display.set_caption("Cookie clicker")
DISPLAY = pg.display.set_mode((500, 300))
c = pg.image.load("cookie.png")
cookie = pg.transform.scale(c, (150,150))
mid = 250,150
mid = cookie.get_rect(center=(mid))
#other imgs here
cpc = 1
money = 0
cps = 0
cookies = 0
class draw(main,sidebar_popup):
def upd():
pg.display.update()
def draw(main):
pg.blit(cookie,mid)
def draw(sidebar_popup):
#show a sidebar
run = True
while run:
draw(main)
for event in pg.event.get():
if event.type == QUIT:
run = False
I want to be able to use draw(#image) to show images when I need but I don't know how to use class function.
I am trying to make a cookie clicker on pygame and learning as I go along.
Ps. I am new to pygame and haven't fully learnt python so dont really understand class yet.
This question already has answers here:
How to scroll the background surface in PyGame?
(1 answer)
Making the background move sideways in pygame
(2 answers)
Closed 3 months ago.
i'm learning how to make a moving backround in pygame.
i learnd how to do it horizontal and trying now to do it vertical.
My problem is that my loop is not fully working , i manged to make it so the backround moves downward, but it wont make a third / fourth etc screen it just stops after 2 screens.
Thank you in advance for the help/ explenation. ^-^
import sys
import pygame
pygame.init()
fps = 60
framepersec = pygame.time.Clock()
white = (255, 255, 255)
screen_width = 400
screen_height = 600
display = pygame.display.set_mode((screen_width, screen_height))
display.fill(white)
pygame.display.set_caption("Backround test")
class Backround():
def __init__(self):
self.bgimage = pygame.image.load("image/test.png").convert()
self.rectbgimg = self.bgimage.get_rect()
self.bgy1 = 0
self.bgx1 = 0
self.bgy2 = -self.rectbgimg.height
self.bgx2 = 0
self.moving_speed = 3
def update(self):
self.bgy1 += self.moving_speed
self.bgy2 += self.moving_speed
if -self.rectbgimg.height >= self.bgy1:
self.bgy1 = self.rectbgimg.height
if -self.rectbgimg.height >= self.bgy2:
self.bgy2 = self.rectbgimg.height
def render(self):
display.blit(self.bgimage, (self.bgx1, self.bgy1))
display.blit(self.bgimage, (self.bgx2, self.bgy2))
backround = Backround()
while True:
framepersec.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
backround.update()
backround.render()
pygame.display.update()
Hi I am trying to code a simple application with Pygame. I have made various searches and found that best way to get an user input is to use a 3rd Party GUI.
I have found Simple Game Code for this aim. Below, you can find my base code, it looks for the images inside same path of script and replaces them in order at screen.
But I have no experience with this kind of applications. I am trying to understand from the documentation of SGC: https://github.com/codetricity/sgc/blob/master/example/test.py
It is not an easy task for me. I could develop this far, my code is running. But I couldn't understand the button implementation part.
Can you help me implement a "Scale Widget" at beginning to get user input between a range of integers. Also, a "Button Widget" to pass starting screen and begin my main code I will share with you.
Thanks for your time
import glob
import time
import numpy as np
import timeit
import pygame
import sgc
from sgc.locals import *
start = timeit.default_timer()
maxnote = 10
maxduration = 10
pygame.init()
white = (255, 255, 255)
path = r'C:\Path'
mylistname = [f for f in sorted(glob.glob("*.png"))]
mylistpath = [f for f in sorted(glob.glob(path + "/*.png"))]
for i in range(len(mylistname)):
mylistname[i] = mylistname[i].replace(".png", "")
mylistname[i] = mylistname[i].replace("h", ".")
mylistname[i] = float(mylistname[i])
imgname = []
for i in range(len(mylistname)):
imgname.append(str("img" + str(mylistname[i])))
imglist = []
for i in range(len(mylistpath)):
name = str(imgname[i])
name = pygame.image.load(mylistpath[i])
imglist.append(name)
current_image = 0
display_surface = pygame.display.set_mode((400, 400))
while (timeit.default_timer() - start < maxduration) | (current_image < maxnote):
#for imj in range(len(imglist)+1):
print(str(current_image) + "s")
if current_image < len(imglist):
print(str(current_image) + "0")
while True:
print(str(current_image) + "p")
display_surface.fill(white)
display_rect = display_surface.get_rect()
image_rect = imglist[current_image].get_rect()
image_rect.center = display_rect.center
display_surface.blit(imglist[current_image],image_rect)
pygame.display.update()
pygame.display.flip()
time.sleep(5)
current_image = current_image + 1
print(str(current_image) + "n")
break
else:
font = pygame.font.Font('freesansbold.ttf', 32)
text = font.render('GeeksForGeeks', True, (0, 255, 0), (0, 0, 128))
textRect = text.get_rect()
textRect.center = display_rect.center
display_surface.blit(text, textRect)
pygame.display.update()
pygame.display.flip()
time.sleep(5)
pygame.display.quit()
print("the end")
Using your code I added SGC button which is displayed on images and it display text in console when it is clicked.
I had two problems:
SGC is old and works only with Python 2. For Python 3 it would need relative imports. But later it may need other changes.
time.sleep() was blocking loop which checks key/mouse events, updates widgets, runs function when button is clicked, etc. sleep makes this problem with all GUI frameworks (tkinter, PyQt, wxpython, etc.) and in PyGame loop which has to run all time to check and update widgets and other elements. I use clock to check if it is time to change image. This way loop can works all time and it can update Button when mouse move on button and click it.
Tested on Python 2.7, Linux Mint 19.2
import glob
import pygame
import time
import sgc
from sgc.locals import *
# --- constants --- (UPPER_CASE)
WHITE = (255, 255, 255)
MAXNOTE = 10
MAXDURATION = 10
PATH = r'C:\Path'
# --- functions --- (lower_case_names)
def on_click_button():
print('on_click_button')
# --- main ---
filenames = sorted(glob.glob(PATH + "/*.png"))
print('len:', len(filenames))
names = []
images = []
for item in filenames:
names.append("img" + item.replace(".png", "").replace("h", "."))
images.append(pygame.image.load(item))
current_image = 0
# ---
pygame.init()
display_surface = sgc.surface.Screen((400, 400))
#display_surface = pygame.display.set_mode((400, 400))
display_rect = display_surface.get_rect()
font = pygame.font.Font('freesansbold.ttf', 32)
# add button
btn = sgc.Button(label="Clicky", pos=(10, 10))#, label_font=font)
btn.add(0)
# assign function to button
btn.on_click = on_click_button
# ---
clock = pygame.time.Clock()
current_time = pygame.time.get_ticks()
end_time = current_time + MAXDURATION*1000
end_slide = current_time
running = True
while running and ((current_time < end_time) or (current_image < MAXNOTE)):
ticks = clock.tick(30)
for event in pygame.event.get():
# send events to SGC so it can check if button was clicke
sgc.event(event)
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
current_time = pygame.time.get_ticks()
if (end_slide <= current_time) and (current_image < len(images)):
image = images[current_image]
image_rect = image.get_rect()
image_rect.center = display_rect.center
end_slide = current_time + 2000 # 2000ms (2s)
current_image += 1
display_surface.fill(WHITE)
display_surface.blit(image, image_rect)
# draw all widgets
sgc.update(ticks)
pygame.display.flip() # doesn't need pygame.display.update() because both do the same
# ---
display_surface.fill(WHITE)
text = font.render('GeeksForGeeks', True, (0, 255, 0), (0, 0, 128))
text_rect = text.get_rect()
text_rect.center = display_rect.center
display_surface.blit(text, text_rect)
#pygame.display.update() # no need it
pygame.display.flip()
time.sleep(5)
# --- end ---
pygame.display.quit()
print("the end")
i Started creating a game and i stumbled into a little problem:
*When pressing "SPACE Bar" Red Squares keep Spawning randomly on Display
Question
How can i make the Red Squares into obstacles?
im a total begginer and im sorry for asking such a simple question.. :/
The Code might give you an idea:
import pygame, sys
from random import randint
from pygame.locals import*
"List the Stores the Squares"
red_square_list = []
gameDisplay_width = 800
gameDisplay_height = 600
pygame.init()
gameDisplay = pygame.display.set_mode((gameDisplay_width, gameDisplay_height))
pygame.display.set_caption("Square-it")
clock = pygame.time.Clock()
red_color = pygame.Color("red")
"White Square"
white_x = 400
white_y = 300
white_width = 10
white_height = 10
white_color = pygame.Color("white")
white = pygame.Rect(white_x, white_y, white_width, white_height)
"Red Squares"
def create_red_square(x, y):
red_width = 10
red_height = 10
red = pygame.Rect(x, y, red_width, red_height)
return red
while True:
clock.tick(60)
gameDisplay.fill((0, 20, 5))
gameDisplay.fill(white_color, white)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
for each in red_square_list:
gameDisplay.fill(red_color, each)
pygame.display.update()
'''White Square Movement'''
keys = pygame.key.get_pressed()
if keys[K_LEFT]:
white.left = white.left - 4
if keys[K_RIGHT]:
white.right = white.right + 4
if keys[K_UP]:
white.top = white.top - 4
if keys[K_DOWN]:
white.bottom = white.bottom + 4
"when Space key Pressed, Spawns red Squares"
if keys[K_SPACE]:
x = randint(0, gameDisplay_width)
y = randint(0, gameDisplay_height)
red_square_list.append(create_red_square(x, y))
With your current system, as long as Space is being held down, a red square will be added to the list. This means that a square will be placed every FRAME the button is being pressed. Too much! What you want to do is add the following into your event loop. This will activate ON the frame that you press the key, not any more than that.
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
x = randint(0, gameDisplay_width)
y = randint(0, gameDisplay_height)
red_square_list.append(create_red_square(x, y))
I want to calculate the time of user's mouse events in Pygame, if user doesn't move his mouse about 15 seconds, then I want to display a text to the screen. I tried time module for that, but it's not working.
import pygame,time
pygame.init()
#codes
...
...
font = pygame.font.SysFont(None,25)
text = font.render("Move your mouse!", True, red)
FPS = 30
while True:
#codes
...
...
start = time.time()
cur = pygame.mouse.get_pos() #catching mouse event
end = time.time()
diff = end-start
if 15 < diff:
gameDisplay.blit(text,(10,500))
pygame.display.update()
clock.tick(FPS)
pygame.quit()
quit()
Well output is not what I want, I don't know how to calculate it if user doesn't move his mouse.
If I want to write a text when user's mouse in a special area, it's working like;
if 100 < cur[0] < 200 and 100 < cur[1] < 200:
gameDisplay.blit(text,(10,500))
But how can I calculate? I even couldn't find how to tell Python, user's mouse is on the same coordinates or not.Then I can say, if mouse coordinates changes, start the timer, and if it's bigger than 15, print the text.
Edit: You can assume it in normal Python without Pygame module, assume you have a function that catching the mouse events, then how to tell Python if coordinates of mouse doesn't change, start the timer, if the time is bigger than 15 seconds,print a text, then refresh the timer.
To display a text on the screen if there is no mouse movement within the pygame window for 3 seconds:
#!/usr/bin/python
import sys
import pygame
WHITE, RED = (255,255,255), (255,0,0)
pygame.init()
screen = pygame.display.set_mode((300,200))
pygame.display.set_caption('Warn on no movement')
font = pygame.font.SysFont(None, 25)
text = font.render("Move your mouse!", True, RED, WHITE)
clock = pygame.time.Clock()
timer = pygame.time.get_ticks
timeout = 3000 # milliseconds
deadline = timer() + timeout
while True:
now = timer()
if pygame.mouse.get_rel() != (0, 0): # mouse moved within the pygame screen
deadline = now + timeout # reset the deadline
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill(WHITE)
if now > deadline: # no movement for too long
screen.blit(text, (10, 50))
pygame.display.flip()
clock.tick(60) # set fps
You should add:
start = time.time()
cur = None
before while loop.
You should also change start = time.time() in while loop to:
if cur != pygame.mouse.get_pos():
start = time.time()
Also you could use pygame.time (it's similar to time but measure time in milliseconds)
In your code, the while True: code block is continuously running. The cur = pygame.mouse.get_pos() function is non blocking. This means it does not wait for mouse input - it will return straight away. So you need to initialize the start and cur variables before your while True: code block and then check the mouse position constantly in your loop.
If cur has changed since the last time the loop ran, then reset the start variable to the current time, and if the difference between the current time and start becomes larger than your 15 seconds, you can display the text.
You can also do that even without getting time, since you can calculate the pause as an integer counter through your FPS. Consider following example. Note that if the cursor is out of the window, the values of its positon will not change even if you move the cursor.
import pygame
pygame.init()
clock = pygame.time.Clock( )
DISP = pygame.display.set_mode((600, 400))
FPS = 25
Timeout = 15
Ticks = FPS*Timeout # your pause but as an integer value
count = 0 # counter
MC = pygame.mouse.get_pos()
MC_old = MC
MainLoop = True
while MainLoop :
clock.tick(FPS)
pygame.event.pump()
Keys = pygame.key.get_pressed()
if Keys[pygame.K_ESCAPE]:
MainLoop = False
MC = pygame.mouse.get_pos() # get mouse position
if (MC[0]-MC_old[0] == 0) and (MC[1]-MC_old[1] == 0) :
count = count + 1
else : count = 0
if count > Ticks :
print "What are you waiting for"
count = 0
MC_old = MC # save mouse position
pygame.display.flip( )
pygame.quit( )