Pygame, I am trying to make a timer - python-2.7

I have created a game that has two cars who race each other by tapping buttons quicker than the other. So i want to make it where after the race ends it prints out how long it took for the winner of the race to make it to the finish line. I have tried using pygame.time.get_ticks() however that gives the time of how long since pygame.init() was called.

You can use pygame.time.get_ticks().
Set a start time and an end time and measure the difference:
import pygame as py
py.init()
clock = py.time.Clock()
start_time = py.time.get_ticks()
print "started at:",start_time
for i in xrange(0,30): #wait 1 second
clock.tick(30)
end_time = py.time.get_ticks()
print "finished at:",end_time
time_taken = end_time-start_time
print "time taken:",time_taken

Related

Is it possible to measure accurate Milliseconds time between few code statements using python?

I am developing a python application using Python2.7.
That application is using pyserial library to read some data bytes from serial port.
Using while loop to read 1 byte of data in each iteration. In each iteration
I have to measure execution time between statements if it is less than 10 ms wait for it to reach 10ms before starting next iteration. there are two questions here as follows:
Time measurement
What would be the best way to measure time between python statements to the accuracy (1ms or 2ms difference acceptable) of milliseconds.
Time delay
How can i use that measured time for delay in order to wait till total time is 10ms (total time = 10ms = code execution time+delay)
I have tried time library but it does not give a good resolution when in millisecond some time it does not give anything when small time duration.
for example:
import time
while uart.is_open:
uart.read()
start = time.time()
#user code will go here
end = time.time()
execution_time=end - start
if execution_time< 10ms:
remaining_time = 10ms - execution_time
delay(remaining_time)
You can get a string that is minutes:seconds:microseconds using datetime like so:
import datetime
string = datetime.datetime.now().strftime("%M:%S:%f")
And then turn it into a number to make comparison more handy:
m, s, u = string.split(":")
time_us = float(m)/60e6 + float(s)/1e6 + float(u)
In your example, that would look like this:
import datetime
def time_us_now():
h, m, s, u = (float(string) for string in datetime.datetime.now().strftime("%H:%M:%S:%f").split(":"))
return h/3600e6 + m/60e6 + s/1e6 + u
start = time_us_now()
# User code will go here.
end = time_us_now()
execution_time = end - start
Solution:
I have managed to get upto 1ms resolution by doing two things.
Changed (increased) the baud rate to 115200 from 19200.
Used time.clock() rather than time.time() as it has more accuracy and resolution.

Feedback requested: Global variables or classes in python2.7 countdown timer for Raspberry Pi

This is my first post to Stack Overflow. I started working with python 2.7 roughly 3 weeks ago and this is my first attempt at creating something in code (I have some basic experience with the Arduino IDE). Although the countdown timer now works for my purposes, I think I can make the code a lot better, especially where I keep declaring my global variable for color so that my digits appear to be flashing (red to black to red every second). I think I might need to use a class for color, but I don't know how. Would you have any tips for me?
This code is just bits and pieces collected and sewn together from code I found in online guides, mainly from this one: https://www.element14.com/community/community/code_exchange/blog/2012/12/17/raspberry-pi-workout-timer
Any feedback would be greatly appreciated, especially on any beginner mistakes I might be making.
All the best,
Katrien
digit_colour = pygame.Color(0, 255, 0)
# Colon between minutes and seconds
pygame.draw.rect(screen, digit_colour, pygame.Rect(left_offset + 2*(2*offset + digit_width), top_offset + offset + led_width / 2 - led_height, led_height, led_height))
pygame.draw.rect(screen, digit_colour, pygame.Rect(left_offset + 2*(2*offset + digit_width), top_offset + 3*offset + 3 * led_width / 2 - led_height, led_height, led_height))
print "Time is up!"
for j in range(0, timeIsUp):
# Draw time on screen
def colourChange():
global digit_colour
digit_colour = pygame.Color(255, 0, 0)
colourChange()
draw_time(screen, 0)
pygame.display.flip()
time.sleep(1)
def colourChange():
global digit_colour
digit_colour = pygame.Color(0, 0, 0)
colourChange()
draw_time(screen, 0)
pygame.display.flip()
time.sleep(1)
if __name__ == '__main__': main()
Hi I am new to and have experience with arduino IDE. You could've done a raw input asking you how long the countdown timer should last. And then you could have a loop with a minus -1 and a time.sleep(1) and a print of the time left example
import time
minutes = raw_input("Minutes? ")
seconds = raw_input("Seconds? ")
time = minutes*60 + seconds
while(remaintime = True)
time-1
time.sleep(1)
print(time," seconds left")
if time<0
remaintime = False
print("time out")
This is a much simpler countdown clock but it works!

