CPU player dice game - python

Need to program a CPU that decides between throwing the dice again or ending its turn.
The game already works with two players. Now I just need the 2nd player to make decisions on its own.
What do I do? This is a part of the code:
while not juego_termina:
print("")
jug_turno.lanzar_dado(dado)
jug2.dec_cpu()
while jug_turno.jugando:
jug2.dec_cpu() #Se anida un while para cada turno del jugador
print("Puntaje parcial acumulado:",end=' ')
print(jug_turno.p_parcial)
continuar = ""
jug2.dec_cpu()
while continuar != "SI" and continuar != "NO": #Pregunta si continua el turno
print("Desea seguir jugando? (SI/NO)")
continuar = input().upper() #.upper para la mayuscula
if continuar == "SI":
jug_turno.lanzar_dado(dado)
else:
jug_turno.terminar_turno()
if jug_turno.p_total >= meta: #Compara el puntaje total con la meta asignada al inicio
juego_termina = True #Se acaba el juego y salta a nombrar el ganador
else:
if jug_turno == jug1:
jug_turno = jug2
else:
jug_turno = jug1
mostrar_puntajes(jug1,jug2)
print("El ganador es:")
print(jug_turno.nombre)

I only know a small amount of Spanish, so it's possible I'm reading your code incorrectly, but it looks like the game works like Blackjack - the winning player is the player who has the highest total without going over some maximum value (21 in the case of Blackjack). The code for the simplest algorithm you could use probably looks something like this:
def dec_cpu(maximum):
total = 0
while total < maximum and (highest_possible_die_roll / 2) < (maximum - total):
total = total + roll_die()
return total
The (highest_possible_die_roll / 2) < (maximum - total) part is essentially saying, "if there's less than a 50% chance that rolling the die again will put me over the maximum, roll again". From there, you can refine it depending on the rules of the game. For example, if there's an amount of money being wagered each time, the computer might want to be 75% sure that they won't go over the maximum when the die is rolled if there's a lot of money on the line.

Related

How to avoid "can be undefined" error in Python?

I am trying to make a simple code to input a positive integer in the most accurate way possible. I mention that I am very new to the language.
Here is my code :
while number != None:
try:
while True:
number = int(input("Donnez la longueur de votre liste: "))
if number > 0:
break
except TypeError:
print("Tu doit donner un nombre entier")
The warning I get is number can be Undefined I am not aware of what is the specific situation where number is undefined as the while loop breaks only when number is not None ( means defined according to me ). I’m so grateful for your help. It is a challenging time but you would make it easier.
You can sidestep any warnings with a more idiomatic loop:
while True:
number = input("Donnez la longueur de votre liste: ")
try:
number = int(number)
except ValueError:
print("Tu doit donner un nombre entier")
continue
if number > 0:
break

Python - Not printing output in a function

I am new to Python and I am trying to write a code that takes from the user an input of money spent, number of transactions and it gives back the average value that was spent. So far I have this:
def compra(conta, valor):
conta["saldo"] = conta["saldo"] + valor
conta["transacoes"] = conta["transacoes"] + 1
conta["media"] = (conta["media"]*(conta["transacoes"]-1)+valor)/conta["transacoes"]
return(conta)
print(f"Os valores de saldo, transações e média são: {conta['saldo']} {conta['transacoes']} {conta['media']}")
while True:
valordacompra = float(input('Digite o valor da compra: '))
But I am not sure how to make it show on the screen what the values are after getting the input. If some more information is needed let me know ! Thank you
import math
money_spent = int(input('How much money was spent?: '))
num_transactions = int(input('How many transactions?: '))
average_value = money_spent / num_transactions
print("The average value is " + str(average_value) + '$')
Also keep an eye on exceptions. For example if the user typed in "cat" instead of a number. You can do this by using try ... except
import math
while True:
try:
money_spent = int(input('How much money was spent?: '))
num_transactions = int(input('How many transactions?: '))
average_value = money_spent / num_transactions
print("The average value is " + str(average_value) + '$')
break
except:
ValueError
print('Type in a number')

How to condition a variable by calling the value?

I have a doubt. Previously I made my first Python program with everything I learned, it was about the system of a vending machine, but one of the main problems was that it was too redundant when conditioning and ended up lengthening the code. So they explained to me that I should define the functions and return in case they are not fulfilled.
But my question is, how can I call the value of a variable, specifically a number, by conditioning it?
Example:
# -*- coding: utf-8 -*-
def select_ware(wares):
print(' '.join(wares))
while True:
selected = input("Elige un código: ")
if selected in wares:
print(f'El precio es de: {wares[selected]}\n')
break
else:
print("El código no existe, introduce un código válido")
return selected
def pay_ware(wares, selected):
money_needed = wares[selected]
money_paid = 0
while money_paid < money_needed:
while True:
try:
money_current = float(input("Introduce tu moneda: "))
break
except ValueError:
print('Please enter a number.')
money_paid += money_current
print(f'Paid ${money_paid}/${money_needed}')
if money_paid>{select_ware}: #This is the part where I want to substitute the value to call the variable.
print(f'Su cambio es ${money_paid-money_needed}')
return money_paid, money_needed
def main():
wares = {'A1': 6, 'A2': 7.5, 'A3': 8, 'A4': 10, 'A5': 11}
selected_ware = select_ware(wares)
pay_ware(wares, selected_ware)
if __name__ == "__main__":
main()
The question is this:
if money_paid>{select_ware}: #This is the part where I want to substitute the value to call the variable.
print(f'Su cambio es ${money_paid-money_needed}')
How can I implement it to avoid making long conditions for each value, that is, for the value of 'A1': 6, 'A2': 7.5, 'A3': 8, 'A4': 10, 'A5': 11?
Thanks for reading. Regards.
You are almost done! Just modify {select where} by money needed. You can also modify the Try Exception statement in order to avoid stop your program until the money current is a float number:
def pay_ware(wares, selected):
money_needed = wares[selected]
money_paid = 0
valid_money_current = False # para chequear que el pago sea con monedas
while money_paid < money_needed:
while not valid_money_current:
money_current = float(input("Introduce tu dinero: "))
if type(money_current) is float:
valid_money_current = True # el pago es valido
else:
print('Please enter a number.')
money_paid += money_current
print(f'Paid ${money_paid}/${money_needed}')
if money_paid > money_needed: #This is the part where I want to substitute the value to call the variable.
print(f'Su cambio es ${money_paid-money_needed}')
return money_paid, money_needed

