Pygame simple score system - python

I have created a simple score system for my pygame. but it's pausing the game. I know it's because of time.sleep but I don't how to sort it out.
The score system is to +100 every 5 seconds while start is true, code:
while start == True:
time.sleep(5)
score = score + 100
Full code with indentation: http://pastebin.com/QLd3YTdJ
code at line : 156-158
Thank you

Instead of using sleep, which stalls the game until time has elapsed, you want to count up an internal timer with the number of seconds which have passed. When you hit 5 seconds, increment the score and then reset the timer.
Something like this:
scoreIncrementTimer = 0
lastFrameTicks = pygame.time.get_ticks()
while start == True:
thisFrameTicks = pygame.time.get_ticks()
ticksSinceLastFrame = thisFrameTicks - lastFrameTicks
lastFrameTicks = thisFrameTicks
scoreIncrementTimer = scoreIncrementTimer + ticksSinceLastFrame
if scoreIncrementTimer > 5000:
score = score + 100
scoreIncrementTimer = 0
This could easily be improved (what if your frame rate is so low there's more than 5 seconds between frames?) but is the general idea. This is commonly called a "delta time" game timer implementation.

If i understand you correctly you dont want the while True: score += 100 loop to block your entire program?
You should solve it by moving the score adding to a seperate function
and use the intervalfunction of APScheduler http://packages.python.org/APScheduler/intervalschedule.html
from apscheduler.scheduler import Scheduler
# Start the scheduler
sched = Scheduler()
sched.start()
# Schedule job_function to be called every 5 seconds
#sched.interval_schedule(seconds=5)
def incr_score():
score += 100
This will result in APScheduler creating a thread for you running the function every 5 seconds.
you might need to do some changes to the function to make it work but it should get you started at least :).

Related

Script B slows down script A

I am working with Python 2.7 on a Raspberry Pi.
I run a script A which is a for-loop, taking pictures every 30 seconds. Normally, for each iteration, it takes about 5 seconds to capture the scene and save it, and then it sleeps (for about 25 seconds) until the next iteration.
After some time I run a script B which is calculating stuff based on the images taken by script A. So the two scripts are running at the same time. I am not using subprocess or anything, just executing the two scripts separately.
My problem is : when script B is running, script A is slowed down a lot, so that sometimes the first 5 seconds turn into 25-30 seconds and then one iteration can last 40 seconds or more !
Do you know why durations are not respected in script A, and how I can solve this issue ?
Thanks :) !
I believe if you are in a Linux environment you can use nice command in order to balance the cpu usage.for example :
nice --12 script.py
the number above represents the amount of being nice to cpu.it is between -20 and +19.
If the calculation amount of "script B" is nearly always the same you could subtract this time in seconds from the sleep timer.
2.You also could take the runtime in seconds of the scripts, that you will output at the end of their execution. The problem is the python programm will wait for a finished script before continuing.
import subprocess
import time
counter = 0
script_a_runtime = 0
script_b_runtime = 0
while True:
counter += 1
script_a = 0
script_b = 0
script_a_runtime = int(subprocess.check_output(['scripta']))
if counter >=5:
counter = 0
script_b_runtime = int(subprocess.check_output(['scriptb']))
sleeptime = 30 - script_a_runtime - script_b_runtime
if sleeptime:
time.sleep(sleeptime)
3.Timers
import datetime
import time
import subprocess
script_a_runtime = 0
script_b_runtime = 0
while True:
counter += 1
start_a = datetime.datetime.now()
subprocess.check_output(['script_a'])
finish_a = datetime.datetime.now()
script_a_runtime = finish_a - start_a
if counter >= 5:
counter = 0
start_b = datetime.datetime.now()
subprocess.check_output(['script_b'])
finish_b = datetime.datetime.now()
script_b_runtime = finish_b - start_b
sleeptime = 30 - script_a_runtime.seconds - script_b_runtime.seconds
if sleeptime:
time.sleep(sleeptime)
I dont think its a good idea to run those scripts that depend on each other side by side. Also if scriptA/B is not finished before it should be run again there may arise problems.

Python Tkinter Tk root.after Delay

