Game Timer Using Pygame - python

I am working on a reaction game using Pygame and have run into a few difficulties with the timer. Currently how this code functions, is that when you start the program, you have to hit "a" for the countdown timer to start. As the letter appears on the screen you hit the corresponding keyboard key, which updates the score. The two things I would like to change have to do with the timer. I would like for the timer to autostart without having to hit the "a" button and I would like for the score to not continue to tally once the time has expired.
You will see some of my previous attempts commented out. In all of the versions where I have tried to implement the auto timer, the timer rapidly ticks off, rather than waiting a second in between counting off.
import pygame
from pygame.locals import *
import os, sys
import random
import time
time_a = 20
a_on = False
n1 = time.time()
letter = ["c", "b"]
pygame.init()
pygame.display.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Reaction Game")
background = pygame.Surface(screen.get_size())
rect = background.fill((0, 0, 0))
clock = pygame.time.Clock()
score = 0
font = pygame.font.SysFont("monospace", 36)
scoreupdate = font.render(format(score), 1, (255, 255, 255))
x = (random.choice(letter))
xupdate = font.render(format(x), 1, (255, 255, 255))
print x
#mainloop
while True:
clock.tick(30)
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
if event.type == USEREVENT:
if time_a > 0:
time_a -= 1
else:
break
#else:
#pygame.time.set_timer(USEREVENT, 0)
elif event.type == KEYDOWN:
if event.key == K_a:
if not a_on:
# Set for 1 second (1000 milliseconds)
pygame.time.set_timer(USEREVENT, 1000)
a_on = True
else:
# The other one should turn on immediately
pygame.time.set_timer(USEREVENT, 0)
pygame.time.set_timer(USEREVENT+1, 1000)
if x == "b" and event.key == K_b:
n3 = time.time()-n1
print n3
score += 1
n1 = time.time()
scoreupdate = font.render(format(score), 1, (255, 255, 255))
print "B button Hit"
print score
x = (random.choice(letter))
xupdate = font.render(format(x), 1, (255, 255, 255))
print x
if x == "c" and event.key == K_c:
n3 = time.time()-n1
print n3
score += 1
scoreupdate = font.render(format(score), 1, (255, 255, 255))
n1 = time.time()
print "C button Hit"
print score
x = (random.choice(letter))
xupdate = font.render(format(x), 1, (255, 255, 255))
print x
if event.key == K_PAUSE or event.key == K_p:
#pause both timers
pygame.time.set_timer(USEREVENT+1, 0)
pygame.time.set_timer(USEREVENT, 0)
#pygame.time.set_timer(USEREVENT, 1000)
#a_on = True
# Format time into minutes:seconds
#pygame.time.set_timer(USEREVENT, 1000)
time_a_str = "%d:%02d" % (int(time_a/60),int(time_a%60))
time_a_txt = font.render(time_a_str, 1, (255, 255, 255))
score_txt = scoreupdate
letter_txt = xupdate
letter_rect = letter_txt.get_rect()
letter_rect.center = (160, 30)
score_rect = score_txt.get_rect()
score_rect.center = (30, 30)
time_a_rect = time_a_txt.get_rect()
time_a_rect.center = (310, 310)
screen.blit(background, rect)
screen.blit(xupdate, letter_rect)
screen.blit(scoreupdate, score_rect)
screen.blit(time_a_txt, time_a_rect)
pygame.display.update()
#end mainloop

I would look at this example of a timer. It should have what you need.

Related

How to properly Dirty rectangles for simple application: Logic Issue

