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

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.

Related

Lua: How do you update a variable that's in an event?

The issue I'm running into is that my variable isn't updating after an event. Here is my code:
local Players = game:GetService("Players")
local intermission = 15 -- time in seconds
local AmountOfPlayers = #Players:GetPlayers() -- starts at zero
local minPlayers = 1
Players.PlayerAdded:Connect(function(Player) -- updates amount of players in server
AmountOfPlayers = AmountOfPlayers + 1
end)
Players.PlayerRemoving:Connect(function(Player) -- updates amount of players in server
AmountOfPlayers = AmountOfPlayers - 1
end)
Below, this if-statement is not running since AmountOfPlayers is not equal to minPlayers.
while intermission > 0 do
if AmountOfPlayers >= minPlayers then
print("SUCCESS")
end
end
I have a scope issue of the variable AmountOfPlayers. I'm not sure how to fix this, so any suggestions will be appreciated. Thank you for your help!
You forgot to add a wait() in your while loop. This is most likely what leads to the script crashing and not working. So it should look like:
while intermission > 0 do
wait()
if AmountOfPlayers >= minPlayers then
print("SUCCESS")
end
end
OR
If that isn't the problem, instead of making:
local AmountOfPlayers = #Players:GetPlayers()
Instead:
local AmountOfPlayers = Players:GetChildren()
And Remove the two functions.

How to redraw a curve to Photoshop with Autoit?

