How to increase a integer every second [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I'm making a dodging game in Python where I want the score to increase by 1 every second, but the problem is that I don't know how. It would be nice to find a solution where I don't have to change too much of my code.
Can someone please help?

As you iterate through the game loop, you can check the current time with the time library. You can then check if it has been a second since the last time you awarded a point.
It might look something like this:
import time
points = 0
currentTime = time.time()
previousPointAwardedTime = currentTime
while gameRunning == True:
...
currentTime = time.time()
if (currentTime - previousPointAwardedTime) >= 1:
points += 1
previousPointAwardedTime = currentTime

you can try using asyncio
import asyncio
score = 0 # starting game with a score of zero
async def s():
global score
score += 1 #increasing score by 1
await asyncio.sleep(1) #waiting for 1 second
while True: #while game is running
asyncio.run(s()) #calling function
print(score) #printing score

Related

Each time a number (health) decreased, execute a code [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
So basically I'm working on a python script to read health in a game. I use the following libraries.
import numpy as np
import pytesseract
import cv2
from PIL import ImageGrab
I have succeeded to read a health number in real-time screen and change it to int in python. However, I still cannot come out with an idea on how to execute a code whenever my health in the game decreasing or in another term each time my health drop.
conf = r'--oem 3 --psm 6 outputbase digits'
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
def screenToData():
while (True):
screen = np.array(ImageGrab.grab(bbox=(350, 150, 550, 300)))
cv2.imshow("window", cv2.cvtColor(screen, cv2.COLOR_BGR2RGB))
data = pytesseract.image_to_data(cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY), lang='eng', config=conf)
# print(data)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
for x, box in enumerate(data.splitlines()):
if x != 0:
box = box.split()
# print(box)
if len(box) == 12:
if int(box[11]) == 100:
print("Full health")
elif int(box[11]) <= 100:
print("Nope")
screenToData()
First step, in your code you should have a variable called health, this meakes the code more readable.
To determine when your health is dropping, each time you loop you just need to compare your current health to the last reading, so maybe add a variable new_health to compare to health.
health = 100
while True:
new_health = read_health()
if new_health < health:
# execute code
health = new_health

How to add 1 to a number every 2 minutes? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
How can I add 1 to a variable every 2 minutes it until reaches 100.
The program will start the number from 0 and it will add every 1 number in every 2 minutes until it reaches 100.
2 min later
0/100 ------> 1/100
Use sleep function from time module
from time import sleep
i = 0
while i <= 100:
sleep(120)
i += 1
I used sleep!
from time import sleep
for i in range(100):
sleep(120)
# print(i)
If you need to make a progressbar, you can also check tqdm.
from tqdm import tqdm
import time
for _ in tqdm(range(100)):
time.sleep(120)
One line solution:
from time import sleep
for t in range(100): time.sleep(120)
I believe all solutions presented so far are thread locking??
import asyncio, time
async def waitT(tWait, count):
print(count)
while count < 100: #The 100 could be passed as a param to make it more generic
await asyncio.sleep(tWait)
count = count + 1
print(count)
return
async def myOtherFoo():
#Do stuff in here
print("aaa")
await asyncio.sleep(2)
print("test that its working")
return
async def main(count):
asyncio.gather(myOtherFoo(), waitT(120, count)) #Obviously tweak 120 to whatever interval in seconds you want
return
if __name__ == "__main__":
count = 0
asyncio.create_task(main(count))
A simple, and hopefully readable, async solution. Doesn't check for running loops etc - but should open you up to a range of possibilities for acting between each update in your counter.

Making Hangman in Processing [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I am currently trying to make the game Hangman using Python in Processing. I have the code to run the game, as well as code for some visuals. The problem is combining the code I've written so far. The game code is written in standard Python, while the visuals code is written in Processing. Can someone please help me combine the two and make a working Hangman game in Processing? Thank you in advance.
Code for game
import time
import random
name = input("What is your name? ")
print ("Hello, " + name, "Time to play hangman!")
print ('')
time.sleep(2)
print ("Start guessing...")
bank = ["ironman", "hulk", "captain america", "black widow", "thor", "hawkeye"]
r = (random.randint(0,5))
word = bank[r]
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char, )
else:
print ("_", )
failed += 1
if failed == 0:
print ("You won")
break
print
guess = input("guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print ("Wrong")
print ("You have", + turns, 'more guesses' )
if turns == 0:
print ("You Lose")
Code for visuals
def setup():
size(250,350)
background(102,204,255)
fill(17,214,11)
rect(0,201,250,350)
def draw():
strokeWeight(2)
line(100,100,100,200)
line(100,100,150,100)
line(150,100,150,125)
line(75,200,125,200)
line(85,200,100,175)
line(115,200,100,175)
You should put it all into Processing. It's much easier to add code to a visualization than to add a visualization to other code. There's also an issue with your Python code: think about what will happen if someone guesses multiple characters at once. What if they guess the entire alphabet?
As for actually making the game, you should try to put your Python code into Processing first. Make the game in Processing, then add the visualization. The current state of your game doesn't really work like a Processing sketch, so try getting yourself into the mindset of Processing (frame-by-frame). Make an animation before doing an interactive back-and-forth game like this.

Why do I keep getting an error saying e in endtime is invalid syntax in Python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
import time as t
t = t.time
starttime = t
def calcprod():
prod = 1
for i in range(1, 1000000):
prod = prod * i
p = calcprod()
print("The result is %s digits" % (str(len(p))))
endtime = t
print("It took %s seconds to calculate" % (starttime - endtime))
I don't know how I can fix my code.
Below you find some hopefully useful comments to solve your problems:
import time as t
t = t.time # Don't name this the same as your time library
# Also use t.time() instead of t.time
starttime = t
def calcprod():
prod = 1
for i in range(1, 1000000):
prod = prod * i
# return a value here (hint: cast the result to a string)
p = calcprod()
print("The result is %s digits" % (str(len(p))))
endtime = t # This assigns the same value to 'endtime' as starttime.
# You need to measure the current time again.
# How can you do this?
print("It took %s seconds to calculate" % (starttime - endtime))
# Does it make sense to calculate starttime-endtime?
# Which one is the bigger value?
You forgot the return statement in your function maybe this is the problem

Why does my while loop not stop? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
RANDOM_COR=random.randrange(5,6)
def check_xy_data():
global COUNT
COUNT=0
input_xy=input("input(x,y) : ")
think_xy=list(map(int,input_xy.split(",")))
if(random_array[think_xy[0]][think_xy[1]] == "C"):
screen_array[think_xy[0]][think_xy[1]] = "O"
COUNT=COUNT+1
else:
screen_array[think_xy[0]][think_xy[1]] = "X"
def main():
make_intro()
init_screen_array ()
init_random_array ()
make_random_num(RANDOM_COR)
while(True):
check_xy_data()
draw_outline_start(TOTAL_COL_NUM//2)
draw_out_rowline(TOTAL_COL_NUM//2, "Input : ")
draw_out_rowline(TOTAL_COL_NUM//2, "Correct : ")
draw_out_rowline(TOTAL_COL_NUM//2, "Error : ")
draw_out_rowline(TOTAL_COL_NUM//2, "Total : ")
draw_outline_mid(TOTAL_COL_NUM//2)
if(COUNT==RANDOM_COR-1):
break
The if at the bottom of my code is supposed to get me out of the while loop, but I'm stuck in an infinite loop. Help?
(assignment, 2016) 예고편 The Assignment | 어싸인먼트 감독: 월터 힐 각본: 월터 힐, 데니스 해밀 출연: 김성훈 출연 현빈, 유해진, 김주혁 개봉 2016 한국 상세보기 그간...
Try this change:
RANDOM_COR=random.randrange(5,6)
COUNT = 0
def check_xy_data():
global COUNT
With COUNT inside check_xy_data, you set it back to 0 on every call. It can never reach more than 1. Your check is whether it's in the range 5-6. This is never true, so you can never leave the loop.
Note that trivial debugging skills would have found this: just stick a print statement before you test your loop condition, to see what the values are. Use that next time ... :-)

Categories