I am currently just testing the waters with Pygame display as I am extremely new to the module.
Here is the code:
import pygame
pygame.init()
SCALE = 1
display_width = int(1200 * SCALE)
display_height = int(800 * SCALE)
x = (display_width * 0.45)
y = (display_height * 0.8)
transparent = (0, 0, 0, 0)
black = (0, 0, 0)
white = (255, 255, 255)
green = (44, 215, 223)
red = (255, 67, 34)
blue = (77, 77, 77)
count = 0
running = True
box1_image = True
box3_image = True
background = pygame.image.load('C:/Users/Justi/source/repos/03 Game/Game/assets/background.jpg')
dirty_spot = pygame.image.load('C:/Users/Justi/source/repos/03 Game/Game/assets/dirty.png')
background_resized = pygame.transform.scale(dirty_spot, (display_width, display_height))
background_rect = background_resized.get_rect()
gameDisplay = pygame.display.set_mode(background_rect.size)
pygame.display.set_caption("Game 1")
clock = pygame.time.Clock()
dirty_spot_resized = pygame.transform.scale(dirty_spot, (200, 200))
square_dirty_spot = dirty_spot_resized.convert()
rect_dirty_spot = square_dirty_spot.get_rect()
def dirtyspot1(imagex, imagey):
gameDisplay.blit(dirty_spot_resized, (imagex,imagey))
while running:
rects = []
if rects != []:
pygame.display.update(rects)
for event in pygame.event.get():
if event.type == pygame.quit:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
running = False
#if box3_image: #Replacing the Bool passing variable with a simple loop count to trigger the else condition
if count < 50:
print("Test 1")
dirtyspot1(0,0)
pygame.display.update()
else:
print("Test 2")
dirty_rect = background.subsurface(rect_dirty_spot)
gameDisplay.blit(dirty_rect, (0,0))
rects.append(pygame.Rect(0,0, 200, 200))
gameDisplay.fill(white)
clock.tick(30)
count += 1
pygame.quit()
quit()
box1_image & box1_image are bool variables to flag certain condition which is passed from another function.
But I have gotten the passing of said variables working by doing a simple test with print("Test 2"). However, when it tries to blit dirty_rect. Nothing changes on the pygame display.
Assets (if needed):
background.jpg
dirty.png
May I check what is missing to properly "remove/delete" the dirty_spot blit? Thank you in advance.
import pygame
pygame.init()
SCALE = 1
display_width = int(1200 * SCALE)
display_height = int(800 * SCALE)
x = (display_width * 0.45)
y = (display_height * 0.8)
transparent = (0, 0, 0, 0)
black = (0, 0, 0)
white = (255, 255, 255)
green = (44, 215, 223)
red = (255, 67, 34)
blue = (77, 77, 77)
count = 0
running = True
box1_image = True
box3_image = True
background = pygame.image.load('background.jpg')
dirty_spot = pygame.image.load('dirty.png')
background_resized = pygame.transform.scale(background, (display_width, display_height))
background_rect = background_resized.get_rect()
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("Game 1")
clock = pygame.time.Clock()
dirty_spot_resized = pygame.transform.scale(dirty_spot, (200, 200))
square_dirty_spot = dirty_spot_resized.convert()
rect_dirty_spot = square_dirty_spot.get_rect()
show_dirt = False
def dirtyspot1(imagex, imagey):
gameDisplay.blit(dirty_spot_resized, (imagex,imagey))
while running:
rects = []
if rects != []:
pygame.display.update(rects)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
running = False
if event.key == pygame.K_d:
show_dirt = not show_dirt
if event.key == pygame.K_UP:
rect_dirty_spot.y -= 5
if event.key == pygame.K_DOWN:
rect_dirty_spot.y += 5
if event.key == pygame.K_RIGHT:
rect_dirty_spot.x += 5
if event.key == pygame.K_LEFT:
rect_dirty_spot.x -= 5
gameDisplay.blit(background_resized, (0,0))
if show_dirt:
gameDisplay.blit(dirty_spot_resized, rect_dirty_spot)
pygame.display.update()
clock.tick(5)
count += 1
pygame.quit()
quit()
like this? (I changed the FPS to 5 so it takes a while to change)
import pygame
pygame.init()
SCALE = 1
display_width = int(1200 * SCALE)
display_height = int(800 * SCALE)
x = (display_width * 0.45)
y = (display_height * 0.8)
transparent = (0, 0, 0, 0)
black = (0, 0, 0)
white = (255, 255, 255)
green = (44, 215, 223)
red = (255, 67, 34)
blue = (77, 77, 77)
count = 0
running = True
box1_image = True
box3_image = True
background = pygame.image.load('background.jpg')
dirty_spot = pygame.image.load('dirty.png')
background_resized = pygame.transform.scale(background, (display_width, display_height))
background_rect = background_resized.get_rect()
gameDisplay = pygame.display.set_mode(background_rect.size)
pygame.display.set_caption("Game 1")
clock = pygame.time.Clock()
dirty_spot_resized = pygame.transform.scale(dirty_spot, (200, 200))
square_dirty_spot = dirty_spot_resized.convert()
rect_dirty_spot = square_dirty_spot.get_rect()
def dirtyspot1(imagex, imagey):
gameDisplay.blit(dirty_spot_resized, (imagex,imagey))
while running:
rects = []
if rects != []:
pygame.display.update(rects)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
running = False
gameDisplay.fill(white)
#if box3_image: #Replacing the Bool passing variable with a simple loop count to trigger the else condition
if count < 50:
print("Test 1")
dirtyspot1(0,0)
else:
print("Test 2")
dirty_rect = background.subsurface(rect_dirty_spot)
gameDisplay.blit(dirty_rect, (0,0))
rects.append(pygame.Rect(0,0, 200, 200))
pygame.display.update()
clock.tick(5)
count += 1
pygame.quit()
quit()
I think you have misunderstood things. You can blit one image or surface on top of another, and you build things up like that, then blit them to the display and finally update the display.
You have this line:
background_resized = pygame.transform.scale(dirty_spot, (display_width, display_height))
which I assume should be background not dirty_spot.
I moved the call to display.update() out of the if loop, because you call display.update() last.

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)

