¿Dados otra vez? Craps! | C++

avatar

Programación.jpg

¿Qué tal todo? Por acá traigo otra publicación de programación, luego de un tiempo sin publicar de esta temática por falta de tiempo para el compilador y también porque estaba actualizando el sistema de mi PC, ahora estoy más cómodo con respecto a dónde puedo hacer mis programas de C++.

El programa de hoy trata sobre el juego de dados "Craps", que según la historia viene de otros juegos de azar mucho más viejos, ya sea desde los romanos o las apuestas callejeras, el azar ha estado presente desde hace mucho, provocando conflictos y enriqueciendo temporalmente a algún supuesto afortunado que luego fue víctima del engaño del placer, derrochando todo y arrastrándose hacia la avaricia para tratar de repetir aquellos números que trajeron ese frenesí de emociones.

El enunciado que me llevó a crearlo viene de la materia "Taller de programación", un compañero me lo envió y decidí tratar de resolverlo. En enero estaba en ello pero lo había dejado incompleto por causa de otros proyectos así que lo retomé. Este es el enunciado:

El juego de dados conocido como “craps” (tiro perdedor) es muy popular, realice un programa que simule dicho juego, a continuación se muestran las reglas: Un jugador tira dos dados. Cada dato tiene seis caras. Las caras contienen 1, 2, 3, 4, 5 y 6 puntos.

Una vez que los dados se hayan detenido, se calcula la suma de los puntos en las dos caras superiores. Si a la primera tirada, la suma es 7, o bien 11, el jugador gana. Si a la primera tirada la suma es 2, 3 o 12 (conocido como “craps”), el jugador pierde (es decir la casa “gana”). Si a la primera tirada la suma es 4, 5, 6, 8, 9 ó 10, entonces dicha suma se convierte en el “punto” o en la “tirada”. Para ganar, el jugador deberá continuar tirando los dados hasta que haga su “tirada”.

Hay otras modalidades para evitar el bucle de espera entre 7 y la nueva "tirada" pero para este enunciado no están incluidos. De todas maneras no estaría mal incluirlos en una futura versión.

How is everything? Here I bring another programming publication, after a while without publishing on this subject due to lack of time for the compiler and also because I was updating my PC system, now I am more comfortable with respect to where I can make my C++ programs.

Today's program is about the dice game "Craps", which according to history comes from other much older games of chance, either from the Romans or street betting, chance has been around for a long time, causing conflicts and temporarily enriching some supposedly lucky person who then fell victim to the lure of pleasure, squandering everything and crawling towards greed to try to repeat those numbers that brought that frenzy of emotions.

The statement that led me to create it comes from the subject "Programming Workshop", a classmate sent it to me and I decided to try to solve it. In January I was working on it but I had left it incomplete because of other projects so I took it up again. This is the statement:

The dice game known as "craps" (losing throw) is very popular, make a program that simulates such a game, below are the rules: A player rolls two dice. Each die has six faces. The faces contain 1, 2, 3, 4, 5 and 6 points.

Once the dice have come to rest, the sum of the points on the top two faces is calculated. If on the first roll, the sum is 7, or 11, the player wins. If on the first roll the sum is 2, 3 or 12 (known as "craps"), the player loses (i.e. the house "wins"). If on the first roll the sum is 4, 5, 6, 8, 9 or 10, then that sum becomes the "point" or the "roll". To win, the player must continue rolling the dice until he makes his "roll".

There are other ways to avoid the waiting loop between 7 and the new "roll" but for this statement they are not included. However, it would not be bad to include them in a future version.

Programación c++.png

Para comencé usé las librerías que ya son conocidas en varios de los programas que he hecho. Para cubrir la entrada y salida, pausas de pantalla y limpiezas de pantalla. Sin embargo, incluí una librería personalizada, esta incluye todas las letras y números a graficar en pantalla. Este código lo expliqué en los post 16-18 y 24-27.

Hice una pequeña corrección al incluir las librerías "iostream, windows.h, conio.h ..." en la librería personalizada; para este programa apliqué clases y objetos, esto para crear un "jugador" de modo que puedo asignar un estado para saber si ganó o no, un tag para el bucle dentro de los condicionales y los "puntos", es decir la sumatoria de los números en los dados que luego serán comparadas. Además de los setters y getters añadí un par de funciones para el futuro, estas incluyen el cambio de estado y el reseteo de puntos.

La función portada muestra en pantalla las letras "CRAPS", esta será la primera pantalla que se mostrará al abrir el programa, el posicionamiento se apoya en la función gotoxy. La función que sigue se apoya en dos ceros para hacer recuadros para representar los dados, esta es fondo_dados.

To start with I used the libraries that are already known from several of the programs I have made. To cover input and output, screen pauses and screen clearing. However, I included a custom library, this one includes all the letters and numbers to be plotted on the screen. I explained this code in posts 16-18 and 24-27.

I made a small correction by including the libraries "iostream, windows.h, conio.h ..." in the custom library; for this program I applied classes and objects, this to create a "player" so that I can assign a state to know if it won or not, a tag for the loop inside the conditionals and the "points", that is the sum of the numbers in the dice that will be compared later. In addition to the setters and getters I added a couple of functions for the future, these include changing state and resetting points.

The cover function displays the letters "CRAPS" on the screen, this will be the first screen to be displayed when the program is opened, the positioning is supported by the gotoxy function. The function that follows relies on two zeros to make boxes to represent the dice, this is dice_background.

image.png

image.png

image.png

image.png

Programación c++.png

