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
Related
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
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.
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 2 years ago.
Improve this question
hope anyone can help me with this as I don't know any better.
I built this for loop where I need to link stock movements with the order that triggered each of them.
The data sets both for orders and stock are huge (>2.000.000 rows) and I built this for loop which is working fine, but very slowly: it would take 74 days to complete by my math.
I need you guys and your magician eyes to take a look at it and tell me what I could be doing to increase this loop's efficiency, as I'm sure I'm doing a lot of rookie mistakes.
EDIT: Stack Overflow asked me to focus the question, sorry guys. I think my issue here is that I'm using a lot of pd.DataFrames in the loop because it was the only way I found to make it work with the datetime operations I'm using and extracting the lines to the result dataframe "inserts".
I think it could get better if I used arrays instead, I just don't know how to frame it or even make it work because of all the datatype errors I get.
Please take a look at the Dataframe operations in the code and tell me if you spot any grotesque mistake that is making this run so slow.
for index, row in FOLredux.iterrows():
# leave stockmov update to another processing step, so this can go faster
newrow = []
rollingDF = []
if row['HadNoStock'] == 'Yes':
stepdate = row['CheckStockDate']
else:
stepdate = row['DecidePackagingDate']
insertedMovList = inserts['MovementDate'][(inserts['SiteID'] == row['SiteId']) & (inserts['ProductID'] == row['ProductId'])
& (inserts['SizeValue'] == row['SizeValue'])]
rollingDF = pd.DataFrame({'MovementDate':[StockMov['MovementDate'][(StockMov['siteid'] == row['SiteId']) & (StockMov['ProductID'] == row['ProductId'])
& (StockMov['SizeValue'] == row['SizeValue']) & (StockMov['Delta'] == row['QtySold']*-1)
]][0]})
rollingDF['TotalTime'] = (stepdate - rollingDF['MovementDate']).dt.total_seconds()
stockdate = pd.DataFrame({'MovementDate': [rollingDF['MovementDate'][(rollingDF['TotalTime'] >= -10) & (rollingDF['TotalTime'] <= 10)]][0]})
if len(stockdate) != 0:
stockdate = stockdate['MovementDate'][~stockdate['MovementDate'].isin(insertedMovList)]
if len(stockdate) == 0:
#use creation date
stepdate = row['BoutiqueOrderDate']
insertedMovList = inserts['MovementDate'][(inserts['SiteID'] == row['SiteId']) & (inserts['ProductID'] == row['ProductId'])
& (inserts['SizeValue'] == row['SizeValue'])]
rollingDF = pd.DataFrame({'MovementDate':[StockMov['MovementDate'][(StockMov['siteid'] == row['SiteId']) & (StockMov['ProductID'] == row['ProductId'])
& (StockMov['SizeValue'] == row['SizeValue']) & (StockMov['Delta'] == row['QtySold']*-1)
]][0]})
rollingDF['TotalTime'] = (rollingDF['MovementDate'] - stepdate).dt.total_seconds()/60
stockdate = pd.DataFrame({'MovementDate': [rollingDF['MovementDate'][(rollingDF['TotalTime'] >= 0) & (rollingDF['TotalTime'] <= 60)]][0]})
if len(stockdate) != 0:
stockdate = stockdate['MovementDate'][~stockdate['MovementDate'].isin(insertedMovList)]
if len(stockdate) != 0:
stockdate = min(stockdate)
orderid = row['OrderCodeId']
values = [orderid, stockdate, row['SiteId'], row['ProductId'], row['SizeValue'], 1, 0]
zipped = zip(columns, values)
data = dict(zipped)
newrow.append(data)
inserts = inserts.append(newrow, True)
else:
stockdate = min(stockdate)
orderid = row['OrderCodeId']
values = [orderid, stockdate, row['SiteId'], row['ProductId'], row['SizeValue'], 0, 0]
zipped = zip(columns, values)
data = dict(zipped)
newrow.append(data)
inserts = inserts.append(newrow, True)
Essentially, this is linking the order to the stock movement based on how close the dates are, product information and uses the help of an aux dataframe (inserts) to not repeat the link to a previously used stock log.
PLEASE HELP :))))
Note: I am relatively new to Python, so don't expect my question to be the highest in quality.
I don't see a loop function at the bottom. You could put the code under a def code(): such as: def main(): and then at the bottom, add: main().
def main():
# Code goes here
main()
The main() at the bottom runs the code under def main(): again. If you are importing libraries, make sure it is at the top of the code, not under def main():.
I am running the following code:
import numpy as np
import cv2
import os
count = 0
cap = cv2.VideoCapture("/home/simon/PROJECT/real_data/00000020.mp4")
while not cap.isOpened():
cap = cv2.VideoCapture("./00000020.mp4")
cv2.waitKey(1000)
print "Wait for the header"
pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
while True:
flag, frame = cap.read()
if flag:
# The frame is ready and already captured
cv2.imshow('video', frame)
pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
print str(pos_frame)+" frames"
else:
# The next frame is not ready, so we try to read it again
cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, pos_frame-1)
print "frame is not ready"
# It is better to wait for a while for the next frame to be ready
cv2.waitKey(1000)
if cv2.waitKey(10) & 0xFF == 27:
break
if cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES) == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
# If the number of captured frames is equal to the total number of frames,
# we stop
break
if ret == True:
frame = cv2.VideoCapture.grab()
frame = 'frame%d' % count
cv2.imwrite('frame%d.png', frame)
count += 1
else:
print 'stopped at' + count
break
And whenever I run it, it loops on the while not loop, printing "wait for header".
There is never an error code or anything like that either.
I have tried to run it as a more simple piece of code, where it doesnt have all these checks, and again that doesn't throw any errors.
I am attempting to run this code to open a video, and then save the frames as png files throughout the video.
Does anyone spot any particular problems with the code?
Or alternatively does anyone know a piece of code that would do what i want more efficiently, as I have trawled through google searches and stack overflow a lot recently and haven't found anything
Thanks in advance
Panda
You need to include a couple of DLLs in your python directory in order to play videos. Please see this for details:
https://li8bot.wordpress.com/2014/07/09/opencvpython-part-1-working-with-videos/
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
Having a problem here with trying to add if statements to a function I am defining. To put things in context, I am programming a Black Jack simulation for a school project.
Here's what I'm having trouble with:
def getDecision():
getDecision = raw_input("What will you do? \n - Hit \n - Stand")
if getDecision = "Hit":
return hit()
I want it so that I can set two conditions in the function when it is called in main: if the player selects Hit, it returns the function hit in which the player receives a card. If the player selects Stand, the turn will transfer to the opponent (CPU).
What do I have to do to fix this? I get a syntax error on my if statement.
And here is the rest of the program as of now if you wish to scrutinize:
import random
def showMenu():
userInput = raw_input("Welcome to the game of Black Jack! Please choose an option from the following: \n - Start Game \n - Rules \n - Exit")
def getInitialMoney():
initialdough = 5000
def cardGenerator():
#Assign a random suit
suit_card = ["Hearts", "Spades", "Clubs", "Diamond"]
from random import choice
#Assign a random number between 1-13 (Ace to King)
number_card = random.randrange(1,14)
print choice(suit_card), str(number_card)
def getPlayerCards():
return cardGenerator(), cardGenerator()
def getCPUcards():
return cardGenerator(), cardGenerator()
This is where you are going wrong
if getDecision = "Hit":
should be
if getDecision == "Hit":
= is assignment and == is comparison.
This is how your final code should look like
def getDecision():
getDecision = raw_input("What will you do? \n - Hit \n - Stand")
if getDecision == "Hit":
return hit()