How can you make the previous line disappear in python?

I'm making a constellation that starts from (0,0). The previous line has to disappear after a two second delay and when the left is clicked within the two second delay, white circles should appear. I don't know why my timer isn't working and I'm not sure how to make the line disappear. Also the circles don't appear. This is my code
from pygame import *
import random
init()
size = width, height = 700, 700
screen = display.set_mode(size)
button = 0
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0,0,255)
WHITE = (255,255,255)
colors = (RED,GREEN,BLUE)
time.set_timer(USEREVENT, 2000)
mx = 0
my = 0
def drawScene(screen, button):
if button == 1:
draw.circle(screen,RED,(mx,my), 5)
draw.line(screen,RED,(mx,my),(lx,ly),2)
draw.circle(screen,RED,(lx,ly), 5)
display.flip()
if button == 3:
draw.line(screen,random.choice(colors),(mx,my),(lx,ly),2)
draw.circle(screen,random.choice(colors),(lx,ly), 5)
display.flip()
running = True
myClock = time.Clock()
start = time.get_ticks()
# Game Loop
while running:
lx = mx
ly = my
for evnt in event.get(): # checks all events that happen
if evnt.type == QUIT:
running = False
if evnt.type == MOUSEBUTTONDOWN:
mx,my = evnt.pos
button = evnt.button
cx,cy = mouse.get_pos()
draw.circle(screen,WHITE,(cx,cy),5)
if evnt.type == USEREVENT:
my_event = event.Event(USEREVENT)
time.set_timer(my_event , 2000)
drawScene(screen, button)
myClock.tick(60) # waits long enough to have 60 fps
quit()
I hope this is what you were wanting and the comments are clear.
from pygame import *
import random
init()
size = width, height = 700, 700
screen = display.set_mode(size)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
WHITE = (255, 255, 255)
colors = (RED, GREEN, BLUE)
time.set_timer(USEREVENT, 2000)
mx = 0
my = 0
def drawScene(screen, button, prev_point, new_point):
if button == 1:
draw.circle(screen, RED, prev_point, 5)
draw.circle(screen, WHITE, new_point, 5)
draw.line (screen, RED, prev_point, new_point, 2)
display.flip()
if button == 3:
draw.line (screen, random.choice(colors), prev_point, new_point,2)
draw.circle(screen, random.choice(colors), new_point, 5)
display.flip()
running = True
myClock = time.Clock()
prev_render = time.get_ticks() #time in ticks that last render occured
prev_point = (mx, my) #where previous line ended
#function for when to re draw the scene
#ternary if. if override == True, then return true. Else return if time since last update > 2secs
rerender = lambda time_since_update, override: (time_since_update>2000, True)[override]
# Game Loop
while running:
override = False
for evnt in event.get(): # checks all events that happen
if evnt.type == QUIT:
running = False
if evnt.type == MOUSEBUTTONDOWN:
override = True #force window to rerender
new_point = evnt.pos #(mx, my)
button = evnt.button
#rerender window only if necessary. (personal preference)
updated_at = time.get_ticks()
dt = updated_at-prev_render #time difference
if(rerender(dt, override)):
screen.fill(BLACK)
drawScene(screen, button, prev_point, new_point)
prev_point = new_point
prev_render = updated_at
display.update()
myClock.tick(60) # waits long enough to have 60 fps
quit()
This is not a complete solution, but I'll give you a general idea how how to start
Create a list of times and a list of lines:
lines = []
Get the current time in the main application loop:
current_time = pygame.time.get_ticks()
When the mouse is clicked then compute the time when the line has to disappear (current_time + 2000) and compute a random color.
Add a Dictionary with the start point, the end point, the time when the line has to disappear and the color to the list of lines.
If the list of lines is empty, then the start point of the line is (0, 0) else the start point is the end point of the last line in the list:
if event.type == pygame.MOUSEBUTTONDOWN:
disappear_time = current_time + 2000
line_color = random.choice(colors)
prev_pt = (0, 0) if len(lines) == 0 else lines[-1]['end']
lines.append({'start': prev_pt, 'end': event.pos, 'time': disappear_time, 'color': line_color})
When the current time exceeds the time which is stored in time, then remove a point and a time form the lists of lines:
if len(times) > 0 and current_time > times[0]:
del lines[0]
Draw the lines by and circles in a loop:
screen.fill(BLACK)
for li in lines:
pygame.draw.line(screen, li['color'], li['start'], li['end'], 2)
pygame.draw.circle(screen, li['color'], li['start'], 5)
pygame.draw.circle(screen, li['color'], li['end'], 5)
See the example:
import pygame
import random
pygame.init()
size = width, height = 700, 700
screen = pygame.display.set_mode(size)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0,0,255)
WHITE = (255,255,255)
colors = (RED,GREEN,BLUE)
lines = []
running = True
myClock = pygame.time.Clock()
while running:
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
disappear_time = current_time + 2000
line_color = random.choice(colors)
prev_pt = (0, 0) if len(lines) == 0 else lines[-1]['end']
lines.append({'start': prev_pt, 'end': event.pos, 'time': disappear_time, 'color': line_color})
if len(lines) > 0 and current_time > lines[0]['time']:
del lines[0]
screen.fill(BLACK)
for li in lines:
pygame.draw.line(screen, li['color'], li['start'], li['end'], 2)
pygame.draw.circle(screen, li['color'], li['start'], 5)
pygame.draw.circle(screen, li['color'], li['end'], 5)
pygame.display.flip()
myClock.tick(60)
quit()

