I'm writing a basic game where you use the mouse to dodge stars, but I can't get a certain part to work properly.
I'm trying to make it so that after 10 seconds of playing you beat the stage and if you lose, the 10 second timer resets.
Here is what I'm trying:
def time_pass(self):
self.time_passed = time.clock()
print self.time_passed
if self.time_passed > 10:
self.state = 3
This method only runs if self.state == 2 which is the main game, and if self.state == 3 you win, and the losing screen is if self.state == 0. But what happens is I run the game and when I click play it runs self.state 2 and starts the timer, and if I lose the timer keeps going. So then when I go back to the main screen and press play again, it picks up where the timer left off instead of resetting.
If you want to see the full game code:
Star Dodger Git
Thanks in advance.
-ChristianCareaga
Save the time into say start_time when you set self.state = 2.
Change self.time_passed > 10: to if self.time_passed > (start_time + 10):
The game will end 10 after starting.
IOW, don't reset the clock.
Related
I want to write a bot that will simulate mouse movements when user is away for more than 5 minutes and stay put when user takes control i.e. moves the mouse.
I have written following code as a part of the program.
Here is the link to my old program which clicks at given points periodically. The problem with this program is I have to start the program when I want to go somewhere and after returning close the program in order to resume working.
Here is the one of the module I wrote for the new program which detects whether mouse is moving or not.
import win32api
from time import sleep
print("starting engine.")
count = 0
while(True):
savedpos = win32api.GetCursorPos()
if count>20*5:
break
sleep(1)
curpos = win32api.GetCursorPos()
if savedpos == curpos:
savedpos = curpos
print("Mouse is steady.")
else:
print("Mouse is moving.")
count += 1
I wont be writing the code but I have the Idea to solve the problem
you use pyautogui.position() to keep checking the position and if it doesnt change position for 300 seconds you move it
I wrote following code referring other Stackoverflow posts.
This code waits 4 minutes for mouse being steady. Whenever mouse is moved, timer is reset to zero.
import win32api
from time import sleep
import pyautogui as gui
print("starting engine.")
count = 0
savedpos = win32api.GetCursorPos()
def actions():
print(gui.size())
while True:
#toast.show_toast("ROBOT V2 !", "Robot is active.", threaded=False, icon_path=None, duration=2)
gui.click()
gui.press('home')
gui.moveTo(541, 142, 0.25) # Money Transfer dropdown
gui.click()
sleep(0.5)
gui.moveTo(541, 172, 0.25) # Money Transfer link
gui.click()
sleep(5)
cond()
def cond():
count = 0
while True:
savedpos = win32api.GetCursorPos()
sleep(0.5)
curpos = win32api.GetCursorPos()
if savedpos == curpos:
savedpos = curpos
print("Mouse is steady. Elapsed time: ", (count+1)/2, " seconds.")
count += 1
if count >= 480: # if count is greater than 60 it means timeout will occur after mouse is steady for more than
# 240 seconds i.e. 4 minutes. (approx.)
print("User away for more than 4 minutes, taking control of the system.")
actions()
break
else:
pass
else:
print("Mouse is moving.")
count = 0
cond()
I am making a game in which u have to carry move objects from one place to another. I can move my character to the zone in which I need to put something. I want the player to wait in the zone for 5 secs before the object is placed there, however, if i do this you cannot move anymore if u decide u dont want to place the object in the zone as the whole script would be paused.
Is there a way to make one part of the script wait while the rest of it runs?
Every game needs one clock to keep the game loop in sync and to control timing. Pygame has a pygame.time.Clock object with a tick() method. Here's what a game loop could look like to get the behaviour you want (not complete code, just an example).
clock = pygame.time.Clock()
wait_time = 0
have_visited_zone = False
waiting_for_block_placement = False
# Game loop.
while True:
# Get the time (in milliseconds) since last loop (and lock framerate at 60 FPS).
dt = clock.tick(60)
# Move the player.
player.position += player.velocity * dt
# Player enters the zone for the first time.
if player.rect.colliderect(zone.rect) and not have_visited_zone:
have_visited_zone = True # Remember to set this to True!
waiting_for_block_placement = True # We're now waiting.
wait_time = 5000 # We'll wait 5000 milliseconds.
# Check if we're currently waiting for the block-placing action.
if waiting_for_block_placement:
wait_time -= dt # Decrease the time if we're waiting.
if wait_time <= 0: # If the time has gone to 0 (or past 0)
waiting_for_block_placement = False # stop waiting
place_block() # and place the block.
Example with threading:
from threading import Thread
def threaded_function(arg):
# check if it's been 5 seconds or user has left
thread = Thread(target = threaded_function, args = (10, ))
if user is in zone:
thread.start()
# continue normal code
Another potential solution is to check the time the user went into the zone and continuously check the current time to see if it's been 5 seconds
Time check example:
import time
entered = false
while true:
if user has entered zone:
entered_time = time.time()
entered = true
if entered and time.time() - entered_time >= 5: # i believe time.time() is in seconds not milliseconds
# it has been 5 seconds
if user has left:
entered=false
#other game code
everything works except the next song doesn't play after the first is finished.
import os, random
from pygame import mixer
from pynput import keyboard
startup = 0
pause = 0
volume = 0.5
def Picker():
global startup
global volume
startup += 1
if startup > 1:
ThisSong = random.choice(os.listdir("C:\\Users\\...\\Music"))
NextSong = random.choice(os.listdir("C:\\Users\\...\\Music"))
ThisSong = NextSong
if ThisSong != NextSong:
mixer.init()
mixer.music.load("C:\\Users\\...\\Music" + ThisSong)
mixer.music.play(0)
mixer.music.set_volume(volume)
while mixer.music.get_busy():
def on_press(key):
global pause
global volume
if key == keyboard.KeyCode(char='-'):
volume -= 0.1
if volume < 0.1:
volume = 0.1
mixer.music.set_volume(volume)
if key == keyboard.KeyCode(char='='):
volume += 0.1
if volume > 1:
volume = 1
mixer.music.set_volume(volume)
if key == keyboard.KeyCode(char='['):
pause += 1
if pause == 1:
mixer.music.pause()
pause = 2
if pause == 3:
mixer.music.unpause()
pause = 0
with keyboard.Listener(on_press=on_press) as listener: listener.join()
else:
Picker()
else:
pass
Picker()
Picker()
screenshot of code
I can't get it to work, i'm very new to python so i'm probably missing something
obvious
Before starting: Thx #JGreenwell for copying the code.
Ok, so first, I’ll help you clean your code.
Things that are wrong
Having all that ThisSong and NextSong things: It won’t get saved when you restart Picker(). Either just have ThisSong, or place the ThisSong and NextSong assignment with the volume and pause variables:
.
pause = 0 # this is a problem! Next point
volume = 0.5
ThisSong = random.choice(...)
NextSong = random.choice(...)
The pause variable should be a boolean (True/False) and the pausing code should be like this:
.
pause = not pause
if pause:
# pause
else:
# unpause
Also, it would ideally be called paused
on_press and the Listener declaration should be outside the while loop, because otherwise they just keep being declared every time it loops. Then you should import time and put time.sleep(500) or something like that in the while loop, so that it doesn’t check every fraction of second.
As for the next song not playing, I don’t really know, but I’d suggest entering Picker() in the shell after the program has run (python -i script.py from CMD, IDLE leaves you in a shell by default). I would also suggest really following recommendation #3 as having them in the loop may break the loop and stop it from finishing. Most importantly, I would ask you to debug your code by adding print in every step of your code:
print(1)
if something:
print(2)
etc...
And seeing where it blocks
P.S.: The random dots are because you can’t have code in lists, so I had to exit the list.
Working solution, incase anyone else has the same problem as me in the future :)
from pygame import mixer
from pynput import keyboard
import threading
import random
import os
paused = 0
def player():
song = random.choice(os.listdir("C:\\users\\...\\desktop\\music"))
mixer.init()
mixer.music.load("C:\\users\\...\\desktop\\music\\" + song)
mixer.music.play(0)
while mixer.music.get_busy():
pass
else:
player()
def main():
t = threading.Thread(target = player, name = 'thread1', args = ())
t.start()
main()
def on_press(key):
global paused
if key == keyboard.KeyCode(char='['):
paused = not paused
if paused:
mixer.music.pause()
else:
mixer.music.unpause()
with keyboard.Listener(on_press=on_press) as listener: listener.join()
I am doing a Photobooth with printing (and uploading) option.
This project presents itself like this:
Start screen with instructions --> preview results screen --> user chooses either to print or restart (or the timeout chooses restart for the user)
If the user chooses print then, printing is done, and a message is displayed (sleep method) before going back to the start screen.
Now, i have one main issue:
Getting back to the start screen...
The simplified code is here:
def PreviewMontage(MontageFile):
global LastTap
LastTap = time.time()
print("Session ID:", SessionID)
print("Show something.")
preview = pygame.image.load(MontageFile)
PILpreview = Image.open(MontageFile)
previewSize = PILpreview.size # returns (width, height) tuple
#added /1.5
ScaleW = AspectRatioCalc(previewSize[0]/1.5, previewSize[1]/1.5, SCREEN_HEIGHT)
preview = pygame.transform.scale(preview, (ScaleW, SCREEN_HEIGHT))
SetBlankScreen()
background.blit(preview, (SCREEN_WIDTH/2-ScaleW/2, 0))
PrintScreen()
#inserting conditions here - get mouse
camera.stop_preview()
UpdateDisplay()
Wait()
return
def Wait():
clock = pygame.time.Clock()
waiting = True
while waiting:
time = 60
time = time -1
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFTMOUSEBUTTON:
x, y = event.pos
print("You pressed the left mouse button at (%d, %d)" % event.pos)
LeftMouseButtonDown(x, y)
if time == 0:
waiting = False
return
I encounter the problem of getting back to the main screen, it seems that the Wait() function never ends...
You are setting the time to 59 on every iteration of your while loop. It means time never reaches 0 and the loop is infinite.
Fix it by declaring time = 60 outside the while()
I'm trying to play background music and the music keeps on starting. I tried to use music.busy, but I can't figure it out. I want it to check if sound/music is playing, then I want it to print "music is playing". If a sound/music isn't playing I want it to start up a new song and loop it.
def musica():
if pygame.mixer.music.get_busy() == True:
print("music is playing")
if pygame.mixer.music.get_busy() == False:
music.play(loops=-1)
An easy way to play looped sounds is winsound. See the python documentation (https://docs.python.org/3.4/library/winsound.html) and set the parameter 'flags' in PlaySound to winsound.SND_LOOP.
I ended up doing this it is more of a workaround but it works:
m = 0
def musica():
global m
if m == 0:
music.play(loops=-1)
m = 1
if you are looking to play a sound during a specific event in a loop (e.g. opening a menu), it is possible to play sound only once by using timers.
example:
sound = pygame.mixer.Sound('sound.wav')
playSound = True
playSound_counter = 0
while:
playSound_counter += 1
if playSound_counter >= 11:
playSound = True
playSound_counter = 0
if i.rect.collidepoint(mouse_position):
if playSound == True :
sound.play()
playSound = False
elif playSound_counter == 10:
playSound_counter = 0
This is essentially two timers - one sets sound back to True every 11 secs, another negates it while mouse is over a rect.
by "playing once" i meant to be able to play it again in a controlled way when a certain event is triggered