Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
175 changes: 162 additions & 13 deletions lab-python-flow-control.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,16 @@
"- 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",
"\n",
"Eres un valiente aventurero que ha decidido explorar la Mansión Encantada, un viejo y decrépito edificio que, según se rumorea, está embrujado por fantasmas y espíritus. Tu objetivo es encontrar el tesoro escondido en algún lugar de la mansión.\n",
"\n",
"## Requisitos\n",
"\n",
"- Tu script debe tener al menos dos funciones: \"run_mansion()\" y \"encounter_ghost()\".\n",
"- Tu script debe usar sentencias if-else, bucles while, bucles for, bucles combinados o bucles anidados para controlar el flujo de ejecución.\n",
"- Tu script debe solicitar al usuario información para decidir qué camino tomar o qué acciones realizar.\n",
"- Tu script debe incluir eventos aleatorios y obstáculos que puedan ayudar o dificultar al aventurero en su búsqueda.\n",
"- Tu script debe tener como objetivo encontrar el tesoro al final de la mansión.\n",
"\n",
"## Instructions\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",
Expand All @@ -54,6 +64,20 @@
"- 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",
"\n",
"- At the end of the mansion, the adventurer will find the treasure, and the game will end.\n",
"\n",
"## Instrucciones\n",
"\n",
"- Comienza a crear una lista de objetos que el aventurero puede recoger en el camino. Estos objetos le ayudarán a superar obstáculos y derrotar fantasmas. Algunos ejemplos son armas, pociones, llaves, etc.\n",
"\n",
"- Completa la función \"run_mansion()\", la función principal del juego. Dentro de \"run_mansion()\", pide al usuario que elija un camino en cada intersección. Cada camino debe tener sus propios desafíos y obstáculos que el aventurero debe superar.\n",
"\n",
"- Usa bucles para comprobar si el aventurero tiene suficientes puntos de salud para continuar la partida. Si sus puntos de salud bajan a cero, la partida termina.\n",
"\n",
"- Completa la función \"encounter_ghost()\", que se usará para gestionar los encuentros con fantasmas. La función debe usar eventos aleatorios para determinar el resultado del encuentro, y el aventurero debe usar sus objetos para derrotar al fantasma.\n",
"\n",
"- Usa bucles para generar eventos u objetos aleatorios en el camino. Estos eventos pueden beneficiar o perjudicar al aventurero, y el resultado debería basarse en el azar.\n",
"\n",
"- Al final de la mansión, el aventurero encontrará el tesoro y el juego terminará.\n",
"\n"
]
},
Expand All @@ -72,16 +96,38 @@
"\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",
"\n",
" Good luck!"
" Good luck!\n",
"\n",
"*Introducción a las Funciones*:\n",
"\n",
" Las funciones son bloques de código que realizan una tarea específica. Sirven para dividir código complejo en partes más pequeñas y manejables, lo que facilita su lectura y comprensión. Además, pueden reutilizarse varias veces a lo largo del código, lo que puede ahorrar mucho tiempo y esfuerzo.\n",
"\n",
" Las funciones se definen mediante la palabra clave def, seguida del nombre de la función y un par de paréntesis. Dentro de los paréntesis, se pueden incluir los argumentos que la función necesita para realizar su tarea. Estos argumentos son opcionales, pero pueden ser útiles si se necesita pasar datos a la función desde el exterior.\n",
"\n",
" Una vez definida una función, puedes llamarla desde cualquier parte del código usando su nombre y pasando los argumentos necesarios. Al llamar a la función, se ejecuta su código y los valores que devuelve se devuelven al código que la llama.\n",
"\n",
" En este ejercicio, hemos definido una función llamada encounter_ghost que simula una batalla entre el aventurero y un fantasma, y ​​run_mansion. Tu tarea consiste en completar estas funciones mediante sentencias de control de flujo como bucles if, else, while, for y bucles anidados. Recuerda prestar atención a las instrucciones y comentarios de la función para guiarte. Una vez completada la función encounter_ghost, puedes llamarla desde el código principal para simular la batalla y probar tu implementación.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 16,
"id": "499552c8-9e30-46e1-a706-4ac5dc64670e",
"metadata": {},
"outputs": [],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Random outcome number: 8\n",
"\n",
"You lost the battle...\n",
"ghost_wins\n"
]
}
],
"source": [
"\n",
"def encounter_ghost():\n",
" \"\"\"\n",
" This function handles the encounter with a ghost. \n",
Expand All @@ -90,15 +136,30 @@
" 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",
"\n",
" Esta función gestiona el encuentro con un fantasma.\n",
" El resultado de la batalla se determina mediante un número aleatorio entre 1 y 10.\n",
" Si el número aleatorio es menor o igual a 5, el aventurero derrota al fantasma. \n",
" En este caso, se imprime el mensaje \"¡Has derrotado al fantasma!\" y se devuelve algo que indica que el aventurero lo derrotó.\n",
" Si el número aleatorio es mayor que 5, el aventurero pierde la batalla. En este caso, se imprime \"Has perdido la batalla...\"\n",
" y se devuelve algo que indica que el fantasma derrotó al aventurero.\n",
" \"\"\"\n",
" print(\"You encounter a ghost!\")\n",
" \n",
" # your code goes here"
" import random\n",
" outcome = random.randint(1, 10)\n",
" print(f\"Random outcome number: {outcome}\") # Debugging line to see the random number\n",
" if outcome <= 5:\n",
" print(\"\\nYou defeated the ghost!\")\n",
" return \"adventurer_wins\"\n",
" else:\n",
" print(\"\\nYou lost the battle...\")\n",
" return \"ghost_wins\"\n",
"\n",
"print(encounter_ghost())"
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 20,
"id": "d3e4076b-48cc-41ac-95ad-891743e775f5",
"metadata": {},
"outputs": [],
Expand Down Expand Up @@ -127,10 +188,70 @@
" 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",
" ---------------------------------------------------------------------------------------------\n",
" Simula una aventura en una mansión embrujada. El aventurero comienza con 10 puntos de vida y sin objetos.\n",
" Se le pide al usuario que elija entre dos caminos: izquierda o derecha.\n",
"\n",
" Si elige \"izquierda\", se produce un evento aleatorio. Hay un 50 % de probabilidad de que el aventurero encuentre una poción \n",
" y un 50 % de probabilidad de que caiga en una trampa y pierda 2 puntos de vida. Si encuentra la poción, esta se guarda en sus objetos.\n",
"\n",
" Si cae en una trampa, se le restan 2 puntos de vida.\n",
"\n",
" Si elige \"derecha\", se llama a la función \"encounter_ghost()\" para gestionar la batalla entre el aventurero y el fantasma.\n",
"\n",
" Si el aventurero gana, encuentra una llave que se guarda en sus objetos. Si pierde, pierde 2 puntos de vida.\n",
" Consejo: recuerda comprobar el resultado de encounter_ghost() para saber si ganó o perdió.\n",
"\n",
" Si el aventurero elige una opción distinta a \"izquierda\" o \"derecha\", se le pedirá que lo intente de nuevo.\n",
"\n",
" Si sus puntos de salud llegan a 0 o menos, se mostrará el mensaje \"Juego terminado, has perdido todos tus puntos de salud\".\n",
"\n",
" Si el aventurero tiene la llave, puede abrir la puerta y encontrar el tesoro. Se mostrará el mensaje \"¡Has abierto la puerta y encontrado el tesoro! ¡Enhorabuena!\".\n",
" Si no tiene la llave, se le pedirá que la busque desde el principio.\n",
"\n",
" \"\"\"\n",
" \n",
" # your code goes here"
"\n",
" health_points = 10\n",
" items = []\n",
"\n",
" while health_points > 0:\n",
" choice = input(\"Choose a path (left/right): \").lower()\n",
" \n",
" if choice == \"left\":\n",
" import random\n",
" event = random.choice([\"potion\", \"trap\"])\n",
" if event == \"potion\":\n",
" print(\"You found a potion! Your health points increase by 2.\")\n",
" health_points += 2\n",
" items.append(\"potion\")\n",
" else:\n",
" print(\"You fell into a trap! You lose 2 health points.\")\n",
" health_points -= 2\n",
" \n",
" elif choice == \"right\":\n",
" result = encounter_ghost()\n",
" if result == \"adventurer_wins\":\n",
" print(\"You found a key after defeating the ghost!\")\n",
" items.append(\"key\")\n",
" else:\n",
" print(\"You lost to the ghost and lose 2 health points.\")\n",
" health_points -= 2\n",
" \n",
" else:\n",
" print(\"Invalid choice. Please choose 'left' or 'right'.\")\n",
" continue\n",
" \n",
" print(f\"Current health points: {health_points}\")\n",
" print(f\"Current items: {items}\")\n",
" \n",
" if health_points <= 0:\n",
" print(\"Game over, you lost all your health points.\")\n",
" break\n",
" \n",
" if \"key\" in items:\n",
" print(\"You unlocked the door and found the Treasure! Congratulations!\")\n",
" break\n",
" "
]
},
{
Expand All @@ -143,11 +264,39 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 21,
"id": "f238dc90-0be2-4d8c-93e9-30a1dc8a5b72",
"metadata": {},
"outputs": [],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Starting the game...\n",
"\n",
"Welcome to the Haunted Mansion!\n",
"Random outcome number: 9\n",
"\n",
"You lost the battle...\n",
"You lost to the ghost and lose 2 health points.\n",
"Current health points: 8\n",
"Current items: []\n",
"You found a potion! Your health points increase by 2.\n",
"Current health points: 10\n",
"Current items: ['potion']\n",
"Random outcome number: 4\n",
"\n",
"You defeated the ghost!\n",
"You found a key after defeating the ghost!\n",
"Current health points: 10\n",
"Current items: ['potion', 'key']\n",
"You unlocked the door and found the Treasure! Congratulations!\n"
]
}
],
"source": [
"print(\"\\nStarting the game...\\n\")\n",
"run_mansion()"
]
},
Expand All @@ -162,7 +311,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
Expand All @@ -176,7 +325,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.12.9"
}
},
"nbformat": 4,
Expand Down