La función principal es "selector", esta tiene el sistema necesario para que el juego se lleve a cabo. Usé la función rand() para que se creara al azar el número, de modo que se simulen los dados. Esto lo había hecho en la publicación "dados aleatorios". Una vez se generan los números, son asignados a través de set_puntos, luego la función filter muestra en pantalla el grafico correspondiente al número generado, esta función ya la había usado antes, en la publicación de dados antes mencionada.
Los condicionales se enfocan en tomar un camino según el número generado por el lanzamiento, basados en el enunciado donde 2,3 o 12 significa que el usuario perdió, un 7 en el primer lanzamiento es victoria y un número ajeno a estos mencionados será marcado como tirada ganadora para posteriormente ser junto al 7 las dos posibles vías para finalizar la partida. De ser 7 en una tirada que no es la inicial será derrota al jugador, de ser el número marcado será victoria, si no es ninguna de estas entonces seguirá tirando.

Hasta ahora el atributo "status" es prácticamente inútil, esto porque lo tengo pensado para partidas entre dos jugadores, posiblemente en el futuro traiga una nueva versión que incluya más modalidades. El atributo "tag" funciona como llave para el bucle do-while que inicia cuando la primera lanzada no cumple con un 7 victorioso o un 2,3 u 12 de fracaso.

The main function is "selector", this has the necessary system for the game to take place. I used the rand() function to randomly create the number, so that the dice are simulated. I had done this in the "random dice" post. Once the numbers are generated, they are assigned through set_points, then the filter function displays on screen the graph corresponding to the generated number, I had used this function before, in the dice publication mentioned above.

The conditionals are focused on taking a path according to the number generated by the roll, based on the statement where 2,3 or 12 means that the user lost, a 7 in the first roll is victory and a number other than these mentioned will be marked as a winning roll to later be together with the 7 the two possible ways to finish the game. A 7 in a roll that is not the initial one will be a defeat to the player, if it is the marked number it will be a victory, if it is none of these then the player will continue to roll.

Until now the attribute "status" is practically useless, this because I have thought it for games between two players, possibly in the future I will bring a new version that includes more modalities. The attribute "tag" works as a key for the do-while loop that starts when the first roll does not meet a 7 victorious or a 2,3 or 12 failure.

image.png

image.png

image.png

image.png

image.png

image.png

Programación c++.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png


Victoria por primer lanzamiento

image.png

Programación c++.png

Programación c++.png

¡Y bueno... Eso es todo por hoy! Recuerda que el efecto gambler puede condenar todos tus ahorros, la casa casi siempre gana así que no caigas en sus garras. Cuídate de la ludopatía antes de que una deuda te condene algún ser querido o... extremidad.

Si te interesa otro tutorial de programación acá te dejo los links a los que he realizado hasta ahora:

And well... That's all for today! Remember that the gambler effect can doom all your savings, the house almost always wins so don't fall into its clutches. Beware of compulsive gambling before a debt condemns you a loved one or... limb.

If you are interested in another programming tutorial here are the links to the ones I have done until now:


Título/TittleLINKTítulo/TittleLINK
Calculador de datos para un triángulo rectángulo en C++1Graficando números en consola (0-3) C++16
Concecionario de autos, ejercicio en JAVA2Graficando números en consola II (4-6) C++17
Calculador de edad básico C++3Graficando números en consola III (7-9) C++18
Inversor de números de tres cifras4Calculadora de ecuaciones cuadráticas C++19
¿Cuántos números de 3 cifras existen cuya suma sea 10? - ¡Respondiendo a otro usuario! C++5Dados digitales C++20
Calculadora simple, cifra menos significativa y portada simple C++6Fichas biográficas de próceres C++21
¡Vistazo a BeatUDO! JAVA7Calculadora de divisores C++22
Comprobar si un número de dos cifras es primo C++8Calculadora de divisores II C++23
Conversor de pulgadas a 7 unidades distintas C++9Graficando letras en consola I (ABCDE) C++24
Comprobar si un número es capicúa (Máx 5 cifras) C++10Graficando letras en consola II (FGHIJ) C++25
Comprobador de caracteres C++11Graficando letras en consola III (KLMNO) C++26
Calculadora de índice de masa corporal C++12Graficando letras en consola V (UVWXYZ) C++27
Calculadora de factoriales C++13Generador de letras aleatorias C++28
Conversor (Grados Celsius - Fahrenheit - Kelvin) C++14Verificador de generación C++29
Calculadora de longitud, diametro y área de una circunferencia C++15XX

Programación c++.png


Redes actualizada.gif


Puedes seguirme por acá si lo deseas:
You can follow me here if you want:

Cuenta secundaria
(Dibujos, edición y juegos) | Secondary account (Drawings, editing and games)



0
0
0.000
7 comments
avatar

Que epico tu codigo, me encantan leer tus publicaciones y ver cada una de las lineas de codigo que has colocado. Pero lo que mas me ha encantado es la forma en que se ven tus dados en la terminal, como si fuera una interfaz de cuando los programas eran de puro texto.

0
0
0.000
avatar

Graaacias, trato de ir mejorando aunque ha estado potente este comienzo de año con improvistos y ocurrencias de la universidad

0
0
0.000
avatar

Gracias gabrielr29 por acompañarnos en PROMUEVE TU PUBLICACIÓN , estamos para apoyarte y te esperamos el próximo miércoles a las 9:15 en nuestro Canal de Discord

0
0
0.000
avatar

Congratulations @gabrielr29! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s):

You distributed more than 8000 upvotes.
Your next target is to reach 9000 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Check out the last post from @hivebuzz:

Hive Power Up Month - Feedback from February day 15
Support the HiveBuzz project. Vote for our proposal!
0
0
0.000