Game Theory - Coding Rock, Paper, Scissors Game in Python |EN/ES|

in Geek Zone2 years ago

RPS.png


Game theory is a very interesting topic with applications in many fields. It has found a niche specially in business and data sciences. It is about anticipation of strategies being played by others while understanding all the possible outcomes. Game theory has three major components: players, strategies, and payoffs. There are many games that have been studied in dept to understand which is the best outcome for each possible situation. One of these games is Rock, paper, scissors. It is a 2-players, zero-sum game which strategies that can be studied. In this post, I want to show how I created this game using python language considering all aspects of the theory behind the game.

La teoría de juegos es un tema muy interesante con aplicaciones en muchos campos. Ha encontrado un nicho especialmente en negocios y ciencias de datos. Se trata de anticipar las estrategias que están jugando otros mientras se comprenden todos los resultados posibles. La teoría de juegos tiene tres componentes principales: jugadores, estrategias y pagos. Hay muchos juegos que se han estudiado en profundidad para comprender cuál es el mejor resultado para cada situación posible. Uno de estos juegos es Piedra, papel, tijera. Es un juego de suma cero para 2 jugadores cuyas estrategias se pueden estudiar. En esta publicación, quiero mostrar cómo creé este juego usando el lenguaje python considerando todos los aspectos de la teoría detrás del juego.

Screenshot 2022-04-11 152413.jpg

When games are non-cooperative and possess only two players, it is easy to understand all possible payoffs by creating a matrix. This is the one for rock, paper, scissors. As you can see, each player has three different options (strategies) available. That creates a matrix of nine possible combination of such strategies. Three represent draws, and six correspond to wins and loses for each player. 1 point is gained by winning. -1 point is received by losing. 0 represents draws. Now, keeping this in mind I proceeded to code in python.

Cuando los juegos no son cooperativos y solo tienen dos jugadores, es fácil comprender todos los pagos posibles creando una matriz. Este es el de piedra, papel o tijera. Como puedes ver, cada jugador tiene tres opciones (estrategias) diferentes disponibles. Eso crea una matriz de nueve posibles combinaciones de tales estrategias. Tres representan empates y seis corresponden a victorias y derrotas de cada jugador. Se gana 1 punto al ganar. -1 punto se recibe por perder. 0 representa empates. Ahora, teniendo esto en cuenta, procedí a codificar en python.


#random library allows to create a random selection of the values in a list. time
#serves as a waiting time between rounds
import random, time

#variables to store the score of both players
user_score = 0
AI_score = 0

#a list the AI can choose from randomnly to play the game
choices = ["r","p","s"]

#number of games played variable
games = 1


First, we set all we need for this code. One of the main aspects is randomness. We want the program (I called it AI) to be able to pick an option to play against us. For that purpose, I imported random library. As you may know, the program does no wait for delivering the next line of code, so I imported time library as well to create a small pause between certain phases in the code.

Second, I created variables to store the scores from the player and the AI. The game is designed to play five rounds. The winner will be determined by the most wins or loses accumulated over those rounds.

Third, we need to provide choices the program can use. All those choices are stored in the list "choices" with the indicative letter for each possible option: (r)rock, (p)aper, and (s)cissor.

Fourth, I created a variable to store the number of games being played. This will serve as count and control of the number of rounds needed to reach a break or game end. With all these elements sets, it is time to code the game itself.

Primero, configuramos todo lo que necesitamos para este código. Uno de los aspectos principales es la aleatoriedad. Queremos que el programa (lo llamé AI) pueda elegir una opción para jugar contra nosotros. Para ese propósito, importé una biblioteca aleatoria. Como sabrá, el programa no espera para entregar la siguiente línea de código, por lo que también importé la biblioteca de tiempo para crear una pequeña pausa entre ciertas fases del código.

En segundo lugar, creé variables para almacenar las puntuaciones del jugador y la IA. El juego está diseñado para jugar cinco rondas. El ganador será determinado por la mayor cantidad de victorias o derrotas acumuladas durante esas rondas.

En tercer lugar, debemos proporcionar opciones que el programa pueda usar. Todas esas opciones se almacenan en la lista "opciones" con la letra indicativa de cada opción posible: (r)piedra, (p)aper y (s)cissor.