I'm trying to do a chess clock using tkinter, and to do so i'm using the root.after method from the class Tk of tkinter. When the program starts, it runs really well, but after a while the clock start to get slower and slower, but if i start shaking my mouse, the clock starts to run fast again. For a clock, time precision is crucial, so i can't afford to run the program in the way that is working now. How can i solve this problem?
def RunClock(self):
"""
Method that runs and change the clock info
"""
#t0 = time.time()
if self.playing:
#Time remaining in milliseconds
clock = self.clock
minutes = clock//60000
clock %= 60000
sec = clock//1000
clock %= 1000
mil = clock//10
#If the turn is of player 1
if self.turn == 1:
self.WriteClock(self.canvas1, self.play1, "%.2i:%.2i:%.2i"%(minutes, sec, mil))
else:
self.WriteClock(self.canvas2, self.play2, "%.2i:%.2i:%.2i"%(minutes, sec, mil))
#tf = time.time()
#deltat = (tf - t0)
#s = 1 - deltat
self.rel -= 1
#if s > 0:
# time.sleep(s/1000)
#else:
# self.rel += s*1000
self.root.after(1, self.RunClock)
Note: The time to run the function is very low (you can calculate it with the commented tf and t0 variables), so i didn't even consider it in the time interval
As Brian pointed out reducing the time interval will likely be the easiest solve to your question. Alternately though, you could try running your timer separately on it's own thread and having it run asynchronously and send it threading events as is discussed here:
Python threading.timer - repeat function every 'n' seconds

How do you create a timer in Python 2.7?

I'm currently programming a brick-breaker clone using the Pyglet library and I would like to make a timer that counts up to 20 seconds for the game's 'bonuses'(i.e. longer paddle, faster paddle movement, a larger ball). I've been digging the internet as hard as I can but I couldn't find the answer.
import threading
bonuses_count = 0
def count_bonuses():
global bonuses_count
# paddle = count(paddle) # something your logic part here
bonuses_count += 20
print "counting bonuses :- ", (bonuses_count)
t = threading.Timer(20.0, count_bonuses).start()
t = threading.Timer(20.0, count_bonuses)
t.start()
Well i don't know your logic of counting bonuses but i think you can acheive 20 seconds timer by creating a thread which will executing after every 20 seconds.
Here i have created function count_bonuses that will contain your game logic and get executed after every 20 seconds.
You can create your own stopflag if you want to stop this thread or create an KeyboardInterrupt to stop the thread with keyboard intruption based on your gamming logic.
counting bonuses :- 20
counting bonuses :- 40
counting bonuses :- 60
counting bonuses :- 80
Try this.
import mx.DateTime as mt
import time
def settime():
st=mt.now()
while(True):
time.sleep(1)
tt=mt.now()
if (int((tt-st).seconds)==20):
print 'level up'
st=mt.now()
elif (int((tt-st).seconds)>20):
print 'logic error'
else:
print int((tt-st).seconds)

How can I add a timer to my game?

I'm working on a game that is sort of like a simple Galaga-esk game. Although, they only move once in a while (something else I can't get working, but that's something different). So, since they don't move on their own, I want a way to add a timer to the game, but I can't seem to find anything on this. Here's what I have for my timer and the surrounding code to reset for each level so far. Will something like this work where I have it?
from livewires import games, color, random, time
start = time.time()
for items in enemies:
items.destroy()
if Enemy_amount > 0:
display_balloons()
elif Enemy_amount == 0 and (time.time() - start <= 120):
start = time.time()
level += 1
Enemy_amount = load_enemies()
#Just telling the code to load the next group of enemies.
The value of start is going to be a number like 1398354442, which is the number of seconds that have passed since January 1, 1970.
If you want to figure out the elapsed time between two events, you'll need to subtract. Perhaps something like this?
elif Enemy_amount == 0 and (time.time() - start <= 120):
start = time.time() # update start variable to the current time

Python loop delay without time.sleep()

In an MMO game client, I need to create a loop that will loop 30 times in 30 seconds (1 time every second).
To my greatest disappointment, I discovered that I can not use time.sleep() inside the loop because that causes the game to freeze during the loop.
The loop itself is pretty simple and the only difficulty is how to delay it.
limit = 31
while limit > 0 :
print "%s seconds remaining" % (limit)
limit = limit -1
The python libs exist in the client as .pyc files in a separate folder and I'm hoping that I can avoid messing with them.
Do you think that there is any way to accomplish this delay or is it a dead end?
Your game has a main loop. (Yes, it does.)
Each time through the loop when you go to check state, move the players, redraw the screen, etc., you check the time left on your timer. If at least 1 second has elapsed, you print out your "seconds remaining" quip. If At least 30 seconds has elapsed, you trigger whatever your action is.
You can't do it without blocking or threading unless you are willing to lose precision...
I'd suggest sometime like this, but threading is the correct way to do this...
import time
counter = 31
start = time.time()
while True:
### Do other stuff, it won't be blocked
time.sleep(0.1)
print "looping..."
### When 1 sec or more has elapsed...
if time.time() - start > 1:
start = time.time()
counter = counter - 1
### This will be updated once per second
print "%s seconds remaining" % counter
### Countdown finished, ending loop
if counter <= 0:
break
or even...
import time
max = 31
start = time.time()
while True:
### Do other stuff, it won't be blocked
time.sleep(0.1)
print "looping..."
### This will be updated every loop
remaining = max + start - time.time()
print "%s seconds remaining" % int(remaining)
### Countdown finished, ending loop
if remaining <= 0:
break

Categories