Creating a Python 3/Pygame "Press Any Key to Continue" Start Page

I know I'm probably making a very basic mistake here, I have been learning python for about a week and change, and I am trying to create a start screen for a text adventure game that allows the user to press any key to continue to the next screen which is expressed as a function, only it is not working despite attempting many permutations.
'''
import time
import pygame
import os
from pygame.locals import
pygame.init()
pygame.display.init()
pygame.mixer.init()
os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.display.set_caption("GK-Sierra\'s Text Adventure - Comic by Tom Siddell")
screen = pygame.display.set_mode((1800, 1000))
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
FUCHSIA = (255, 0, 255)
GRAY = (128, 128, 128)
LIME = (0, 128, 0)
MAROON = (128, 0, 0)
NAVYBLUE = (0, 0, 128)
OLIVE = (128, 128, 0)
PURPLE = (128, 0, 128)
TEAL = (0, 128, 128)
def title_screen():
title_screen_display = True
while title_screen_display:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
title_screen_display = False
font = pygame.font.Font('spiritmedium.ttf', 40)
logo_image = pygame.image.load('logo.jpg')
title_screen_image = pygame.image.load('tictoc.jpg')
title_screen_image2 = pygame.image.load('firehand.jpg')
title_screen_soundtrack = 'bythewall.mp3'
screen.fill(BLACK)
screen.blit(title_screen_image, (520, 100))
screen.blit(title_screen_image2, (0, 600))
screen.blit(logo_image, (600, 0))
text = font.render('Press Any Key To Continue', True, PURPLE, BLACK)
textrect = text.get_rect()
textrect.center = (900, 950)
screen.blit(text, textrect)
pygame.display.update()
pygame.mixer.music.load(title_screen_soundtrack)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
def input_screen():
input_screen_display = True
input = ""
font = pygame.font.Font('spiritmedium.ttf', 50)
while input_screen_display:
for evt in pygame.event.get():
if evt.type == KEYDOWN:
if evt.unicode.isalpha():
input += evt.unicode
elif evt.key == K_SPACE:
input = input + " "
elif evt.key == K_BACKSPACE:
input = input[:-1]
elif evt.key == K_RETURN:
input = ""
elif evt.type == QUIT:
return
screen.fill((0, 0, 0))
block = font.render(input, True, PURPLE)
rect = block.get_rect()
rect.center = screen.get_rect().center
screen.blit(block, rect)
pygame.display.flip()
if __name__ == "__main__":
name()
pygame.quit()
time.sleep(7)
quit()
title_screen()
input_screen()
'''
I had the same issue and believe me when I say I couldn't hold a shout in... because I couldn't.
Establish a variable
window = 0
if window == 0:
(Title screen)
if window > 0:
(Rest of windows, to avoid each click setting the window value to 1)
elif event.type == pygame.KEYDOWN:
window == 1