Cuarto, creé una variable para almacenar la cantidad de juegos que se estaban jugando. Esto servirá como conteo y control de la cantidad de rondas necesarias para llegar a un descanso o final del juego. Con todos estos conjuntos de elementos, es hora de codificar el juego en sí.

while True:
    print("Game: ", games)
    user_choice = input("What's your pick (r)ock, (p)aper, or (s)cissors? ")
    AI_choice = random.choice(choices)
    print("AI chose: ", AI_choice)

    #this statement cover no input or pressing enter when asked for a choice so the game restarts
    if len(user_choice) == 0:
        print("invalid option. Try again!")
        time.sleep(1)
        continue

    #this if statement covers all 3 draw possibilities leaving 6 other strategies possible only
    if user_choice[0].lower() == AI_choice:
        print("DRAW!")
        time.sleep(1)
        continue

The whole game runs inside a while loop that will contain a break once all rounds are played. The loop is true for the conditions needed to be met till the end of the game. The fist action is to create a question for the user to provide input. We need to ask the user's option, then make the program chose one, and finally establish a comparison to assign payoff or points according to the strategies selected.

As you can imagine, the user might input an option win different forms like: rock, ROCK, Rock, r, or just something completely different. That is the reason for the first two if statements. IF the user provides a completely different input, or no input at all, the first IF statement will carry the user back to the beginning through the use of "continue." The second IF statement contemplates the possibility of a draw. IF the user choice and the AI choice are the same, a draw happen and that round is not counted to determine the winner, so the program just start over in the round it was.

Todo el juego se ejecuta dentro de un bucle while que contendrá un descanso una vez que se hayan jugado todas las rondas. El bucle es cierto para las condiciones que deben cumplirse hasta el final del juego. La primera acción es crear una pregunta para que el usuario proporcione información. Necesitamos preguntar la opción del usuario, luego hacer que el programa elija una y finalmente establecer una comparación para asignar pagos o puntos de acuerdo con las estrategias seleccionadas.

Como puede imaginar, el usuario puede ingresar una opción en diferentes formas como: rock, ROCK, Rock, r, o simplemente algo completamente diferente. Esa es la razón de las dos primeras sentencias if. SI el usuario proporciona una entrada completamente diferente, o ninguna entrada, la primera instrucción IF llevará al usuario de vuelta al principio mediante el uso de "continuar". La segunda sentencia SI contempla la posibilidad de empate. SI la elección del usuario y la elección de la IA son las mismas, ocurre un sorteo y esa ronda no se cuenta para determinar el ganador, por lo que el programa simplemente comienza de nuevo en la ronda que era.

#rock strtegies
    elif user_choice[0].lower() == "r" and AI_choice == "s":
        print("You win!")
        time.sleep(1)
        user_score = user_score + 1

    elif user_choice[0].lower() == "r" and AI_choice == "p":
        print("AI wins!")
        time.sleep(1)
        AI_score = AI_score + 1

    #paper strategies
    elif user_choice[0].lower() == "p" and AI_choice == "r":
        print("You win!")
        time.sleep(1)
        user_score = user_score + 1

    elif user_choice[0].lower() == "p" and AI_choice == "s":
        print("AI wins!")
        time.sleep(1)
        AI_score = AI_score + 1

    #scissors strategies
    elif user_choice[0].lower() == "s" and AI_choice == "r":
        print("AI wins!")
        time.sleep(1)
        AI_score = AI_score + 1

    elif user_choice[0].lower() == "s" and AI_choice == "p":
        print("You win!")
        time.sleep(1)
        user_score = user_score + 1

    else:
        print("Invalid answer. Try again!")

The longer part of the code is the options for comparison. As stated above in the matrix, there are six possible option not leading to a draw in this game. Each one was created through an ELIF statement. Notice how the user choice only takes the first, lower case letter from the input. Immediately after the user provides its option, the AI chooses one, the comparison happens, and the score is added to the pertinent variable.

La parte más larga del código son las opciones de comparación. Como se indicó anteriormente en la matriz, hay seis opciones posibles que no conducen a un empate en este juego. Cada uno fue creado a través de una declaración ELIF. Observe cómo la elección del usuario solo toma la primera letra minúscula de la entrada. Inmediatamente después de que el usuario proporciona su opción, la IA elige una, se realiza la comparación y se agrega el puntaje a la variable pertinente.

 games = games + 1
    if games == 6:
        break

