Use of random in a Hangman game - python

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
...
...

Related

Filter Pandas dataframe with user input

I'm trying to develop this code where I would have certain inputs for different variables, these would make the filter happen and return the filtered dataframe, this input will always only receive a single value that the user will choose amoung fewer options and if the input is empty, that filter must bring all the data.
I didn't put the user input because I was testing the function first, however, the function always returns an empty dataframe and I can't find out why. Here is the code I was developing:
I didn't put the dataframe because it comes from an excel, but if necessary I'll put together a sample that fits
df = pd.DataFrame({"FarolAging":["Vermelho","Verde","Amarelo"],"Dias Pendentes":["20 dias","40 dias","60 dias"],"Produto":["Prod1","Prod1","Prod2"],
"Officer":["Alexandre Denardi","Alexandre Denardi","Lucas Fernandes"],"Analista":["Guilherme De Oliveira Moura","Leonardo Silva","Julio Cesar"],
"Coord":["Anna Claudia","Bruno","Bruno"]})
FarolAging1 = ['Vermelho']
DiasPendentes = []
Produto = []
Officer = []
def func(FarolAging1,DiasPendentes,Produto,Officer):
if len(Officer) <1:
Officer = df['Officer'].unique()
if len(FarolAging1) <1:
FarolAging1 = df['FarolAging'].unique()
if len(DiasPendentes) <1:
DiasPendentes = df['Dias Pendentes'].unique()
if len(Produto) <1:
Produto = df['Produto'].unique()
dados2 = df.loc[df['FarolAging'].isin([FarolAging1]) & (df['Dias Pendentes'].isin([DiasPendentes])) & (df['Produto'].isin([Produto])) & (df['Officer'].isin([Officer]))]
print(dados2)
func(FarolAging1, DiasPendentes, Produto, Officer) ```
You have to remove the square brackets in isin because you already have lists:
def func(FarolAging1,DiasPendentes,Produto,Officer):
if len(Officer) <1:
Officer = df['Officer'].unique()
if len(FarolAging1) <1:
FarolAging1 = df['FarolAging'].unique()
if len(DiasPendentes) <1:
DiasPendentes = df['Dias Pendentes'].unique()
if len(Produto) <1:
Produto = df['Produto'].unique()
# Transform .isin([...]) into .isin(...)
dados2 = (df.loc[df['FarolAging'].isin(FarolAging1)
& (df['Dias Pendentes'].isin(DiasPendentes))
& (df['Produto'].isin(Produto))
& (df['Officer'].isin(Officer))])
print(dados2)
return dados2 # don't forget to return something
Output:
>>> func(FarolAging1, DiasPendentes, Produto, Officer)
FarolAging Dias Pendentes Produto Officer Analista Coord
0 Vermelho 20 dias Prod1 Alexandre Denardi Guilherme De Oliveira Moura Anna Claudia

"pyautogui.locateOnScreen" is confusing one image with another

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

How to set a value for an empy list

I am starting to learn to program using BeautifulSoup. What I want to achieve with this code is to save prices from different pages. To achieve this I store the prices of each page in a list and all those lists in a list. The problem is some pages do not save the prices so there are some lists that are completely empty. What I am looking for is that those empty lists are assigned the elements of the "ListaR" so that later I do not have problems. Here's my code:
from bs4 import BeautifulSoup
import requests
import pandas as pd
from decimal import Decimal
from typing import List
AppID = ['495570', '540190', '607210', '575780', '338840', '585830', '637330', '514360', '575760', '530540', '361890', '543170', '346500', '555930', '575700', '595780', '362400', '562360', '745670', '763360', '689360', '363610', '575770', '467310', '380560']
ListaPrecios = list()
ListaUrl = list() #<------- LISTA
Blanco = [""]
ListaR = ["$0.00 USD", "$0.00 USD"]
for x in AppID: # <--------- Para cada una de las AppID...
#STR#
url = "https://steamcommunity.com/market/search?category_753_Game%5B%5D=tag_app_"+x+"&category_753_cardborder%5B%5D=tag_cardborder_0&category_753_item_class%5B%5D=tag_item_class_2#p1_price_asc" # <------ Usa AppID para entrar a sus links de mercado
ListaUrl += [url] # <---------- AGREGA CADA LINK A UNA LISTA
PageCromos = [requests.get(x) for x in ListaUrl]
SoupCromos = [BeautifulSoup(x.content, "html.parser") for x in PageCromos]
PrecioCromos = [x.find_all("span", {"data-price": True}) for x in SoupCromos] # <--------- GUARDA LISTAS DENTRO DE LISTAS CON CODIGO
min_CromoList = []
for item in PrecioCromos:
CromoList = [float(i.text.strip('USD$')) for i in item]
min_CromoList.append(min(CromoList)) # <---------------- Lista con todos los precios minimos de cromos de cada juego
print(min_CromoList)
Output:
ValueError: min() arg is an empty sequence
You can change this line
min_CromoList.append(min(CromoList))
to:
if not CromoList: # this will evaluate to True if the list is empty
min_CromoList.append(min(ListaR))
else:
min_CromoList.append(min(CromoList))
A neat feature of python is that empty lists evaluate to False and non-empty lists evaluate to True.
Since min(ListaR) will always evaluate to '$0.00 USD' it is probably neater to write this as:
if not CromoList:
min_CromoList.append('$0.00 USD')
else:
min_CromoList.append(min(CromoList))

Dictionary of unique words and their position in a file

I'm trying to build a 'database' of words and their corresponding tweet identifier.
My guess is that a dictionary is the best option for doing this.
Identifier, user, text, words get split on tab.
Example of input :
1035421931321864192 SchipholWatch RT #vinvanoort: Zo, ik heb getekend Genoeg #geschiphol, hoogste tijd voor een eerlijk en duurzaam #luchtvaartbeleid RT #vinvanoort : Zo , ik heb getekend Genoeg #geschiphol , hoogste tijd voor een eerlijk en duurzaam #luchtvaartbeleid
1035421930541772800 ev4uam2 RT #AfshinEllian1: Kennelijk vinden ze daar aan die gezellige tafel normaal dat steltje barbaren onze grondwettelijke rechten bedreigen. Zouden we ook voor andere buitenwettelijke dreigingen moeten capituleren? Wat een door ons gesubsidieerde domheid! #laatop1 #cartoonwedstrijd RT #AfshinEllian1 : Kennelijk vinden ze daar aan die gezellige tafel normaal dat steltje barbaren onze grondwettelijke rechten bedreigen . Zouden we ook voor andere buitenwettelijke dreigingen moeten capituleren ? Wat een door ons gesubsidieerde domheid ! #laatop1 #cartoonwedstrijd
Example of desired output:
{'exampleword' : ['1035421930541772800', '1235424930545772800']}
Current code :
def main():
olist = []
worddict = {}
for line in sys.stdin:
i,u,t,w = line.split('\t')
splitword = w.split()
olist.extend(splitword)
for num,name in enumerate(olist):
print("{} [{}]".format(name.strip(), num))
main()
So far i have tried iterating over the lines and adding splitword + i(which is the tweet identifier) to a dictionary, without succes.
Basically what you want is to "reverse" a dictionary with list values to another dictionary with list values.
I abstracted from the actual tweet data since that would obfuscate the actual problem's answer.
A greedy implementation could be:
import collections
def reverse_dict(input):
output = collections.defaultdict(list)
for key, val in input.items():
for item in val:
output[item].append(key)
return output
def main():
input = {
'u123': ['hello', 'world'],
'u456': ['hello', 'you'],
'u789': ['you', 'world'],
}
output = reverse_dict(input)
print output
if __name__ == '__main__':
main()
As #Michael Butscher said, the expected output from your question is not a valid Python dictionary. The above code will output:
{'world': ['u789', 'u123'], 'you': ['u789', 'u456'], 'hello': ['u456', 'u123']}
Furthermore, as #Austin answered, approaching this problem using "brute force" won't necessarily be the best solution.

Parsing a simple text file in python

I've the following text file taken from a csv file. The file is two long to be shown properly here, so here's the line info:
The file has 5 lines:The 1st one starts in ETIQUETASThe 2nd one stars in RECURSOSThe 3rd one starts in DATOS CLIENTE Y PIEZAThe 4th one starts in Numero Referencia,The 5th and last one starts in BRIDA Al.
ETIQUETAS:;;;;;;;;;START;;;;;;;;;;;;;;;;;;;;;END;;
RECURSOS:;;;;;;;;;0;0;0;0;0;0;0;0;0;1;0;0;0;0;0;0;1;1;1;0;1;0;;Nota: 0
equivale a infinito, para decir que no existen recursos usar un numero
negativo DATOS CLIENTE Y PIEZA;;;;PLAZOS Y PROCESOS;;;;;;;;;;hoja
de ruta;MU;;;;;;;;;;;;;;;;; Numero Referencia;Descripcion
Referencia;Nombre Cliente;Codigo Cliente;PLAZO DE
ENTREGA;piezas;PROCESO;MATERIAL;stock;PROVEEDOR;tiempo ida
pulidor;pzas dia;TPO;tiempo vuelta pulidor;TIEMPO RECEPCION;CONTROL
CALIDAD DE ENTRADA;TIEMPO CONTROL CALIDAD DE ENTRADA;ALMACEN A (ANTES
DE ENTRAR
MAQUINA);GRANALLA;TPO;LIMPIADO;TPO;BRILLADO;TPO;;CARGA;MAQUINA;SOLTAR;control;EMPAQUETADO;ALMACENB;TIEMPO;
BRIDA Al;BRIDA Al;AEROGRAFICAS AHE,
S.A.;394;;;niquelado;aluminio;;;;matriz;;;5min;NO;;3dias;;;;;;;;1;1;1;;1;4D;;
I want to do two things:
Count the between START and END of the first line, both inclusive and save it as TOTAL_NUMBERS. This means if I've START;;END has to count 3; the START itself, the blank space between the two ;; and the END itself. In the example of the test, START;;;;;;;;;;;;;;;;;;;;;END it has to count 22.
What I've tried so far:
f = open("lt.csv", 'r')
array = []
for line in f:
if 'START' in line:
for i in line.split(";"):
array.append(i)
i = 0
while i < len(array):
if i == 'START':
# START COUNTING, I DONT KNOW HOW TO CONTINUE
i = i + 1
2.Check the file, go until the word PROVEEDOR appears, and save that word and the following TOTAL_NUMBERS(in the example, 22) on an array.
This means it has to save:
final array = ['PROVEEDOR', 'tiempo ida pulidor', 'pzas dia, 'TPO', 'tiempo vuelta pulidor', 'TIEMPO RECEPCION', 'CONTROL CALIDAD DE ENTRADA', 'TIEMPO CONTROL CALIDAD DE ENTRADA, 'ALMACEN A (ANTES DE ENTRAR MAQUINA)', 'GRANALLA', 'TPO', 'LIMPIADO', 'TPO','BRILLADO','TPO','','CARGA', 'MAQUINA', 'SOLTAR', 'control', 'EMPAQUETADO', 'ALMACENB']
Thanks in advance.
I am assuming the file is split into two lines; the first line with START and END and then a long line which needs to be parsed. This should work:
with open('somefile.txt') as f:
first_row = next(f).strip().split(';')
TOTAL_NUMBER = len(first_row[first_row.index('START'):first_row.index('END')+1])
bits = ''.join(line.rstrip() for line in f).split(';')
final_array = bits[bits.index('PROVEEDOR'):bits.index('PROVEEDOR')+TOTAL_NUMBER]

Categories

Resources