I want to draw a specific curve line to Photoshop or to mspaint. This drawing action should be saved for the possibility to redraw that curve in the exact same way. How can I do it with Autoit? Is there a recording and play mechanism? As far as I read, the AU3 recorder is not available anymore.
Photoshop is just an example. I want to be able to do that kind of drawing record for different purposes and programs. Maybe also for online image editors or something.
I am not that familiar with Autoit yet. I do not expect a full code example, maybe you can give me an idea - that would be very helpful.
Currently I tried a bit with mouse functions like MouseDown, MouseMove etc. and it is quite funny, but i do not really have a concept to record and redraw these mouse actions.
If I have to clarify more please let me know - i will do my best to be precise.
I recommend using two scripts, one for recording and the second to replay recorded actions.
Code for the recording:
; declaration
Global $sFileCoordinates = #ScriptDir & '\RecordedMouseMoveCoordinates.txt'
Global $iRecordingDurationInSeconds = 10
Global $iXSave, $iYSave
; functions
Func _recordMouseMoveCoordinatesToFile()
Local $aPos = MouseGetPos()
If $aPos[0] <> $iXSave Or $aPos[1] <> $iYSave Then
FileWrite($hFile, $aPos[0] & ',' & $aPos[1] & #CRLF)
Local $aPos = MouseGetPos()
$iXSave = $aPos[0]
$iYSave = $aPos[1]
EndIf
Sleep(80)
EndFunc
; processing
Sleep(4000) ; wait 4 seconds to place your mouse to the start position
Global $hFile = FileOpen($sFileCoordinates, 1 + 256)
Global $hTimer = TimerInit()
While Round((TimerDiff($hTimer) / 1000), 1) <= $iRecordingDurationInSeconds
ToolTip(Round((TimerDiff($hTimer) / 1000), 1))
_recordMouseMoveCoordinatesToFile()
WEnd
FileClose($hFile)
Recording will start after a 4 second delay. This should allow to move your mouse to the start point of your drawing action.
Global $iRecordingDurationInSeconds = 10 means your drawing action should be finished in 10 seconds (a tooltip displays remaining seconds). And here the seconds script.
Code to redraw curve:
; declaration
Global $sFileCoordinates = #ScriptDir & '\RecordedMouseMoveCoordinates.txt'
; functions
Func _getFileContent($sFile)
Local $hFile = FileOpen($sFile, 256)
Local $sFileContent = FileRead($hFile)
FileClose($hFile)
Return $sFileContent
EndFunc
Func _drawRecordedMouseMoveCoordinatesFromFile($sContent)
Local $aFileContent = StringSplit($sContent, #CRLF, 1)
Local $iX = StringSplit($aFileContent[1], ',')[1]
Local $iY = StringSplit($aFileContent[1], ',')[2]
MouseMove($iX, $iY, 4)
MouseDown('left')
For $i = 1 To $aFileContent[0] Step 1
If $aFileContent[$i] <> '' Then
Local $iX = StringSplit($aFileContent[$i], ',')[1]
Local $iY = StringSplit($aFileContent[$i], ',')[2]
MouseMove($iX, $iY, 4)
EndIf
Next
MouseUp('left')
EndFunc
; processing
Sleep(2000) ; wait 2 seconds till start
Global $sFileContent = _getFileContent($sFileCoordinates)
_drawRecordedMouseMoveCoordinatesFromFile($sFileContent)
There is a start delay of 2 seconds. All saved coordinates will be executed in the same way recorded. It starts with MouseDown('left'), then the mouse movements to MouseUp('left').
Notice:
This approach isn't really robust because of the coordinates which aren't relative to your window. Please see Opt('MouseCoordMode', 0|1|2) in the help file for more information. If you want to draw more than just one line or curve this approach isn't the best. But as your question describes only that requirement it should be fine.

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!

Pygame - How to make the number of obstacles that need to be dodged increase

I want to program my game in such a way that as your points progress, the obstacles that are approaching the player are faster and there are more of them at once. I've played around with my code and have done some research, but everything I try seems to fail. Python isn't giving me any errors, it is just that more obstacles are not appearing.
enemy = pygame.image.load('tauros1.png')
....
def things(thingx, thingy):
gameDisplay.blit(enemy, (thingx, thingy))
....
thing_starty = -100
thing_speed = 7
thing_width = 42
thing_height = 43
thing_startx = random.randrange(192, displayWidth - 192)
dodged = 0
....
things(thing_startx, thing_starty)
thing_starty += thing_speed
if thing_starty > displayHeight:
thing_starty = 0 - thing_height
thing_startx = random.randrange(192, ((displayWidth - 192) - thing_width))
dodged += 1
thing_speed += 2
These are the components of the code that make up the enemy base. I've tried implementing while loops, for loops, and embedded if statements. I can't think of anything else to try.
I can't give you a complete answer with code specific for your game, but I can give you a few tips to make the whole thing simpler, which will in turn give you more control over all the elements in your game.
First off, you should have a "container" for your sprites. You could have one for everything or, better, have them grouped in a way that makes sense. For example you might have environment sprites, enemies, allies, HUD, etc. What determines how you group your sprites is essentially what they do: similar-behaving sprites should be grouped together.
You could use an array, but since you're using pygame I'd suggest pygame.sprite.Goup - this implements methods like .update and .draw which will greatly improve the comprehensibility of your code - and therefore your control over the game.
The you should have a "game loop" (though I'm guessing you already do), which is the place where everything happens, at each frame. Something like:
# This code is only intended as a generic example. It wouldn't work on it's
# own and has many placehoders, of course. But you can adapt your
# game to have this kind of structure.
# Game clock keeps frame rate steady
theClock = pygame.time.Clock()
# Sprite groups!
allsprites = pygame.sprite.Group()
environmentSprites = pygame.sprite.Group()
enemySprites = pygame.game.Group()
# Initially populate sprite groups here, e.g.
environmentSprites.add(rockSprite)
allsprites.add(rockSprite)
# ...
# Game loop
while True:
theClock.tick(max_fps)
# Add new enemies:
spawn_enemies(enemySprites, allSprites, player_score)
# Update all sprites
environmentSprites.update()
enemySprites.update()
playerSprite.update()
# ...and draw them
allSprites.draw(background)
window.blit(background)
pygame.display.flip()
This way you can keep your game loop short (as in not many lines, externalize most of the actual work to functions and methods) and therefore have more control over what happens.
Achieving what you wanted is now much, much simpler. You have a single function which does that, and only that, which means that you can focus on just how you want the enemies to spawn in relation to the player_score. Just an example off the top of my head:
def spawn_enemies(enemyGroup, all, player_score):
# Calculate the number of enemies you want
num_enemies = player_score / 100
for i in range(num_enemies):
# Create a new enemy sprite instance and
# set it's initial x and y positions
enemy = EnemyClass()
enemy.xpos = random.randint(displayWidth, displayWidth + 100)
enemy.ypos = random.randint(0, displayHeight)
enemy.velocity = (player_score / 100) * base_velocity
# Add the sprite to the groups, so it'll automatically
# be updated and blitted in the main loop!
enemyGroup.add(enemy)
all.add(enemy)
I suggest you read up on the pygame docs and tutorials for things like pygame.sprite.Sprite, pygame.sprite.Group and pygame.time.Clock if you haven't already. I found them really useful when developing my games. The tutorialy also give a pretty good idea of how the game is best structured.
Hope this helps.

Pygame, I am trying to make a timer

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