Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solutions | Extra Lab Flow Control Extended #17

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
266 changes: 250 additions & 16 deletions lab-python-flow-control.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,117 @@
"\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "f5a64b56",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"You are at a crossroad. Choose a path:\n",
"1: Go left\n",
"2: Go right\n",
"3: Check inventory\n",
"4: Exit mansion\n"
]
}
],
"source": [
"# import random\n",
"\n",
"# Initialize the items that the adventurer can pick up\n",
"items = ['sword', 'shield', 'potion', 'key']\n",
"\n",
"# Initialize the player's stats\n",
"player = {\n",
" 'health': 100,\n",
" 'items': [],\n",
" 'has_key': False\n",
"}\n",
"\n",
"def encounter_ghost():\n",
" \"\"\"\n",
" Handle a ghost encounter. The outcome depends on random events and player items.\n",
" \"\"\"\n",
" ghost_strength = random.randint(1, 10)\n",
" print(f\"A ghost appears with a strength of {ghost_strength}!\")\n",
"\n",
" # Check if the player has a sword\n",
" if 'sword' in player['items']:\n",
" print(\"You use your sword to fight the ghost!\")\n",
" if ghost_strength <= 5:\n",
" print(\"You defeat the ghost easily with your sword.\")\n",
" return True\n",
" else:\n",
" player['health'] -= ghost_strength\n",
" print(f\"The ghost was too strong! You lose {ghost_strength} health.\")\n",
" return False\n",
" else:\n",
" print(\"You have no weapon to fight the ghost!\")\n",
" player['health'] -= ghost_strength\n",
" print(f\"You lose {ghost_strength} health.\")\n",
" return False\n",
"\n",
"def run_mansion():\n",
" \"\"\"\n",
" Main function to run the haunted mansion adventure game.\n",
" \"\"\"\n",
" while player['health'] > 0:\n",
" print(\"\\nYou are at a crossroad. Choose a path:\")\n",
" print(\"1: Go left\")\n",
" print(\"2: Go right\")\n",
" print(\"3: Check inventory\")\n",
" print(\"4: Exit mansion\")\n",
"\n",
" choice = input(\"Enter your choice (1-4): \").strip()\n",
"\n",
" if choice == '1':\n",
" print(\"You go left and find a treasure chest!\")\n",
" item_found = random.choice(items)\n",
" player['items'].append(item_found)\n",
" print(f\"You find a {item_found}.\")\n",
" if item_found == 'key':\n",
" player['has_key'] = True\n",
" print(\"You found a key!\")\n",
" \n",
" elif choice == '2':\n",
" print(\"You go right and encounter a ghost.\")\n",
" if not encounter_ghost():\n",
" if player['health'] <= 0:\n",
" print(\"You have been defeated by the ghost. Game over!\")\n",
" return\n",
" else:\n",
" print(\"You survived the ghost encounter.\")\n",
" \n",
" elif choice == '3':\n",
" print(\"Your inventory contains:\", player['items'])\n",
" print(f\"Your health is {player['health']}.\")\n",
" print(f\"You {'have' if player['has_key'] else 'do not have'} the key.\")\n",
" \n",
" elif choice == '4':\n",
" print(\"You decide to exit the mansion.\")\n",
" if player['has_key']:\n",
" print(\"Congratulations! You escaped the mansion with the treasure!\")\n",
" else:\n",
" print(\"You left the mansion without the treasure. Better luck next time!\")\n",
" return\n",
" \n",
" else:\n",
" print(\"Invalid choice. Please select again.\")\n",
"\n",
" # Check if the player has any health left\n",
" if player['health'] <= 0:\n",
" print(\"You have no health left. Game over!\")\n",
" return\n",
"\n",
"# Start the game\n",
"run_mansion()\n"
]
},
{
"cell_type": "markdown",
"id": "8846d61d-cf9d-4ad4-bbb8-1ecb3bb22005",
Expand All @@ -77,31 +188,68 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 2,
"id": "499552c8-9e30-46e1-a706-4ac5dc64670e",
"metadata": {},
"outputs": [],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"¡Te encuentras con un fantasma!\n",
"Perdiste la batalla...\n",
"Tu aventura termina aquí.\n"
]
}
],
"source": [
"import random \n",
"\n",
"def encounter_ghost():\n",
" \"\"\"\n",
" This function handles the encounter with 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",
" Esta función maneja el encuentro con un fantasma.\n",
" El resultado de la batalla se determina por 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, imprime \"¡Derrotaste al fantasma!\" y retorna True.\n",
" Si el número aleatorio es mayor a 5, el aventurero pierde la batalla. \n",
" En este caso, imprime \"Perdiste la batalla...\" y retorna False.\n",
" \"\"\"\n",
" print(\"You encounter a ghost!\")\n",
" print(\"¡Te encuentras con un fantasma!\")\n",
" \n",
" # your code goes here"
" # Generar un número aleatorio entre 1 y 10\n",
" ghost_strength = random.randint(1, 10)\n",
" \n",
" # Determinar el resultado de la batalla\n",
" if ghost_strength <= 5:\n",
" print(\"¡Derrotaste al fantasma!\")\n",
" return True\n",
" else:\n",
" print(\"Perdiste la batalla...\")\n",
" return False\n",
"\n",
"# Ejemplo de uso de encounter_ghost()\n",
"battle_result = encounter_ghost()\n",
"if battle_result:\n",
" print(\"Puedes continuar tu aventura.\")\n",
"else:\n",
" print(\"Tu aventura termina aquí.\")\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 4,
"id": "d3e4076b-48cc-41ac-95ad-891743e775f5",
"metadata": {},
"outputs": [],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"¡Bienvenido a la Mansión Embrujada!\n"
]
}
],
"source": [
"# main function for the game\n",
"def run_mansion():\n",
Expand Down Expand Up @@ -130,7 +278,81 @@
"\n",
" \"\"\"\n",
" \n",
" # your code goes here"
" # your code goes here\n",
"\n",
" import random\n",
"\n",
"def encounter_ghost():\n",
" \"\"\"\n",
" Esta función maneja el encuentro con un fantasma.\n",
" El resultado de la batalla se determina por 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, imprime \"¡Derrotaste al fantasma!\" y retorna True.\n",
" Si el número aleatorio es mayor a 5, el aventurero pierde la batalla. \n",
" En este caso, imprime \"Perdiste la batalla...\" y retorna False.\n",
" \"\"\"\n",
" print(\"¡Te encuentras con un fantasma!\")\n",
" \n",
" # Generar un número aleatorio entre 1 y 10\n",
" ghost_strength = random.randint(1, 10)\n",
" \n",
" # Determinar el resultado de la batalla\n",
" if ghost_strength <= 5:\n",
" print(\"¡Derrotaste al fantasma!\")\n",
" return True\n",
" else:\n",
" print(\"Perdiste la batalla...\")\n",
" return False\n",
"\n",
"def run_mansion():\n",
" print(\"¡Bienvenido a la Mansión Embrujada!\")\n",
" \n",
" health_points = 10\n",
" items = []\n",
"\n",
" while health_points > 0:\n",
" # Elegir camino\n",
" path = input(\"Estás en un cruce. ¿Quieres ir a la 'izquierda' o a la 'derecha'? \").lower()\n",
"\n",
" if path == \"izquierda\":\n",
" # Evento aleatorio\n",
" event = random.choice([\"potion\", \"trap\"])\n",
" if event == \"potion\":\n",
" print(\"¡Encontraste una poción!\")\n",
" items.append(\"potion\")\n",
" else:\n",
" print(\"¡Caíste en una trampa y perdiste 2 puntos de salud!\")\n",
" health_points -= 2\n",
"\n",
" elif path == \"derecha\":\n",
" # Encuentro con fantasma\n",
" if encounter_ghost():\n",
" print(\"¡Encontraste una llave!\")\n",
" items.append(\"key\")\n",
" else:\n",
" print(\"Perdiste 2 puntos de salud en la batalla con el fantasma.\")\n",
" health_points -= 2\n",
"\n",
" else:\n",
" print(\"Elección no válida. Intenta nuevamente.\")\n",
" continue\n",
"\n",
" # Chequear si la salud llega a 0\n",
" if health_points <= 0:\n",
" print(\"Game over, perdiste todos tus puntos de salud.\")\n",
" break\n",
"\n",
" # Chequear si el aventurero tiene la llave\n",
" if \"key\" in items:\n",
" print(\"¡Desbloqueaste la puerta y encontraste el Tesoro! ¡Felicidades!\")\n",
" break\n",
" else:\n",
" print(\"Necesitas encontrar la llave para desbloquear la puerta y encontrar el tesoro.\")\n",
"\n",
"run_mansion()\n",
"\n",
"\n",
" "
]
},
{
Expand All @@ -143,10 +365,22 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 1,
"id": "f238dc90-0be2-4d8c-93e9-30a1dc8a5b72",
"metadata": {},
"outputs": [],
"outputs": [
{
"ename": "NameError",
"evalue": "name 'run_mansion' is not defined",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[1;32mIn[1], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m run_mansion()\n",
"\u001b[1;31mNameError\u001b[0m: name 'run_mansion' is not defined"
]
}
],
"source": [
"run_mansion()"
]
Expand Down Expand Up @@ -176,7 +410,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.12.4"
}
},
"nbformat": 4,
Expand Down