diff --git a/lab-python-flow-control.ipynb b/lab-python-flow-control.ipynb index 7905339..d1c1ca1 100644 --- a/lab-python-flow-control.ipynb +++ b/lab-python-flow-control.ipynb @@ -31,30 +31,29 @@ "id": "7086f8f7-ded2-48e5-b966-7ec44fb57ca5", "metadata": {}, "source": [ - "You are a brave adventurer who has decided to explore the Haunted Mansion, a decrepit old building that is rumored to be haunted by ghosts and spirits. Your objective is to find the treasure that is hidden somewhere in the mansion.\n", + "Eres un valiente aventurero que ha decidido explorar la Mansión Encantada, un antiguo edificio decrépito que se rumorea que está perseguido por fantasmas y espíritus. Tu objetivo es encontrar el tesoro que se esconde en algún lugar de la mansión.\n", "\n", - "## Requirements\n", + "## Requisitos\n", "\n", - "- Your script should have at least two functions: \"run_mansion()\" and \"encounter_ghost()\".\n", - "- Your script should use if-else statements, while loops, for loops, combined loops, or nested loops to control the flow of execution.\n", - "- Your script should prompt the user for input to make decisions on which path to take or what actions to perform.\n", - "- Your script should include random events and obstacles that can either help or hinder the adventurer in their quest.\n", - "- Your script should have an objective of finding the treasure at the end of the mansion.\n", + "- Tu script debe tener al menos dos funciones: \"run_mansion()\" y \"encounter_ghost()\".\n", + "- Su secuencia de comandos debe utilizar sentencias if-else, bucles while, bucles for, bucles combinados o bucles anidados para controlar el flujo de ejecución.\n", + "- Su secuencia de comandos debe solicitar al usuario información para tomar decisiones sobre qué camino tomar o qué acciones realizar.\n", + "- Tu guión debe incluir eventos y obstáculos aleatorios que puedan ayudar o dificultar al aventurero en su búsqueda.\n", + "- Tu guión debe tener como objetivo encontrar el tesoro al final de la mansión.\n", "\n", - "## Instructions\n", + "## Instrucciones\n", "\n", - "- Begin by creating a list of items that the adventurer can pick up along the way. These items will be used to help the adventurer overcome obstacles and defeat ghosts. Examples of items can be weapons, potions, keys, etc.\n", + "- Comienza creando una lista de elementos que el aventurero puede recoger en el camino. Estos elementos se utilizarán para ayudar al aventurero a superar obstáculos y derrotar fantasmas. Ejemplos de elementos pueden ser armas, pociones, llaves, etc.\n", "\n", - "- Complete the function called \"run_mansion()\" that serves as the main function for the game. Within \"run_mansion()\", prompt the user to choose a path to take at each intersection. Each path should have its unique challenges and obstacles that the adventurer must overcome.\n", + "- Completa la función llamada \"run_mansion()\" que sirve como función principal del juego. Dentro de \"run_mansion()\", solicite al usuario que elija un camino a seguir en cada intersección. Cada camino debe tener sus desafíos y obstáculos únicos que el aventurero debe superar.\n", "\n", - "- Use loops to check if the adventurer has enough health points to continue the game. If their health points drop to zero, the game is over.\n", + "- Usa bucles para comprobar si el aventurero tiene suficientes puntos de salud para continuar el juego. Si sus puntos de salud caen a cero, el juego termina.\n", "\n", - "- Complete the function called \"encounter_ghost()\" that will be used to handle ghost encounters. The function should use random events to determine the outcome of the encounter, and the adventurer should use their items to help them defeat the ghost.\n", + "- Completa la función llamada \"encounter_ghost()\" que se utilizará para manejar los encuentros con fantasmas. La función debe usar eventos aleatorios para determinar el resultado del encuentro, y el aventurero debe usar sus elementos para ayudarlo a derrotar al fantasma.\n", "\n", - "- Use loops to generate random events or items along the way. These events can either help or hinder the adventurer, and the outcome should be based on random chance.\n", + "- Utilice bucles para generar eventos o elementos aleatorios a lo largo del camino. Estos eventos pueden ayudar o perjudicar al aventurero, y el resultado debe basarse en el azar.\n", "\n", - "- At the end of the mansion, the adventurer will find the treasure, and the game will end.\n", - "\n" + "- Al final de la mansión, el aventurero encontrará el tesoro y el juego finalizará." ] }, { @@ -64,36 +63,66 @@ "source": [ "*Introduction to Functions*:\n", "\n", - " Functions are blocks of code that perform a specific task. They are used to break up complex code into smaller, more manageable parts, which can make your code easier to read and understand. Functions can also be reused multiple times throughout your code, which can save you a lot of time and effort.\n", + " Las funciones son bloques de código que realizan una tarea específica. Se utilizan para dividir código complejo en partes más pequeñas y manejables, lo que puede hacer que su código sea más fácil de leer y comprender. Las funciones también se pueden reutilizar varias veces en el código, lo que puede ahorrarle mucho tiempo y esfuerzo.\n", "\n", - " Functions are defined using the def keyword, followed by the name of the function and a set of parentheses. Inside the parentheses, you can list any arguments that the function needs in order to perform its task. These arguments are optional, but they can be useful if you need to pass data into the function from outside.\n", + " Las funciones se definen utilizando la palabra clave def, seguida del nombre de la función y un conjunto de paréntesis. Dentro de los paréntesis, puede enumerar los argumentos que la función necesita para realizar su tarea. Estos argumentos son opcionales, pero pueden resultar útiles si necesita pasar datos a la función desde fuera.\n", "\n", - " Once you have defined a function, you can call it from anywhere in your code using its name and passing any necessary arguments. When the function is called, the code inside it is executed, and any values that it returns are passed back to the calling code.\n", + " Una vez que haya definido una función, puede llamarla desde cualquier lugar de su código usando su nombre y pasando los argumentos necesarios. Cuando se llama a la función, el código que contiene se ejecuta y cualquier valor que devuelva se devuelve al código de llamada.\n", "\n", - " In this exercise, we have defined a function called encounter_ghost that simulates a battle between the adventurer and a ghost, and run_mansion. Your task is to complete these functions by using flow control statements such as if, else, while, for loops, and nested loops. Remember to pay attention to the instructions and comments provided in the function to help guide you. Once you have completed the function encounter_ghost, you can call it from the main code to simulate the battle and test your implementation.\n", + " En este ejercicio hemos definido una función llamada encuentro_ghost que simula una batalla entre el aventurero y un fantasma, y ​​run_mansion. Su tarea es completar estas funciones mediante el uso de declaraciones de control de flujo como bucles if, else, while, for y anidados. Recuerda prestar atención a las instrucciones y comentarios proporcionados en la función para ayudarte a guiarte. Una vez que hayas completado la función encuentro_ghost, puedes llamarla desde el código principal para simular la batalla y probar tu implementación.\n", "\n", - " Good luck!" + " ¡Buena suerte!" ] }, { "cell_type": "code", - "execution_count": null, - "id": "499552c8-9e30-46e1-a706-4ac5dc64670e", + "execution_count": 1, + "id": "5544c6b8", "metadata": {}, "outputs": [], + "source": [ + "import random" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "499552c8-9e30-46e1-a706-4ac5dc64670e", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "You encounter a ghost!\n", + "7\n", + "You lost the battle...\n", + "el fantastma te derrotó\n" + ] + } + ], "source": [ "def encounter_ghost():\n", - " \"\"\"\n", - " This function handles the encounter with a ghost. \n", + " \"\"\"\n", + " This function handles encountering a ghost. \n", " The outcome of the battle is determined by a random number between 1 and 10.\n", " If the random number is less than or equal to 5, the adventurer defeats the ghost. In this case, print the message \"You defeated the ghost!\" \n", - " and return something that indicates the adventurer defeated the ghost.\n", - " If the random number is greater than 5, the adventurer loses the battle. In this case, print \"You lost the battle...\"\n", - " and return something that indicates the ghost defeated the adventurer.\n", + " and return something that indicates that the adventurer defeated the ghost.\n", + " If the random number is greater than 5, the adventurer loses the battle. In this case, write \"You lost the battle...\"\n", + " and return something that indicates that the ghost defeated the adventurer.\n", " \"\"\"\n", - " print(\"You encounter a ghost!\")\n", - " \n", - " # your code goes here" + " print (\"You encounter a ghost!\")\n", + " ataque_de_ghost = random.randint(1,10)\n", + " print(ataque_de_ghost)\n", + " if ataque_de_ghost <= 5:\n", + " print(\"You defeated the ghost!\")\n", + " return \"puedes seguir la aventura\"\n", + " elif ataque_de_ghost > 5:\n", + " print(\"You lost the battle...\")\n", + " return \"el fantastma te derrotó\"\n", + " \n", + "batalla = encounter_ghost()\n", + "print(batalla)" ] }, { @@ -107,30 +136,109 @@ "def run_mansion():\n", " \n", " print(\"Welcome to the Haunted Mansion!\")\n", - " \n", " \"\"\"\n", - " Simulates an adventure through a haunted mansion. The adventurer starts with 10 health points and no items.\n", + " Simulate an adventure through a haunted mansion. The adventurer starts with 10 life points and no items.\n", " Prompt the user to choose between two paths: \"left\" or \"right\". \n", "\n", - " If they choose \"left\", a random event occurs. There is a 50% chance that the adventurer will find a potion and a 50% chance that they will \n", - " fall into a trap and lose 2 health points. If they find the potion, it is saved into the adventurer's items. \n", - " If they fall into a trap, 2 points are taken out of the adventurer's health points.\n", + " If they choose \"left\", a random event occurs. There is a 50% chance that the adventurer will find a potion and a 50% chance that they will find it. \n", + " fall into a trap and lose 2 life points. If they find the potion, it is stored in the adventurer's items. \n", + " If they fall into a trap, 2 life points are subtracted from the adventurer.\n", "\n", - " If they choose \"right\", the \"encounter_ghost()\" function is called to handle the battle between the adventurer and the ghost. \n", - " If the adventurer wins, they find a key which is saved into the adventurer's items. If they lose, they lose 2 health points.\n", - " Hint: remember to check what encounter_ghost() returned to make know if they won or lost.\n", + " If they choose \"correct\", the \"encounter_ghost()\" function is called to handle the battle between the adventurer and the ghost. \n", + " If the adventurer wins, he finds a key that is kept in the adventurer's items. If they lose, they lose 2 life points.\n", + " Tip: Remember to check what encounter_ghost() returned to see if they won or lost.\n", "\n", - " If the adventurer chooses something other than \"left\" or \"right\", they are prompted to try again.\n", + " If the adventurer chooses something other than \"left\" or \"right\", they will be prompted to try again.\n", "\n", - " If the adventurer's health points reach 0 or less, the message \"Game over, you lost all your health points.\" is printed.\n", + " If the adventurer's life points reach 0 or less, the message \"Game over, you lost all your life points\" will appear. is printed.\n", "\n", - " If the adventurer has the key, they can unlock the door and find the Treasure. This message is printed \"You unlocked the door and found the \n", - " Treasure! Congratulations!\".\n", - " If they don't have the key, they are prompted to find it from the beginning.\n", + " If the adventurer has the key, they can open the door and find the Treasure. This message is printed \"You opened the door and found the \n", + " Treasure! Congratulations!\"\n", + " If they don't have the key, they will be prompted to look it up from the beginning.\n", "\n", " \"\"\"\n", - " \n", - " # your code goes here" + " " + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "126fabb3", + "metadata": {}, + "outputs": [], + "source": [ + "def run_mansion():\n", + " print(\"Welcome to the Haunted Mansion!\")\n", + " \"\"\"\n", + " Simulate an adventure through a haunted mansion. The adventurer starts with 10 life points and no items.\n", + " Prompt the user to choose between two paths: \"left\" or \"right\". \n", + " \n", + " If they choose \"left\", a random event occurs. There is a 50% chance that the adventurer will find a potion and a 50% chance that they will find it. \n", + " fall into a trap and lose 2 life points. If they find the potion, it is stored in the adventurer's items. \n", + " If they fall into a trap, 2 life points are subtracted from the adventurer.\n", + " \n", + " If they choose \"correct\", the \"encounter_ghost()\" function is called to handle the battle between the adventurer and the ghost. \n", + " If the adventurer wins, he finds a key that is kept in the adventurer's items. If they lose, they lose 2 life points.\n", + " Tip: Remember to check what encounter_ghost() returned to see if they won or lost.\n", + " \n", + " If the adventurer chooses something other than \"left\" or \"right\", they will be prompted to try again.\n", + " \n", + " If the adventurer's life points reach 0 or less, the message \"Game over, you lost all your life points\" will appear. is printed.\n", + " \n", + " If the adventurer has the key, they can open the door and find the Treasure. This message is printed \"You opened the door and found the \n", + " Treasure! Congratulations!\"\n", + " If they don't have the key, they will be prompted to look it up from the beginning.\n", + " \n", + " \"\"\"\n", + " \n", + " nombre = input(\"Escribe el nombre de tu personaje\")\n", + " runner = {nombre : {'vida' : 10 , \"objetos\":[]}}\n", + " print(f\"¡Hola {nombre}! Empiezas una nueva aventura, en la mansion encantada con 10 de vida y 0 objetos\")\n", + " \n", + " while True:\n", + " print(f\"Recuerda que debes elegir entre el camino de la (izquierda) o de la (derecha), suerte!\")\n", + " print(f\"{nombre}! Sigues en la aventura con:{runner[nombre]}\")\n", + "\n", + " while True:\n", + " \n", + " ruta = input(\"¿Que camino vas a elegir? escribe 'izquierda' o 'derecha'):\").lower()\n", + " if ruta == 'izquierda' or ruta == 'derecha':\n", + " break\n", + " else:\n", + " print(\"opcion invalida, solo puedes elegir el camino de la 'izquierda' o 'derecha'.\")\n", + " \n", + " if ruta == \"izquierda\":\n", + " evento_aleatorio = random.randint(1,2)\n", + " print(evento_aleatorio)\n", + " \n", + " if evento_aleatorio == 1:\n", + " print(\"Genial! encontraste una 'pocion'.\")\n", + " runner[nombre][\"objetos\"].append(\"pocion\")\n", + " runner[nombre][\"vida\"] += 1\n", + " print(\"tomaste la pocion y sanaste +1\")\n", + "\n", + " elif evento_aleatorio == 2:\n", + " print(\"Rayos! caiste en una trampa electrica, perdiste 2 puntos\")\n", + " runner[nombre][\"vida\"] -= 2 \n", + "\n", + " elif ruta == \"derecha\":\n", + " batalla = encounter_ghost()\n", + " if batalla == \"puedes seguir la aventura\":\n", + " print(\"¡Excelente! recogiste la 'llave' del cuerpo del fantasma\")\n", + " runner[nombre][\"objetos\"].append(\"llave\") \n", + " else:\n", + " print(f\"perdiste 2 puntos de vida, tu vida actual es: {runner[nombre]['vida']}\")\n", + " runner[nombre][\"vida\"] -= 2\n", + " \n", + "\n", + " if runner[nombre][\"vida\"] <= 0:\n", + " print(\"Game over, you lost all your life points\")\n", + " break\n", + " elif \"llave\" in runner[nombre][\"objetos\"]:\n", + " print(\"You opened the door and found the Treasure! Congratulations!\")\n", + " return runner\n", + " else:\n", + " print(\"Aun no puedes salir de la mansion, vuelve y sigue intentando\") " ] }, { @@ -143,10 +251,59 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 11, "id": "f238dc90-0be2-4d8c-93e9-30a1dc8a5b72", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Welcome to the Haunted Mansion!\n", + "¡Hola JUCASKYWALKER! Empiezas una nueva aventura, en la mansion encantada con 10 de vida y 0 objetos\n", + "Recuerda que debes elegir entre el camino de la (izquierda) o de la (derecha), suerte!\n", + "JUCASKYWALKER! Sigues en la aventura con:{'vida': 10, 'objetos': []}\n", + "2\n", + "Rayos! caiste en una trampa electrica, perdiste 2 puntos\n", + "Aun no puedes salir de la mansion, vuelve y sigue intentando\n", + "Recuerda que debes elegir entre el camino de la (izquierda) o de la (derecha), suerte!\n", + "JUCASKYWALKER! Sigues en la aventura con:{'vida': 8, 'objetos': []}\n", + "2\n", + "Rayos! caiste en una trampa electrica, perdiste 2 puntos\n", + "Aun no puedes salir de la mansion, vuelve y sigue intentando\n", + "Recuerda que debes elegir entre el camino de la (izquierda) o de la (derecha), suerte!\n", + "JUCASKYWALKER! Sigues en la aventura con:{'vida': 6, 'objetos': []}\n", + "1\n", + "Genial! encontraste una 'pocion'.\n", + "tomaste la pocion y sanaste +1\n", + "Aun no puedes salir de la mansion, vuelve y sigue intentando\n", + "Recuerda que debes elegir entre el camino de la (izquierda) o de la (derecha), suerte!\n", + "JUCASKYWALKER! Sigues en la aventura con:{'vida': 7, 'objetos': ['pocion']}\n", + "You encounter a ghost!\n", + "7\n", + "You lost the battle...\n", + "perdiste 2 puntos de vida, tu vida actual es: 7\n", + "Aun no puedes salir de la mansion, vuelve y sigue intentando\n", + "Recuerda que debes elegir entre el camino de la (izquierda) o de la (derecha), suerte!\n", + "JUCASKYWALKER! Sigues en la aventura con:{'vida': 5, 'objetos': ['pocion']}\n", + "You encounter a ghost!\n", + "1\n", + "You defeated the ghost!\n", + "¡Excelente! recogiste la 'llave' del cuerpo del fantasma\n", + "You opened the door and found the Treasure! Congratulations!\n" + ] + }, + { + "data": { + "text/plain": [ + "{'JUCASKYWALKER': {'vida': 5, 'objetos': ['pocion', 'llave']}}" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "run_mansion()" ] @@ -162,7 +319,7 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 3 (ipykernel)", + "display_name": "base", "language": "python", "name": "python3" }, @@ -176,7 +333,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.14.6" } }, "nbformat": 4,