#total scores and winner of the rounds
print()
print("User wins: ", user_score)
print("AI wins: ", AI_score)
print()

if user_score > AI_score:
    print("Congratulations! You won!")
elif AI_score > user_score:
    print("Great day for the machines! \n AI wins!")
else:
    print("Draw!")

The last part contains the break logic and the totals. Inside the while loop, a break function allows to stop the game once all five rounds have been played. After that, we just need the program to print the respective scores, and then make a comparison to determine the winner. This is done by a simple IF statement using the variables that have been storing the scores this far.

La última parte contiene la lógica de ruptura y los totales. Dentro del bucle while, una función de interrupción permite detener el juego una vez que se han jugado las cinco rondas. Después de eso, solo necesitamos que el programa imprima los puntajes respectivos y luego haga una comparación para determinar el ganador. Esto se hace mediante una declaración IF simple usando las variables que han estado almacenando los puntajes hasta el momento.

Screenshot 2022-04-11 161721.jpg

Here you can see the game ran directly. The program keeps the count of games, takes the option even though I used an upper case, and then it provides a winner. The only aspect for this game to have some intelligence is for the program to detect a pattern in the options selected by the user. That way (and as we do in real life) the option provided by AI could attempt to win instead of just randomly select its option. Sadly, that goes beyond my newbie coding skills, but it would be the best choice for this game I think.

Aquí puedes ver el juego ejecutado directamente. El programa lleva la cuenta de los juegos, toma la opción a pesar de que usé mayúsculas y luego proporciona un ganador. El único aspecto para que este juego tenga algo de inteligencia es que el programa detecte un patrón en las opciones seleccionadas por el usuario. De esa manera (y como lo hacemos en la vida real), la opción proporcionada por la IA podría intentar ganar en lugar de simplemente seleccionar su opción al azar. Lamentablemente, eso va más allá de mis habilidades de codificación de novato, pero creo que sería la mejor opción para este juego.



@gaaeljosser
Python for Windows
Visual Studio Code v1.66.0
Image source for cover

Sort:  

Excelente artículo @gaeljosser, la programación es sin duda el idioma del mundo digital; y el presente y futuro de Python es inminente para cualquier profesión, inclusive para los juegos. Saludos!

 2 years ago  

Muchas gracias. Ciertamente tiene ventajas sobre otros lenguajes, y es un buen punto de partida para aprender la logica detras de la programación en general.

¡Hola Mundo!
Novato por ahora, ya te veré en unos meses 😜

 2 years ago  

jeje baby steps!

¡Me encanta! luego de esto viene interfaz grafica y luego un RPG. Esta genial aprender este lenguaje de programación, llegara un punto (sino es que ya estamos en el) en que, independientemente de la carrera, debes saber sobre este lenguaje.

 2 years ago  

Mi profesor uso python para crear un programa que captara los pixeles de la pantalla en el juego original de Mario Bros, y con eso lograba que el programa ejecutara las acciones de Mario de acuerdo al cambio de pixeles que tenia al frente. Si eran verdes, mario debia saltar porque era un tubo, y asi. Tambien pienso que la programacion sera necesaria en algun grado para todos conforme el mundo digital crezca.

 2 years ago  

waooo amogo tremendo contendo. Eres valiente. El codigo no es complejo pero contienes lo primero que el desglose del algoritmo y la logica. Creo que es lo principal todo lo demas queda en practica. Si continuas tienes un futuro grande. 👍👍

 2 years ago  

Muchas gracias! poco a poco voy aprendiendo.


The rewards earned on this comment will go directly to the person sharing the post on Twitter as long as they are registered with @poshtoken. Sign up at https://hiveposh.com.


Colmena-Curie.jpg

¡Felicidades! Esta publicación obtuvo upvote y fue compartido por @la-colmena, un proyecto de Curación Manual para la comunidad hispana de Hive que cuenta con el respaldo de @curie.

Si te gusta el trabajo que hacemos, te invitamos a darle tu voto a este comentario y a votar como testigo por Curie.

Si quieres saber más sobre nuestro proyecto, acompáñanos en Discord: La Colmena.


 2 years ago  

Gracias por el apoyo

Your content has been voted as a part of Encouragement program. Keep up the good work!

Use Ecency daily to boost your growth on platform!

Support Ecency
Vote for new Proposal
Delegate HP and earn more

 2 years ago  

thanks for the support