Timer in Pygame displaying same values

I'm trying to make a reaction time tester in Pygame, but the timer for each attempt is displaying 0. When the screen is red, pressing the down key is supposed to record the time taken. I'm not sure exactly where I'm supposed to place the timer, as I'm struggling to understand how the event loop actually works.
import pygame, sys
import random
from random import randint
import time
from time import sleep
from pygame.locals import *
FPS = 30
fpsClock = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)
pygame.display.set_caption('Test')
WHITE = (255, 255, 255)
RED = (255, 0, 0)
y = False
x = 0
while True:
if y is False:
y = True
DISPLAYSURF.fill(WHITE)
start = time.time()
sleep(randint(1,3))
else:
y = False
DISPLAYSURF.fill(RED)
time.sleep(2)
for event in pygame.event.get():
if x < 5:
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if y is True:
end = time.time()
print(end - start)
x += 1
else:
pygame.quit()
sys.exit()
pygame.display.update()
fpsClock.tick(FPS)
I'm not sure if it works exactly as you expect but it checks time reaction on red color in miliseconds, and it works without time.sleep()
import pygame
import random
# --- constants ---
FPS = 30
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# --- main ---
pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Test')
repeats = 5
testing = False
color = WHITE
current_time = pygame.time.get_ticks()
# random time to start test
start_test = current_time + random.randint(1, 3)*1000 # 1000ms = 1s
# - mainloop -
fps_clock = pygame.time.Clock()
while True:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if testing:
end = pygame.time.get_ticks()
print(end - start, 'ms')
repeats -= 1
# - other
if repeats == 0:
pygame.quit()
exit()
current_time = pygame.time.get_ticks()
# is it time to start displaying red color
if not testing and current_time >= start_test:
testing = True
color = RED
start = pygame.time.get_ticks()
# display white color
stop_test = current_time + 2*1000 # 1000ms = 1s
# is it time to stop displaying red color
if testing and current_time >= stop_test:
testing = False
color = WHITE
# random time to start next test
start_test = current_time + random.randint(1, 3)*1000 # 1000ms = 1s
# - draws -
screen.fill(color)
pygame.display.flip()
fps_clock.tick(FPS)

Categories