applying a QUIT function to mini game in python

So I just started with python and I received the following task;
I need to create a mini game where the game choses a random number from 0-10.
Now I got most of my code but it seems I keep having issues with implementing a Quit option.
So the point is that the player can at any time give Quit as an answer and then the game quits.
It seems I can not attribute Quit in the right way.
When typing the Quit command (nee) I keep getting the following error message;
**Traceback (most recent call last):
File "C:\Users\aarabsa\PycharmProjects\projecten1\Lotto1.2.py", line 22, in <module>
guess = int(input('Probeer opnieuw of typ nee om het spel te verlaten: '))
ValueError: invalid literal for int() with base 10: 'nee'**
Could any of you guys give some advise ?
import random
import sys
print("Hello, wat is uw naam?")
naam = input()
print("Kan je de juiste cijfer raden tussen 0 en 10?")
answer = random.randint(0, 10)
guess = int(input('geef uw gekozen nummer: '))
TotalGuesses = 0
while guess != answer:
TotalGuesses += 1
if guess < answer:
print('fout antwoord!')
guess = int(input('Probeer opnieuw of typ nee om het spel te verlaten: '))
if guess in ['nee']:
print('Jammer dat je nu al opgeeft ' + naam + ', tot de volgende keer!')
sys.exit()
elif guess > answer:
print('fout antwoord!')
guess = int(input('Probeer opnieuw of typ nee om het spel te verlaten: '))
if guess in ['nee']:
print('Jammer dat je nu al opgeeft ' + naam + ', tot de volgende keer!')
sys.exit()
if guess == answer:
break
if guess == answer:
print('Correct ' + naam + '! Je hebt ' + str(TotalGuesses) + 'foutief geraden voordat je de juiste antwoord kon vinden!')
You should convert to an int only if you've first made sure the user didn't enter that string. For example:
guess = None # So it's defined
guess_string = input('geef uw gekozen nummer: ')
if guess_string.lower() == 'nee':
... # tell the user goodbye, or whatever
sys.exit()
else:
guess = int(guess_string)
Additionally, you could check that their input is a valid number before converting it and assigning it to guess. Here is an explanation of how you can do that.
Since you get user input multiple times in your program, you could wrap all that up in a function and just call that, so you don't have repeats in your code.

changing variable value inside IF loop

I have a function which accepts value 1-5, and I want to declare a global variable called 'Des' and make it change according to the option selected because I want to use that value in another function. I tried this but it does not work.
def mainNJ():
#S_menu()
print( "\033[1m" " PLEASE SELECT THE TYPE OF DONATION.")
global Des
validate = False
while not validate:
option = input(" INPUT VALUE 1 TO 5 : " "\033[0m")
# For Selection 1 Animal Protection And Welfare.
if option == str(1):
validate = True
print()
print("\033[1m" " Animal Protection And Welfare Has Been Selected." "\033[0m")
#Amount()
Des1 = " Animal Protection And Welfare Has Been Selected."
Des = Des1
# For Selection 2 Support For Natural Disaster.
elif option == str(2):
validate = True
print()
print("\033[1m" " Support For Natural Disaster Has Been Selected." "\033[0m")
#Amount()
Des2 = " Support For Natural Disaster Has Been Selected."
Des = Des2
# For Selection 3 Children Education And Activities.
elif option == str(3):
validate = True
print()
print("\033[1m" " Children Education And Activities Has Been Selected." "\033[0m")
#Amount()
Des3 = " Children Education And Activities Has Been Selected."
Des = Des3
# For Selection 4 Children Education And Activities.
elif option == str(4):
validate = True
print()
print("\033[1m" " Caregiving And Health Research Has Been Selected." "\033[0m")
#Amount()
Des4 = " Caregiving And Health Research Has Been Selected."
Des = Des4
# For Selection 5 Conservation Of Cultural Arts.
elif option == str(5):
validate = True
print()
print("\033[1m" " Conservation Of Cultural Arts Has Been Selected." "\033[0m")
#Amount()
Des5 = " Conservation Of Cultural Arts Has Been Selected."
Des = Des5
else:
print()
print(" Invalid Option. Please Try Again.")
#S_menu()
Maybe, if Des is not defined outside of function, you are trying to access it before it > > was assigned. i.e. you are doing something with Des before making mainNJ() call
to give solution, if this is problem
in another function, where you use it
try:
print(Des) # example of usage
except NameError:
print("Des not yet created")
# also you can put return statement so function does not continue
# or call mainNJ() here
You assign Des to Desx and that is a string. You need to assign it to int(option)

Categories