Slow Python serial speed

I have connected an Arduino UNO to my raspberry pi and want to read from a connected Sensor with a Python Script.
When I try to read the sensor data from the Arduino IDE, it works perfectly fast, but with Python it is really slow.
This is my code:
import serial
from subprocess import call
from time import sleep
ser = serial.Serial('/dev/ttyACM0')
ser.baudrate = 9600
a = 0
stop = False
file = open("PulseData/MasterArrayData.txt","w")
if(ser.isOpen() == False):
ser.open()
print("Start scanning")
while stop == False:
test = ser.readline()
try:
testInt = int(test)
if testInt > 100 and testInt < 800:
print test
file.write(str(testInt))
file.write("\n")
a = a+1
except ValueError:
print "Not an integer"
if(a == 400):
stop = True
sleep(0.1)
file.close()
call(["./main", "PulseData/MasterArrayData.txt"])
I already tried to use a higher baud rate, or a shorter sleeping time, without success.
I've read that the speed can be improved with PyTTY, but unfortunately I didn't find any documentation about that.
I appreciate any help.
From comment by jasonharper:
Sleeping for a tenth of a second between readings is an absolute guarantee that you will get less than 10 readings per second. The occasional garbage value you're getting happens when the serial port buffer inevitably overflows and characters get lost.

How can I fix the timer to avoid values below 0 seconds?

while gamerunning:
timerstart = time.time()
posy2 += 3
if posy2 >= window_height:
posy2 = -50
randomx = random.randrange(0, window_width - 50)
if health == 0:
gameover = True
while gameover:
timerend = time.time()
timer = timerend - timerstart
print timer
screentext("Game over, press esc to quit or press R to retry", black)
pygame.display.update()
I'm trying to figure out how to correctly implement a timer in python but I get values below 0 seconds when I print it out so I'm assuming that the timer variable is only printing out the time it takes for the python interpreter to run the code inside my gameover loop. My question is how can I fix this problem and make a proper timer that runs while the gamerunning loop is going and end once it's game over. I'm rather new to Python so I'm not sure what other modules I can really use to accomplish this other than time.
Try moving timerstart = timer.time() outside the loop that runs your game. In your example that is before while gamerunning:. The problem was that in every loop the variable was being reset, thus the results you got.
We can't see the rest of your code in that image, but in this case in order to update the start time between games you have to update timerstart after/if the player selects 'R' to retry the game. Otherwise your game ends.

How can i make it so the program progresses while a 'while loop' is running a timer (python)

I need to know how i can enter user input while this while loop counting time is running. I know my program is not efficient nor organized as I am new to python. A simple but longer fix is better than a short fix that I would not understand.
import time
print 'Welcome To the Speedy Type Game!'
time.sleep(1)
print "You're objective is to win the game by typing the specific word before the time runs out"
print "Don't forget to press 'enter' after typing the word!!!!"
print "For round 1 you will have 5 seconds"
null = raw_input('Press enter when you are ready to start')
print '3'
time.sleep(1)
print '2'
time.sleep(1)
print '1'
time.sleep(1)
print 'GO'
C = 'poop'
x = 5
while C in ['poop']:
x = x - 1
time.sleep(1) #This is where my program comes to a halt.
C = raw_input("Print the word 'Calfornia': ") #I dont know how to make the program progress to here without stopping the timer above.
if x < 0:
print 'You have failed, game over!'
else:
print 'Good Job! let us move to the next round!'
There is no easy way to do this in Python - a single process is running at a time, so without e.g. threading (see https://stackoverflow.com/a/2933423/3001761) you can't overlap user input with counting. An easier approach might be:
def test(word, limit=5):
started = time.time()
while True:
result = raw_input("Type {0!r}: ".format(word))
finished = time.time()
if result == word and finished <= started + limit:
print 'Good Job! let us move to the next round!'
return True
elif finished > started + limit:
break
print 'Wrong, try again.'
print 'You have failed, game over!'
return False
Then call e.g.:
>>> test("California")
Type 'California': California # typed quickly
Good Job! let us move to the next round!
True
>>> test("California")
Type 'California': foo # typed wrongly but quickly
Wrong, try again.
Type 'California': California # typed quickly
Good Job! let us move to the next round!
True
>>> test("California")
Type 'California': foo # typed wrongly and slowly
You have failed, game over!
False
>>> test("California")
Type 'California': California # typed slowly
You have failed, game over!
False