I am creating a bot to automate an activy at the game "Monster Sanctuary", but i'm having a problem where my pyautogui is recognizing another image as the one I input as argument, cause all of the things in screen looks the same!
Image, to undestand better what I am saying:
The one that I am trying to make my pyautogui locate is the "Sino de Monstro".
Here is the specifc part of code used to do that:
while time.time() - start < 2:
if pyautogui.locateOnScreen('Images-PTBR\\Screenshot_1.png') != None:
Sino = True
print("Achei!")
if Sino == True:
start = 2
else:
print('Ainda localizando...')
if Sino == True:
m_x, m_y = pyautogui.locateCenterOnScreen('Images-PTBR\\Screenshot_1.png')
pyautogui.click(m_x, m_y)
print("Sino de monstro alcançado.")
# Tem um problema, se estiver na outra página o sino, ele dá dois enters e quebra tudo.
while contador_2 != 2:
pyautogui.press('enter')
time.sleep(0.2)
contador_2 += 1
else:
No_Sino = True
Related
I'm practicing with an algorithm that generates a random number that the user needs, then keeps trying until it hits. But PySimpleGUI produces an error saying: Unable to complete operation on element with key None.
import randomimport PySimpleGUI as sg
class ChuteONumero:
def init(self):
self.valor_aleatorio = 0
self.valor_minimo = 1
self.valor_maximo = 100
self.tentar_novamente = True
def Iniciar(self):
# Layout
layout = [
[sg.Text('Seu chute', size=(39, 0))],
[sg.Input(size=(18, 0), key='ValorChute')],
[sg.Button('Chutar!')],
[sg.Output(size=(39, 10))]
]
# Criar uma janela
self.janela = sg.Window('Chute o numero!', Layout=layout)
self.GerarNumeroAleatorio()
try:
while True:
# Receber valores
self.evento, self.valores = self.janela.Read()
# Fazer alguma coisa com os vaalores
if self.evento == 'Chutar!':
self.valor_do_chute = self.valores['ValorChute']
while self.tentar_novamente == True:
if int(self.valor_do_chute) > self.valor_aleatorio:
print('Chute um valor mais baixo')
break
elif int(self.valor_do_chute) < self.valor_aleatorio:
print('Chute um valor mais alto!')
break
if int(self.valor_do_chute) == self.valor_aleatorio:
self.tentar_novamente = False
print('Parabéns, você acertou!')
break
except:
print('Não foi compreendido, apenas digite numeros de 1 a 100')
self.Iniciar()
def GerarNumeroAleatorio(self):
self.valor_aleatorio = random.randint(
self.valor_minimo, self.valor_maximo)
chute = ChuteONumero()
chute.Iniciar()
I expected a layout to open, but it does not open.
Revised your code ...
import random
import PySimpleGUI as sg
class ChuteONumero:
def __init__(self):
self.valor_aleatorio = 0
self.valor_minimo = 1
self.valor_maximo = 100
self.tentar_novamente = True
def Iniciar(self):
# Layout
layout = [
[sg.Text('Your kick', size=(39, 0))],
[sg.Input(size=(18, 0), key='ValorChute')],
[sg.Button('Kick!')],
[sg.Output(size=(39, 10))]
]
# Create a window
self.janela = sg.Window('Guess The Number!', layout)
self.GerarNumeroAleatorio()
while True:
# Receive amounts
evento, valores = self.janela.read()
if evento == sg.WIN_CLOSED:
break
# Do something with the values
elif evento == 'Kick!':
try:
valor_do_chute = int(valores['ValorChute'])
except ValueError:
print('Not understood, just type numbers from 1 to 100')
continue
if valor_do_chute > self.valor_aleatorio:
print('Guess a lower value')
elif valor_do_chute < self.valor_aleatorio:
print('Kick a higher value!')
if valor_do_chute == self.valor_aleatorio:
sg.popup_ok('Congratulations, you got it right!')
break
self.janela.close()
def GerarNumeroAleatorio(self):
self.valor_aleatorio = random.randint(self.valor_minimo, self.valor_maximo)
chute = ChuteONumero()
chute.Iniciar()
This is a Hangman game. The fact is that the user counts with one help, which can be used to reveal one of the letters of the word. I need it for the unknown letters (actually it works randomly and when the user has the word almost done it's more probably for the letter to be revealed yet, so there's no really help)
How can I modify the code for it to reveal a letter that hasn't been revealed yet?
import random
#AHORCADO
lista_palabras=['programacion', 'python', 'algoritmo', 'computacion', 'antioquia', 'turing', 'ingenio', 'AYUDA']
vidas=['🧡','🧡','🧡','🧡','🧡','🧡','🧡']
num_word=random.randint(0,6)
palabra=lista_palabras[num_word]
print(' _ '*len(palabra))
print('Inicias con siete vidas', "".join(vidas),'\n', 'Pista: escribe AYUDA para revelar una letra (sólo tienes disponible 1)')
#print(palabra)
palabra_actual=['_ ']*len(palabra)
posicion=7
contador_pistas=0
while True:
fullword="".join(palabra_actual)
#condición para ganar
if letra==palabra or fullword==palabra:
print(palabra)
print('¡GANASTE!')
break
letra=input('Inserta una letra: ')
#condición que agrega letra adivinada
if letra in palabra:
orden=[i for i in range(len(palabra)) if palabra[i] == letra]
for letras in orden:
palabra_actual[letras]=letra
print(''.join(palabra_actual))
#condición AYUDAs
elif letra=='AYUDA' and contador_pistas==0:
pista=random.randint(0,len(palabra)-1)
palabra_actual[pista]=palabra[pista]
print(''.join(palabra_actual))
contador_pistas+=1
#condición límite de ayudas
elif letra=='AYUDA' and contador_pistas>=1:
print('Ya no te quedan pistas restantes')
#condición para perder
elif letra not in lista_palabras:
posicion-=1
vidas[posicion]='💀'
print('¡Perdiste una vida!',''.join(vidas))
if posicion==0:
print('GAME OVER')
break
Thank you <3
Create a list of of index values for the word, and remove the indexes from the list as the user selects the correct characters. then when they ask for help, you can call random.choice on the remaining indexes so you are guarateed to get one that hasn't been chosen yet
...
...
palabra_actual=['_ ']*len(palabra)
posicion=7
contador_pistas=0
indexes = list(range(len(palabra))) # list of index values
while True:
fullword="".join(palabra_actual)
if letra==palabra or fullword==palabra:
print(palabra)
print('¡GANASTE!')
break
letra=input('Inserta una letra: ')
if letra in palabra:
orden=[i for i in range(len(palabra)) if palabra[i] == letra]
for letras in orden:
indexes.remove(letras) # remove index values for selected characters
palabra_actual[letras]=letra
print(''.join(palabra_actual))
elif letra=='AYUDA' and contador_pistas==0:
pista=random.choice(indexes) # choose from remaining index values using random.choice
palabra_actual[pista]=palabra[pista]
print(''.join(palabra_actual))
contador_pistas+=1
...
...
everything's fine? I hope so.
I'm dealing with this issue: List index out of range. -
Error message:
c:\Users.....\Documents\t.py:41: FutureWarning: As the xlwt package is no longer maintained, the xlwt engine will be removed in a future version of pandas. This is the only engine in pandas that supports writing in the xls format. Install openpyxl and write to an xlsx file instead. You can set the option io.excel.xls.writer to 'xlwt' to silence this warning. While this option is deprecated and will also raise a warning, it can be globally set and the warning suppressed.
read_file.to_excel(planilhaxls, index = None, header=True)
The goal: I need to create a loop that store a specific line of a worksheet such as sheet_1.csv, this correspondent line in sheet_2.csv and a third sheet also, stored in 3 columns in a sheet_output.csv
Issue: It's getting an index error out of range that I don't know what to do
Doubt: There is any other way that I can do it?
The code is below:
(Please, ignore portuguese comments)
import xlrd as ex
import pyautogui as pag
import os
import pyperclip as pc
import pandas as pd
import pygetwindow as pgw
import openpyxl
#Inputs
numerolam = int(input('Escolha o número da lamina: '))
amostra = input('Escoha a amostra: (X, Y, W ou Z): ')
milimetro_inicial = int(input("Escolha o milimetro inicial: "))
milimetro_final = int(input("Escolha o milimetro final: "))
tipo = input("Escolha o tipo - B para Branco & E para Espelho: ")
linha = int(input("Escolha a linha da planilha: "))
# Conversão de código
if tipo == 'B':
tipo2 = 'BRA'
else:
tipo2 = 'ESP'
#Arquivo xlsx
#planilhaxlsx = f'A{numerolam}{amostra}{milimetro_inicial}{tipo2}.xlsx'
#planilhaxls = f'A{numerolam}{amostra}{milimetro_inicial}{tipo2}.xls'
#planilhacsv = f'A{numerolam}{amostra}{milimetro_inicial}{tipo2}.csv'
#planilhacsv_ = f'A{numerolam}{amostra}{milimetro_final}{tipo2}.csv'
#arquivoorigin = f'A{numerolam}{amostra}{milimetro_inicial}{tipo2}.opj'
#Pasta
pasta = f'L{numerolam}{amostra}'
while milimetro_inicial < milimetro_final:
planilhaxlsx = f'A{numerolam}{amostra}{milimetro_inicial}{tipo2}.xlsx'
planilhaxls = f'A{numerolam}{amostra}{milimetro_inicial}{tipo2}.xls'
planilhacsv = f'A{numerolam}{amostra}{milimetro_inicial}{tipo2}.csv'
planilhacsv_ = f'A{numerolam}{amostra}{milimetro_final}{tipo2}.csv'
arquivoorigin = f'A{numerolam}{amostra}{milimetro_inicial}{tipo2}.opj'
# Converte o arquivo .csv para .xls e .xlsx
read_file = pd.read_csv(planilhacsv)
read_file.to_excel(planilhaxls, index = None, header=True)
#read_file.to_excel(planilhaxlsx, index = None, header=True)
# Abre o arquivo .xls com o xlrd - arquivo excel.
book = ex.open_workbook(planilhaxls)
sh = book.sheet_by_index(0)
# Declaração de variáveis.
coluna_inicial = 16 # Q - inicia em 0
valor = []
index = 0
# Loop que armazena o valor da linha pela coluna Q-Z na variável valor 0-(len-1)
while coluna_inicial < 25:
**#ERRO NA LINHA ABAIXO**
**temp = sh.cell_value(linha, coluna_inicial)**
valor.append(temp) # Adiciona o valor
print(index)
print(valor[index])
index +=1
coluna_inicial += 1
# Abre planilha de saída
wb = openpyxl.Workbook()
ws = wb.active
#Inicia loop de escrita
colunas = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
idx_colunas = 0
contador_loop = colunas[idx_colunas]
linha_loop = 1
index_out = 0
s = f'{contador_loop}{linha_loop}'
print(s)
while linha_loop < len(valor):
valor[index_out] = "{}".format(valor[index_out])
ws[s].value = valor[index_out]
print(valor[index_out] + ' feito')
linha_loop += 1
idx_colunas += 1
index_out += 1
# Salva planilha de saída
wb.save("teste.xlsx")
milimetro_inicial += 1
Your problem is on this line
temp = sh.cell_value(linha, coluna_inicial)
There are two index params used linha and coluna_inicial, 'linha' appears to be a static value so the problem would seem to be with 'coluna_inicial' which gets increased by 1 each iteration
coluna_inicial += 1
The loop continues while 'coluna_inicial' value is less than 25. I suggest you check number of columns in the sheet 'sh' using
sh.ncols
either for debugging or as the preferred upper value of your loop. If this is less than 25 you will get the index error once 'coluna_inicial' value exceeds the 'sh.ncols' value.
<---------------Additional Information---------------->
Since this is an xls file there would be no need for delimiter settings, your code as is should open it correctly. However since the xls workbook to be opened is determined by params entered by the user at the start presumably meaning there are a number in the directory to choose from, are you sure you are checking the xls file your code run is opening? Also if there is more than one sheet in the workbook(s) are you opening the correct sheet?
You can print the workbook name to be sure which one is being opened. Also by adding verbosity to the open_workbook command (level 2 should be high enough), it will upon opening the book, print in console details of the sheets available including number of rows and columns in each.
print(planilhaxls)
book = ex.open_workbook(planilhaxls, verbosity=2)
sh = book.sheet_by_index(0)
print(sh.name)
E.g.
BOF: op=0x0809 vers=0x0600 stream=0x0010 buildid=14420 buildyr=1997 -> BIFF80
sheet 0('Sheet1') DIMENSIONS: ncols=21 nrows=21614
BOF: op=0x0809 vers=0x0600 stream=0x0010 buildid=14420 buildyr=1997 ->
BIFF80
sheet 1('Sheet2') DIMENSIONS: ncols=13 nrows=13
the print(sh.name) as shown checks the name of the sheet that 'sh' is assigned to.
I am getting Rollbacks automatically.
Here is my code:
#socketio.on('update2')
def update_table_infocorp(trigger):
checknotprocess = Infocorp.query.filter(Infocorp.Procesado == False)
for row in checknotprocess:
getidentityuser = Usuarios.query.filter(Usuarios.id_user == row.id_user).first()
getidentityconsulta = Consolidado.query.filter(Consolidado.id_user == row.id_user and
(Consolidado.numdocumento == getidentityuser.numdocumento)).first()
if not getidentityconsulta:
# print("No se encontro la consulta relacionada al usuario.")
test = True
else:
sentinelresult = getsentinel(getidentityuser.tipodocumento, getidentityuser.numdocumento, row.id_consulta,
getidentityconsulta.solicitudes_id)
print(getidentityconsulta.solicitudes_id)
print(getidentityuser.tipodocumento)
if sentinelresult == True:
continue
else:
print("Ocurrio un error")
resultadoquery = Infocorp.query.filter(Infocorp.Procesado == True)
datatransform = InfocorpSchema(many=True)
datatransformresult = datatransform.dump(resultadoquery)
emit('nuevatableinfocorp', datatransformresult, broadcast=True)
And those are my logs:
I hope you will be able to help me because it is affecting other systems that use the same database.
I want to do a system using a Autorules fuzzy controller where i create rules from process real data.
My problem is when i use the new data to simulate the fuzzy controller with the rules extracted of the older data, i get a error about the crisp output that cannot be calculated because do not exist rules enough, what is totally normal because my fuzzy system needs more rules and that's my point! I want to implement a new routine that analyses the crisp input/output and create new rules from this data, after that, i want to go back in my code and simulate again.
Is there a function that blocks the AssertionError from stop the code and redirect to another def or to a previously code line?
I tried to find some lib with a function that allows me to redirect the error steady to stop the code but no sucess. I think i will have to change the skfuzzy defuzz def code to allow to make it.
Thank you very much.
''' python
step = stp_ini
k = 0
delay = stp_ini
end = stp_fim - stp_ini
Tout_sim = pd.DataFrame(columns=['val'])
Vent_sim = pd.DataFrame(columns=['val'])
start = timeit.default_timer()
for step in range(end-k):
clear_output(wait=True)
simulation.input['PCA1'] = comp1n[step+delay]
simulation.input['PCA2'] = comp2n[step+delay]
simulation.input['PCA3'] = comp3n[step+delay]
simulation.input['PCA4'] = comp4n[step+delay]
simulation.input['Vent'] = dataoutf.NumVentOn[step+delay]
simulation.compute()
Tout_sim = Tout_sim.append({'val':simulation.output['Tout']},ignore_index=True)
stop = timeit.default_timer()
if ((step/(stp_fim-k-1))*100) < 5:
expected_time = "Calculating..."
else:
time_perc = timeit.default_timer()
expected_time = np.round( ( (time_perc-start)/(step/(end-k-1)) )/60,2)
'''
~\AppData\Local\Continuum\anaconda3\lib\site-packages\skfuzzy\control\controlsystem.py in defuzz(self)
587 self.var.defuzzify_method)
588 except AssertionError:
--> 589 raise ValueError("Crisp output cannot be calculated, likely "
590 "because the system is too sparse. Check to "
591 "make sure this set of input values will "
ValueError: Crisp output cannot be calculated, likely because the system is too sparse. Check to make sure this set of input values will activate at least one connected Term in each Antecedent via the current set of Rules.
edit:
I try to wrap the line code ValueError by try but the ValueError is activated yet
def defuzz(self):
"""Derive crisp value based on membership of adjective(s)."""
if not self.sim._array_inputs:
ups_universe, output_mf, cut_mfs = self.find_memberships()
if len(cut_mfs) == 0:
raise ValueError("No terms have memberships. Make sure you "
"have at least one rule connected to this "
"variable and have run the rules calculation.")
try:
return defuzz(ups_universe, output_mf,
self.var.defuzzify_method)
except AssertionError:
try:
new_c1 = []
new_c2 = []
new_c3 = []
new_c4 = []
new_vent = []
new_tout = []
newcondition1 = []
newcondition2 = []
newcondition3 = []
newcondition4 = []
newcondition5 = []
newcondition6 = []
#input
n = 0
for n in range(len(namespca)):
new_c1.append(fuzz.interp_membership(PCA1.universe, PCA1[namespcapd.name.loc[n]].mf, comp1n[step]))
new_c2.append(fuzz.interp_membership(PCA2.universe, PCA2[namespcapd.name.loc[n]].mf, comp2n[step]))
new_c3.append(fuzz.interp_membership(PCA3.universe, PCA3[namespcapd.name.loc[n]].mf, comp3n[step]))
new_c4.append(fuzz.interp_membership(PCA4.universe, PCA4[namespcapd.name.loc[n]].mf, comp4n[step]))
n = 0
for n in range(len(namesvent)):
new_vent.append(fuzz.interp_membership(Vent.universe, Vent[namesventpd.name.loc[n]].mf, dataoutf.NumVentOn[step]))
#output
n = 0
for n in range(len(namestemp)):
new_tout.append(fuzz.interp_membership(Tout.universe, Tout[namestemppd.name.loc[n]].mf, dataoutf.TsaidaHT[step]))
#new_c1 = np.transpose(new_c1)
new_c1_conv = pd.DataFrame(new_c1)
#new_c2 = np.transpose(new_c2)
new_c2_conv = pd.DataFrame(new_c2)
#new_c3 = np.transpose(new_c3)
new_c3_conv = pd.DataFrame(new_c3)
#new_c4 = np.transpose(new_c4)
new_c4_conv = pd.DataFrame(new_c4)
#new_vent = np.transpose(new_vent)
new_vent_conv = pd.DataFrame(new_vent)
#new_tout = np.transpose(new_tout)
new_tout_conv = pd.DataFrame(new_tout)
i=0
for i in range(pcamf):
newcondition1.append([new_c1_conv.idxmax(axis=0) == i])
newcondition2.append([new_c2_conv.idxmax(axis=0) == i])
newcondition3.append([new_c3_conv.idxmax(axis=0) == i])
newcondition4.append([new_c4_conv.idxmax(axis=0) == i])
i=0
for i in range(ventmf):
newcondition5.append([new_vent_conv.idxmax(axis=0) == i])
i=0
for i in range(tempmf):
newcondition6.append([new_tout_conv.idxmax(axis=0) == i])
choicelistpca = namespca
choicelistvent = namesvent
choicelisttout = namestemp
new_c1_rules = np.select(newcondition1, choicelistpca)
new_c2_rules = np.select(newcondition2, choicelistpca)
new_c3_rules = np.select(newcondition3, choicelistpca)
new_c4_rules = np.select(newcondition4, choicelistpca)
new_vent_rules = np.select(newcondition5, choicelistvent)
new_tout_rules = np.select(newcondition6, choicelisttout)
new_rules = np.vstack([new_c1_rules,new_c2_rules,new_c3_rules,new_c4_rules,new_vent_rules,new_tout_rules])
new_rules = new_rules.T
new_rulespd = pd.DataFrame(new_rules,columns=['PCA1','PCA2','PCA3','PCA4','Vent','Tout'])
#Checar se a nova regra está dentro do conjunto de regras fuzzy atual
if pd.merge(new_rulespd,AutoRules, on=['PCA1','PCA2','PCA3','PCA4','Vent','Tout'],how='inner').empty:
print('Nova regra não encontrada no conjunto atual de regras fuzzy!')
else:
pd.merge(new_rulespd,AutoRules, on=['PCA1','PCA2','PCA3','PCA4','Vent','Tout'],how='inner')
"""except AssertionError:
raise ValueError("Crisp output cannot be calculated, likely "
"because the system is too sparse. Check to "
"make sure this set of input values will "
"activate at least one connected Term in each "
"Antecedent via the current set of Rules.")"""
else:
# Calculate using array-aware version, one cut at a time.
output = np.zeros(self.sim._array_shape, dtype=np.float64)
it = np.nditer(output, ['multi_index'], [['writeonly', 'allocate']])
for out in it:
universe, mf = self.find_memberships_nd(it.multi_index)
out[...] = defuzz(universe, mf, self.var.defuzzify_method)
return output
Wrap the line of code that raises ValueError in a try. And decide what to do in its except ValueError: clause. Perhaps continue-ing on to the next iteration might be reasonable.