diff --git a/.ipynb_checkpoints/lab-python-flow-control-checkpoint.ipynb b/.ipynb_checkpoints/lab-python-flow-control-checkpoint.ipynb new file mode 100644 index 0000000..75b7c22 --- /dev/null +++ b/.ipynb_checkpoints/lab-python-flow-control-checkpoint.ipynb @@ -0,0 +1,767 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "d3bfc191-8885-42ee-b0a0-bbab867c6f9f", + "metadata": { + "tags": [] + }, + "source": [ + "# Lab | Flow Control" + ] + }, + { + "cell_type": "markdown", + "id": "303cceb0-f898-4c5f-99bd-c04e131e1ded", + "metadata": {}, + "source": [ + "Objective: Practice how to use programming constructs like if/else statements and loops to control the flow of a program's execution." + ] + }, + { + "cell_type": "markdown", + "id": "42fd260a-9eb2-4c39-9989-f2c8c70552ec", + "metadata": {}, + "source": [ + "## Challenge: The Haunted Mansion" + ] + }, + { + "cell_type": "markdown", + "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", + "\n", + "## Requirements\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", + "\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", + "\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", + "\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", + "\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", + "\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", + "\n", + "- At the end of the mansion, the adventurer will find the treasure, and the game will end.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "id": "8846d61d-cf9d-4ad4-bbb8-1ecb3bb22005", + "metadata": {}, + "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", + "\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", + "\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", + "\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!" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "499552c8-9e30-46e1-a706-4ac5dc64670e", + "metadata": {}, + "outputs": [], + "source": [ + "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", + " \"\"\"\n", + " print(\"You encounter a ghost!\")\n", + " \n", + " # your code goes here" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "d3e4076b-48cc-41ac-95ad-891743e775f5", + "metadata": {}, + "outputs": [], + "source": [ + "# main function for the game\n", + "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", + " 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", + "\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", + "\n", + " If the adventurer chooses something other than \"left\" or \"right\", they are 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", + "\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", + "\n", + " \"\"\"\n", + " \n", + " import random\n", + "\n", + "def encounter_ghost(items):\n", + " \"\"\"\n", + " Handles a ghost encounter.\n", + " - Random number (1–10) determines win or loss.\n", + " - If adventurer has a weapon, it increases their chance of winning.\n", + " - Returns True if ghost is defeated, False otherwise.\n", + " \"\"\"\n", + " print(\"\\nπŸ‘» You encounter a ghost!\")\n", + "\n", + " # Base roll\n", + " roll = random.randint(1, 10)\n", + "\n", + " # Bonus if adventurer has a weapon\n", + " if \"sword\" in items or \"dagger\" in items:\n", + " print(\"You brandish your weapon bravely! βš”οΈ\")\n", + " roll += 2\n", + "\n", + " if roll <= 5:\n", + " print(\"βœ… You defeated the ghost!\")\n", + " return True\n", + " else:\n", + " print(\"❌ You lost the battle...\")\n", + " return False\n" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "36212882-9941-4d43-b9a1-098eb5f3f603", + "metadata": {}, + "outputs": [], + "source": [ + "import random\n", + "\n", + "def encounter_ghost(items):\n", + " \"\"\"\n", + " Handles a ghost encounter.\n", + " - Random number (1–10) determines win or loss.\n", + " - If adventurer has a weapon, it increases their chance of winning.\n", + " - Returns True if ghost is defeated, False otherwise.\n", + " \"\"\"\n", + " print(\"\\nπŸ‘» You encounter a ghost!\")\n", + "\n", + " # Base roll\n", + " roll = random.randint(1, 10)\n", + "\n", + " # Bonus if adventurer has a weapon\n", + " if \"sword\" in items or \"dagger\" in items:\n", + " print(\"You brandish your weapon bravely! βš”οΈ\")\n", + " roll += 2\n", + "\n", + " if roll <= 5:\n", + " print(\"βœ… You defeated the ghost!\")\n", + " return True\n", + " else:\n", + " print(\"❌ You lost the battle...\")\n", + " return False\n" + ] + }, + { + "cell_type": "markdown", + "id": "9e13a33c-38e5-44b3-bd1b-9a642c962c89", + "metadata": {}, + "source": [ + "To run the game, simply call the run_mansion() function:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "f238dc90-0be2-4d8c-93e9-30a1dc8a5b72", + "metadata": {}, + "outputs": [], + "source": [ + "def run_mansion():\n", + " health = 10\n", + " items = []\n", + " print(\"🏰 Welcome to the Haunted Mansion!\")\n", + " print(\"You begin with 10 health points and an empty inventory.\\n\")\n", + "\n", + " while True:\n", + " print(f\"Your health: {health}, Your items: {items}\")\n", + " choice = input(\"Do you go 'left' or 'right'? \").lower()\n", + "\n", + " if choice == \"left\":\n", + " event = random.choice([\"potion\", \"trap\", \"weapon\"])\n", + " if event == \"potion\":\n", + " print(\"πŸ§ͺ You found a potion and drank it. +2 health!\")\n", + " health += 2\n", + " elif event == \"trap\":\n", + " print(\"⚠️ You fell into a trap and lost 2 health.\")\n", + " health -= 2\n", + " else:\n", + " print(\"βš”οΈ You found a sword!\")\n", + " items.append(\"sword\")\n", + "\n", + " elif choice == \"right\":\n", + " won = encounter_ghost(items)\n", + " if won:\n", + " print(\"πŸ”‘ You found a key on the ghost’s remains!\")\n", + " items.append(\"key\")\n", + " else:\n", + " health -= 2\n", + " print(\"You lost 2 health after the fight.\")\n", + "\n", + " else:\n", + " print(\"❓ Invalid choice. Please type 'left' or 'right'.\")\n", + " continue\n", + "\n", + " # Game over condition\n", + " if health <= 0:\n", + " print(\"\\nπŸ’€ Game over! You lost all your health points.\")\n", + " break\n", + "\n", + " # Win condition\n", + " if \"key\" in items:\n", + " print(\"\\nπŸŽ‰ You unlocked the final door and found the Treasure! Congratulations!\")\n", + " break\n" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "2edb6df1-597c-440a-885e-a66c3bd50064", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "🏰 Welcome to the Haunted Mansion!\n", + "Objective: Find the treasure behind the final door.\n", + "Commands: type 'left', 'right', or 'quit' to exit.\n", + "\n", + "\n", + "--- Turn 1 ---\n", + "Health: 10 | Items: []\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Do you go 'left' or 'right'? left\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "βš”οΈ You found a sword!\n", + "\n", + "--- Turn 2 ---\n", + "Health: 10 | Items: ['sword']\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Do you go 'left' or 'right'? right\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "πŸ‘» You encounter a ghost!\n", + "You have a weapon β€” your chances improve!\n", + "(roll: 12)\n", + "❌ You lost the battle...\n", + "You stagger away and lost 2 health.\n", + "\n", + "--- Turn 3 ---\n", + "Health: 8 | Items: ['sword']\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Do you go 'left' or 'right'? left\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "πŸ§ͺ You found a potion and drank it. +1 health!\n", + "\n", + "--- Turn 4 ---\n", + "Health: 9 | Items: ['sword']\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Do you go 'left' or 'right'? done\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Invalid choice β€” please type 'left' or 'right' (or 'quit').\n", + "\n", + "--- Turn 5 ---\n", + "Health: 9 | Items: ['sword']\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Do you go 'left' or 'right'? left\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "You found another sword, but you already have one.\n", + "\n", + "--- Turn 6 ---\n", + "Health: 9 | Items: ['sword']\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Do you go 'left' or 'right'? quit\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "You chose to leave the mansion. Goodbye!\n" + ] + } + ], + "source": [ + "#!/usr/bin/env python3\n", + "\"\"\"\n", + "mansion_game.py\n", + "Standalone Haunted Mansion text game.\n", + "Save this file and run with: python mansion_game.py\n", + "\"\"\"\n", + "\n", + "import random\n", + "import sys\n", + "\n", + "def encounter_ghost(items):\n", + " \"\"\"\n", + " Handles a ghost encounter.\n", + " - Random number (1–10) determines win or loss.\n", + " - If the adventurer has a weapon, they get a bonus.\n", + " Returns True if the adventurer defeats the ghost, False otherwise.\n", + " \"\"\"\n", + " print(\"\\nπŸ‘» You encounter a ghost!\")\n", + " roll = random.randint(1, 10)\n", + " if any(w in items for w in (\"sword\", \"dagger\", \"axe\")):\n", + " print(\"You have a weapon β€” your chances improve!\")\n", + " roll += 2 # weapon bonus\n", + "\n", + " print(f\"(roll: {roll})\")\n", + " if roll <= 5:\n", + " print(\"βœ… You defeated the ghost!\")\n", + " return True\n", + " else:\n", + " print(\"❌ You lost the battle...\")\n", + " return False\n", + "\n", + "\n", + "def run_mansion():\n", + " health = 10\n", + " items = []\n", + " max_turns = 50 # safety to avoid infinite loops\n", + " turn = 0\n", + "\n", + " print(\"🏰 Welcome to the Haunted Mansion!\")\n", + " print(\"Objective: Find the treasure behind the final door.\")\n", + " print(\"Commands: type 'left', 'right', or 'quit' to exit.\\n\")\n", + "\n", + " # initial short intro\n", + " while health > 0 and turn < max_turns:\n", + " turn += 1\n", + " print(f\"\\n--- Turn {turn} ---\")\n", + " print(f\"Health: {health} | Items: {items}\")\n", + " try:\n", + " choice = input(\"Do you go 'left' or 'right'? \").strip().lower()\n", + " except (EOFError, KeyboardInterrupt):\n", + " print(\"\\nExiting game. Goodbye!\")\n", + " return\n", + "\n", + " if choice == \"quit\":\n", + " print(\"You chose to leave the mansion. Goodbye!\")\n", + " return\n", + "\n", + " if choice == \"left\":\n", + " event = random.choices(\n", + " population=[\"potion\", \"trap\", \"weapon\", \"nothing\"],\n", + " weights=[30, 30, 30, 10],\n", + " k=1\n", + " )[0]\n", + "\n", + " if event == \"potion\":\n", + " heal = random.randint(1, 3)\n", + " health += heal\n", + " print(f\"πŸ§ͺ You found a potion and drank it. +{heal} health!\")\n", + " elif event == \"trap\":\n", + " loss = 2\n", + " health -= loss\n", + " print(f\"⚠️ You fell into a trap and lost {loss} health.\")\n", + " elif event == \"weapon\":\n", + " new_weapon = random.choice([\"dagger\", \"sword\", \"axe\"])\n", + " if new_weapon not in items:\n", + " items.append(new_weapon)\n", + " print(f\"βš”οΈ You found a {new_weapon}!\")\n", + " else:\n", + " print(f\"You found another {new_weapon}, but you already have one.\")\n", + " else:\n", + " print(\"You walk a quiet corridor... nothing happens.\")\n", + "\n", + " elif choice == \"right\":\n", + " # chance to meet ghost or find an item / key\n", + " encounter_type = random.choices(\n", + " population=[\"ghost\", \"key\", \"nothing\", \"trap\"],\n", + " weights=[50, 15, 20, 15],\n", + " k=1\n", + " )[0]\n", + "\n", + " if encounter_type == \"ghost\":\n", + " won = encounter_ghost(items)\n", + " if won:\n", + " if \"key\" not in items:\n", + " items.append(\"key\")\n", + " print(\"πŸ”‘ The ghost dropped a key! You pick it up.\")\n", + " else:\n", + " health -= 2\n", + " print(\"You stagger away and lost 2 health.\")\n", + " elif encounter_type == \"key\":\n", + " if \"key\" not in items:\n", + " items.append(\"key\")\n", + " print(\"πŸ”‘ You found a shiny key on a dusty pedestal!\")\n", + " else:\n", + " print(\"You find an old chest, but it is empty.\")\n", + " elif encounter_type == \"trap\":\n", + " health -= 2\n", + " print(\"⚠️ A hidden trap springs! You lose 2 health.\")\n", + " else:\n", + " print(\"You search the room but find nothing of note.\")\n", + "\n", + " else:\n", + " print(\"Invalid choice β€” please type 'left' or 'right' (or 'quit').\")\n", + " continue\n", + "\n", + " # Check end conditions\n", + " if health <= 0:\n", + " print(\"\\nπŸ’€ Game over! You lost all your health points.\")\n", + " break\n", + "\n", + " if \"key\" in items:\n", + " print(\"\\nπŸ”“ You see a locked door. You use the key.\")\n", + " print(\"πŸŽ‰ You unlocked the door and found the Treasure! Congratulations!\")\n", + " break\n", + "\n", + " else:\n", + " # reached max turns or other termination\n", + " if turn >= max_turns:\n", + " print(\"\\nYou wandered the mansion for too long and decided to leave.\")\n", + " print(\"Thanks for playing!\")\n", + "\n", + "if __name__ == \"__main__\":\n", + " run_mansion()\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "b54ea7a8-bfee-433b-928a-f2268c756f9f", + "metadata": {}, + "outputs": [], + "source": [ + "# Uncomment to play\n", + "# run_mansion()\n" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "e08b3dae-9670-4d58-a3b9-7458c691ad31", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "🏰 Welcome to the Haunted Mansion!\n", + "Objective: Find the treasure behind the final door.\n", + "Commands: type 'left', 'right', 'status' or 'quit' (or 'done').\n", + "\n", + "\n", + "--- Turn 1 ---\n", + "Health: 10 | Items: []\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Do you go 'left' or 'right'? left\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "βš”οΈ You found a dagger!\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Do you want to continue exploring? (yes/no): right\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Please answer 'yes' or 'no' (or type 'quit').\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Do you want to continue exploring? (yes/no): quit\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "You chose to leave the mansion. Goodbye!\n" + ] + } + ], + "source": [ + "import random\n", + "\n", + "def encounter_ghost(items):\n", + " \"\"\"\n", + " Handles a ghost encounter.\n", + " - Random number (1–10) determines win or loss.\n", + " - If the adventurer has a weapon, they get a bonus.\n", + " Returns True if the adventurer defeats the ghost, False otherwise.\n", + " \"\"\"\n", + " print(\"\\nπŸ‘» You encounter a ghost!\")\n", + " roll = random.randint(1, 10)\n", + " if any(w in items for w in (\"sword\", \"dagger\", \"axe\")):\n", + " print(\"You have a weapon β€” your chances improve!\")\n", + " roll += 2 # weapon bonus\n", + "\n", + " print(f\"(roll: {roll})\")\n", + " if roll <= 5:\n", + " print(\"βœ… You defeated the ghost!\")\n", + " return True\n", + " else:\n", + " print(\"❌ You lost the battle...\")\n", + " return False\n", + "\n", + "\n", + "def run_mansion():\n", + " health = 10\n", + " items = []\n", + " max_turns = 50 # safety to avoid infinite loops\n", + " turn = 0\n", + "\n", + " print(\"🏰 Welcome to the Haunted Mansion!\")\n", + " print(\"Objective: Find the treasure behind the final door.\")\n", + " print(\"Commands: type 'left', 'right', 'status' or 'quit' (or 'done').\\n\")\n", + "\n", + " while health > 0 and turn < max_turns:\n", + " turn += 1\n", + " print(f\"\\n--- Turn {turn} ---\")\n", + " print(f\"Health: {health} | Items: {items}\")\n", + " try:\n", + " choice = input(\"Do you go 'left' or 'right'? \").strip().lower()\n", + " except (EOFError, KeyboardInterrupt):\n", + " print(\"\\nExiting game. Goodbye!\")\n", + " return\n", + "\n", + " # quick commands\n", + " if choice in (\"quit\", \"done\"):\n", + " print(\"You chose to leave the mansion. Goodbye!\")\n", + " return\n", + "\n", + " if choice == \"status\":\n", + " print(f\"Status β€” Health: {health}, Items: {items}, Turn: {turn}\")\n", + " # Ask if player wants to continue after status\n", + " cont = input(\"Do you want to continue exploring? (yes/no): \").strip().lower()\n", + " if cont in (\"no\", \"n\", \"quit\", \"done\"):\n", + " print(\"You chose to leave the mansion. Goodbye!\")\n", + " return\n", + " else:\n", + " continue\n", + "\n", + " if choice == \"left\":\n", + " event = random.choices(\n", + " population=[\"potion\", \"trap\", \"weapon\", \"nothing\"],\n", + " weights=[30, 30, 30, 10],\n", + " k=1\n", + " )[0]\n", + "\n", + " if event == \"potion\":\n", + " heal = random.randint(1, 3)\n", + " health += heal\n", + " print(f\"πŸ§ͺ You found a potion and drank it. +{heal} health!\")\n", + " elif event == \"trap\":\n", + " loss = 2\n", + " health -= loss\n", + " print(f\"⚠️ You fell into a trap and lost {loss} health.\")\n", + " elif event == \"weapon\":\n", + " new_weapon = random.choice([\"dagger\", \"sword\", \"axe\"])\n", + " if new_weapon not in items:\n", + " items.append(new_weapon)\n", + " print(f\"βš”οΈ You found a {new_weapon}!\")\n", + " else:\n", + " print(f\"You found another {new_weapon}, but you already have one.\")\n", + " else:\n", + " print(\"You walk a quiet corridor... nothing happens.\")\n", + "\n", + " elif choice == \"right\":\n", + " encounter_type = random.choices(\n", + " population=[\"ghost\", \"key\", \"nothing\", \"trap\"],\n", + " weights=[50, 15, 20, 15],\n", + " k=1\n", + " )[0]\n", + "\n", + " if encounter_type == \"ghost\":\n", + " won = encounter_ghost(items)\n", + " if won:\n", + " if \"key\" not in items:\n", + " items.append(\"key\")\n", + " print(\"πŸ”‘ The ghost dropped a key! You pick it up.\")\n", + " else:\n", + " health -= 2\n", + " print(\"You stagger away and lost 2 health.\")\n", + " elif encounter_type == \"key\":\n", + " if \"key\" not in items:\n", + " items.append(\"key\")\n", + " print(\"πŸ”‘ You found a shiny key on a dusty pedestal!\")\n", + " else:\n", + " print(\"You find an old chest, but it is empty.\")\n", + " elif encounter_type == \"trap\":\n", + " health -= 2\n", + " print(\"⚠️ A hidden trap springs! You lose 2 health.\")\n", + " else:\n", + " print(\"You search the room but find nothing of note.\")\n", + "\n", + " else:\n", + " print(\"Invalid choice β€” please type 'left' or 'right' (or 'status'/'quit').\")\n", + " continue\n", + "\n", + " # Check end conditions\n", + " if health <= 0:\n", + " print(\"\\nπŸ’€ Game over! You lost all your health points.\")\n", + " break\n", + "\n", + " if \"key\" in items:\n", + " print(\"\\nπŸ”“ You see a locked door. You use the key.\")\n", + " print(\"πŸŽ‰ You unlocked the door and found the Treasure! Congratulations!\")\n", + " break\n", + "\n", + " # Ask whether to continue each turn (friendly prompt)\n", + " while True:\n", + " keep_playing = input(\"Do you want to continue exploring? (yes/no): \").strip().lower()\n", + " if keep_playing in (\"no\", \"n\", \"quit\", \"done\"):\n", + " print(\"You chose to leave the mansion. Goodbye!\")\n", + " return\n", + " elif keep_playing in (\"yes\", \"y\", \"\"):\n", + " # continue main loop\n", + " break\n", + " else:\n", + " print(\"Please answer 'yes' or 'no' (or type 'quit').\")\n", + "\n", + " else:\n", + " if turn >= max_turns:\n", + " print(\"\\nYou wandered the mansion for too long and decided to leave.\")\n", + " print(\"Thanks for playing!\")\n", + "\n", + "\n", + "if __name__ == \"__main__\":\n", + " run_mansion()\n" + ] + }, + { + "cell_type": "markdown", + "id": "88212f63-3bdb-479f-bf6c-4ecd0685d39a", + "metadata": {}, + "source": [ + "This should print the game's narrative and prompt the user to make choices and fight ghosts. The game ends when the adventurer finds the key or loses all their health points. " + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.13.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/lab-python-flow-control.ipynb b/lab-python-flow-control.ipynb index 7905339..75b7c22 100644 --- a/lab-python-flow-control.ipynb +++ b/lab-python-flow-control.ipynb @@ -98,7 +98,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 1, "id": "d3e4076b-48cc-41ac-95ad-891743e775f5", "metadata": {}, "outputs": [], @@ -130,7 +130,65 @@ "\n", " \"\"\"\n", " \n", - " # your code goes here" + " import random\n", + "\n", + "def encounter_ghost(items):\n", + " \"\"\"\n", + " Handles a ghost encounter.\n", + " - Random number (1–10) determines win or loss.\n", + " - If adventurer has a weapon, it increases their chance of winning.\n", + " - Returns True if ghost is defeated, False otherwise.\n", + " \"\"\"\n", + " print(\"\\nπŸ‘» You encounter a ghost!\")\n", + "\n", + " # Base roll\n", + " roll = random.randint(1, 10)\n", + "\n", + " # Bonus if adventurer has a weapon\n", + " if \"sword\" in items or \"dagger\" in items:\n", + " print(\"You brandish your weapon bravely! βš”οΈ\")\n", + " roll += 2\n", + "\n", + " if roll <= 5:\n", + " print(\"βœ… You defeated the ghost!\")\n", + " return True\n", + " else:\n", + " print(\"❌ You lost the battle...\")\n", + " return False\n" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "36212882-9941-4d43-b9a1-098eb5f3f603", + "metadata": {}, + "outputs": [], + "source": [ + "import random\n", + "\n", + "def encounter_ghost(items):\n", + " \"\"\"\n", + " Handles a ghost encounter.\n", + " - Random number (1–10) determines win or loss.\n", + " - If adventurer has a weapon, it increases their chance of winning.\n", + " - Returns True if ghost is defeated, False otherwise.\n", + " \"\"\"\n", + " print(\"\\nπŸ‘» You encounter a ghost!\")\n", + "\n", + " # Base roll\n", + " roll = random.randint(1, 10)\n", + "\n", + " # Bonus if adventurer has a weapon\n", + " if \"sword\" in items or \"dagger\" in items:\n", + " print(\"You brandish your weapon bravely! βš”οΈ\")\n", + " roll += 2\n", + "\n", + " if roll <= 5:\n", + " print(\"βœ… You defeated the ghost!\")\n", + " return True\n", + " else:\n", + " print(\"❌ You lost the battle...\")\n", + " return False\n" ] }, { @@ -143,12 +201,537 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 3, "id": "f238dc90-0be2-4d8c-93e9-30a1dc8a5b72", "metadata": {}, "outputs": [], "source": [ - "run_mansion()" + "def run_mansion():\n", + " health = 10\n", + " items = []\n", + " print(\"🏰 Welcome to the Haunted Mansion!\")\n", + " print(\"You begin with 10 health points and an empty inventory.\\n\")\n", + "\n", + " while True:\n", + " print(f\"Your health: {health}, Your items: {items}\")\n", + " choice = input(\"Do you go 'left' or 'right'? \").lower()\n", + "\n", + " if choice == \"left\":\n", + " event = random.choice([\"potion\", \"trap\", \"weapon\"])\n", + " if event == \"potion\":\n", + " print(\"πŸ§ͺ You found a potion and drank it. +2 health!\")\n", + " health += 2\n", + " elif event == \"trap\":\n", + " print(\"⚠️ You fell into a trap and lost 2 health.\")\n", + " health -= 2\n", + " else:\n", + " print(\"βš”οΈ You found a sword!\")\n", + " items.append(\"sword\")\n", + "\n", + " elif choice == \"right\":\n", + " won = encounter_ghost(items)\n", + " if won:\n", + " print(\"πŸ”‘ You found a key on the ghost’s remains!\")\n", + " items.append(\"key\")\n", + " else:\n", + " health -= 2\n", + " print(\"You lost 2 health after the fight.\")\n", + "\n", + " else:\n", + " print(\"❓ Invalid choice. Please type 'left' or 'right'.\")\n", + " continue\n", + "\n", + " # Game over condition\n", + " if health <= 0:\n", + " print(\"\\nπŸ’€ Game over! You lost all your health points.\")\n", + " break\n", + "\n", + " # Win condition\n", + " if \"key\" in items:\n", + " print(\"\\nπŸŽ‰ You unlocked the final door and found the Treasure! Congratulations!\")\n", + " break\n" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "2edb6df1-597c-440a-885e-a66c3bd50064", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "🏰 Welcome to the Haunted Mansion!\n", + "Objective: Find the treasure behind the final door.\n", + "Commands: type 'left', 'right', or 'quit' to exit.\n", + "\n", + "\n", + "--- Turn 1 ---\n", + "Health: 10 | Items: []\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Do you go 'left' or 'right'? left\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "βš”οΈ You found a sword!\n", + "\n", + "--- Turn 2 ---\n", + "Health: 10 | Items: ['sword']\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Do you go 'left' or 'right'? right\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "πŸ‘» You encounter a ghost!\n", + "You have a weapon β€” your chances improve!\n", + "(roll: 12)\n", + "❌ You lost the battle...\n", + "You stagger away and lost 2 health.\n", + "\n", + "--- Turn 3 ---\n", + "Health: 8 | Items: ['sword']\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Do you go 'left' or 'right'? left\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "πŸ§ͺ You found a potion and drank it. +1 health!\n", + "\n", + "--- Turn 4 ---\n", + "Health: 9 | Items: ['sword']\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Do you go 'left' or 'right'? done\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Invalid choice β€” please type 'left' or 'right' (or 'quit').\n", + "\n", + "--- Turn 5 ---\n", + "Health: 9 | Items: ['sword']\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Do you go 'left' or 'right'? left\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "You found another sword, but you already have one.\n", + "\n", + "--- Turn 6 ---\n", + "Health: 9 | Items: ['sword']\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Do you go 'left' or 'right'? quit\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "You chose to leave the mansion. Goodbye!\n" + ] + } + ], + "source": [ + "#!/usr/bin/env python3\n", + "\"\"\"\n", + "mansion_game.py\n", + "Standalone Haunted Mansion text game.\n", + "Save this file and run with: python mansion_game.py\n", + "\"\"\"\n", + "\n", + "import random\n", + "import sys\n", + "\n", + "def encounter_ghost(items):\n", + " \"\"\"\n", + " Handles a ghost encounter.\n", + " - Random number (1–10) determines win or loss.\n", + " - If the adventurer has a weapon, they get a bonus.\n", + " Returns True if the adventurer defeats the ghost, False otherwise.\n", + " \"\"\"\n", + " print(\"\\nπŸ‘» You encounter a ghost!\")\n", + " roll = random.randint(1, 10)\n", + " if any(w in items for w in (\"sword\", \"dagger\", \"axe\")):\n", + " print(\"You have a weapon β€” your chances improve!\")\n", + " roll += 2 # weapon bonus\n", + "\n", + " print(f\"(roll: {roll})\")\n", + " if roll <= 5:\n", + " print(\"βœ… You defeated the ghost!\")\n", + " return True\n", + " else:\n", + " print(\"❌ You lost the battle...\")\n", + " return False\n", + "\n", + "\n", + "def run_mansion():\n", + " health = 10\n", + " items = []\n", + " max_turns = 50 # safety to avoid infinite loops\n", + " turn = 0\n", + "\n", + " print(\"🏰 Welcome to the Haunted Mansion!\")\n", + " print(\"Objective: Find the treasure behind the final door.\")\n", + " print(\"Commands: type 'left', 'right', or 'quit' to exit.\\n\")\n", + "\n", + " # initial short intro\n", + " while health > 0 and turn < max_turns:\n", + " turn += 1\n", + " print(f\"\\n--- Turn {turn} ---\")\n", + " print(f\"Health: {health} | Items: {items}\")\n", + " try:\n", + " choice = input(\"Do you go 'left' or 'right'? \").strip().lower()\n", + " except (EOFError, KeyboardInterrupt):\n", + " print(\"\\nExiting game. Goodbye!\")\n", + " return\n", + "\n", + " if choice == \"quit\":\n", + " print(\"You chose to leave the mansion. Goodbye!\")\n", + " return\n", + "\n", + " if choice == \"left\":\n", + " event = random.choices(\n", + " population=[\"potion\", \"trap\", \"weapon\", \"nothing\"],\n", + " weights=[30, 30, 30, 10],\n", + " k=1\n", + " )[0]\n", + "\n", + " if event == \"potion\":\n", + " heal = random.randint(1, 3)\n", + " health += heal\n", + " print(f\"πŸ§ͺ You found a potion and drank it. +{heal} health!\")\n", + " elif event == \"trap\":\n", + " loss = 2\n", + " health -= loss\n", + " print(f\"⚠️ You fell into a trap and lost {loss} health.\")\n", + " elif event == \"weapon\":\n", + " new_weapon = random.choice([\"dagger\", \"sword\", \"axe\"])\n", + " if new_weapon not in items:\n", + " items.append(new_weapon)\n", + " print(f\"βš”οΈ You found a {new_weapon}!\")\n", + " else:\n", + " print(f\"You found another {new_weapon}, but you already have one.\")\n", + " else:\n", + " print(\"You walk a quiet corridor... nothing happens.\")\n", + "\n", + " elif choice == \"right\":\n", + " # chance to meet ghost or find an item / key\n", + " encounter_type = random.choices(\n", + " population=[\"ghost\", \"key\", \"nothing\", \"trap\"],\n", + " weights=[50, 15, 20, 15],\n", + " k=1\n", + " )[0]\n", + "\n", + " if encounter_type == \"ghost\":\n", + " won = encounter_ghost(items)\n", + " if won:\n", + " if \"key\" not in items:\n", + " items.append(\"key\")\n", + " print(\"πŸ”‘ The ghost dropped a key! You pick it up.\")\n", + " else:\n", + " health -= 2\n", + " print(\"You stagger away and lost 2 health.\")\n", + " elif encounter_type == \"key\":\n", + " if \"key\" not in items:\n", + " items.append(\"key\")\n", + " print(\"πŸ”‘ You found a shiny key on a dusty pedestal!\")\n", + " else:\n", + " print(\"You find an old chest, but it is empty.\")\n", + " elif encounter_type == \"trap\":\n", + " health -= 2\n", + " print(\"⚠️ A hidden trap springs! You lose 2 health.\")\n", + " else:\n", + " print(\"You search the room but find nothing of note.\")\n", + "\n", + " else:\n", + " print(\"Invalid choice β€” please type 'left' or 'right' (or 'quit').\")\n", + " continue\n", + "\n", + " # Check end conditions\n", + " if health <= 0:\n", + " print(\"\\nπŸ’€ Game over! You lost all your health points.\")\n", + " break\n", + "\n", + " if \"key\" in items:\n", + " print(\"\\nπŸ”“ You see a locked door. You use the key.\")\n", + " print(\"πŸŽ‰ You unlocked the door and found the Treasure! Congratulations!\")\n", + " break\n", + "\n", + " else:\n", + " # reached max turns or other termination\n", + " if turn >= max_turns:\n", + " print(\"\\nYou wandered the mansion for too long and decided to leave.\")\n", + " print(\"Thanks for playing!\")\n", + "\n", + "if __name__ == \"__main__\":\n", + " run_mansion()\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "b54ea7a8-bfee-433b-928a-f2268c756f9f", + "metadata": {}, + "outputs": [], + "source": [ + "# Uncomment to play\n", + "# run_mansion()\n" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "e08b3dae-9670-4d58-a3b9-7458c691ad31", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "🏰 Welcome to the Haunted Mansion!\n", + "Objective: Find the treasure behind the final door.\n", + "Commands: type 'left', 'right', 'status' or 'quit' (or 'done').\n", + "\n", + "\n", + "--- Turn 1 ---\n", + "Health: 10 | Items: []\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Do you go 'left' or 'right'? left\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "βš”οΈ You found a dagger!\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Do you want to continue exploring? (yes/no): right\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Please answer 'yes' or 'no' (or type 'quit').\n" + ] + }, + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Do you want to continue exploring? (yes/no): quit\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "You chose to leave the mansion. Goodbye!\n" + ] + } + ], + "source": [ + "import random\n", + "\n", + "def encounter_ghost(items):\n", + " \"\"\"\n", + " Handles a ghost encounter.\n", + " - Random number (1–10) determines win or loss.\n", + " - If the adventurer has a weapon, they get a bonus.\n", + " Returns True if the adventurer defeats the ghost, False otherwise.\n", + " \"\"\"\n", + " print(\"\\nπŸ‘» You encounter a ghost!\")\n", + " roll = random.randint(1, 10)\n", + " if any(w in items for w in (\"sword\", \"dagger\", \"axe\")):\n", + " print(\"You have a weapon β€” your chances improve!\")\n", + " roll += 2 # weapon bonus\n", + "\n", + " print(f\"(roll: {roll})\")\n", + " if roll <= 5:\n", + " print(\"βœ… You defeated the ghost!\")\n", + " return True\n", + " else:\n", + " print(\"❌ You lost the battle...\")\n", + " return False\n", + "\n", + "\n", + "def run_mansion():\n", + " health = 10\n", + " items = []\n", + " max_turns = 50 # safety to avoid infinite loops\n", + " turn = 0\n", + "\n", + " print(\"🏰 Welcome to the Haunted Mansion!\")\n", + " print(\"Objective: Find the treasure behind the final door.\")\n", + " print(\"Commands: type 'left', 'right', 'status' or 'quit' (or 'done').\\n\")\n", + "\n", + " while health > 0 and turn < max_turns:\n", + " turn += 1\n", + " print(f\"\\n--- Turn {turn} ---\")\n", + " print(f\"Health: {health} | Items: {items}\")\n", + " try:\n", + " choice = input(\"Do you go 'left' or 'right'? \").strip().lower()\n", + " except (EOFError, KeyboardInterrupt):\n", + " print(\"\\nExiting game. Goodbye!\")\n", + " return\n", + "\n", + " # quick commands\n", + " if choice in (\"quit\", \"done\"):\n", + " print(\"You chose to leave the mansion. Goodbye!\")\n", + " return\n", + "\n", + " if choice == \"status\":\n", + " print(f\"Status β€” Health: {health}, Items: {items}, Turn: {turn}\")\n", + " # Ask if player wants to continue after status\n", + " cont = input(\"Do you want to continue exploring? (yes/no): \").strip().lower()\n", + " if cont in (\"no\", \"n\", \"quit\", \"done\"):\n", + " print(\"You chose to leave the mansion. Goodbye!\")\n", + " return\n", + " else:\n", + " continue\n", + "\n", + " if choice == \"left\":\n", + " event = random.choices(\n", + " population=[\"potion\", \"trap\", \"weapon\", \"nothing\"],\n", + " weights=[30, 30, 30, 10],\n", + " k=1\n", + " )[0]\n", + "\n", + " if event == \"potion\":\n", + " heal = random.randint(1, 3)\n", + " health += heal\n", + " print(f\"πŸ§ͺ You found a potion and drank it. +{heal} health!\")\n", + " elif event == \"trap\":\n", + " loss = 2\n", + " health -= loss\n", + " print(f\"⚠️ You fell into a trap and lost {loss} health.\")\n", + " elif event == \"weapon\":\n", + " new_weapon = random.choice([\"dagger\", \"sword\", \"axe\"])\n", + " if new_weapon not in items:\n", + " items.append(new_weapon)\n", + " print(f\"βš”οΈ You found a {new_weapon}!\")\n", + " else:\n", + " print(f\"You found another {new_weapon}, but you already have one.\")\n", + " else:\n", + " print(\"You walk a quiet corridor... nothing happens.\")\n", + "\n", + " elif choice == \"right\":\n", + " encounter_type = random.choices(\n", + " population=[\"ghost\", \"key\", \"nothing\", \"trap\"],\n", + " weights=[50, 15, 20, 15],\n", + " k=1\n", + " )[0]\n", + "\n", + " if encounter_type == \"ghost\":\n", + " won = encounter_ghost(items)\n", + " if won:\n", + " if \"key\" not in items:\n", + " items.append(\"key\")\n", + " print(\"πŸ”‘ The ghost dropped a key! You pick it up.\")\n", + " else:\n", + " health -= 2\n", + " print(\"You stagger away and lost 2 health.\")\n", + " elif encounter_type == \"key\":\n", + " if \"key\" not in items:\n", + " items.append(\"key\")\n", + " print(\"πŸ”‘ You found a shiny key on a dusty pedestal!\")\n", + " else:\n", + " print(\"You find an old chest, but it is empty.\")\n", + " elif encounter_type == \"trap\":\n", + " health -= 2\n", + " print(\"⚠️ A hidden trap springs! You lose 2 health.\")\n", + " else:\n", + " print(\"You search the room but find nothing of note.\")\n", + "\n", + " else:\n", + " print(\"Invalid choice β€” please type 'left' or 'right' (or 'status'/'quit').\")\n", + " continue\n", + "\n", + " # Check end conditions\n", + " if health <= 0:\n", + " print(\"\\nπŸ’€ Game over! You lost all your health points.\")\n", + " break\n", + "\n", + " if \"key\" in items:\n", + " print(\"\\nπŸ”“ You see a locked door. You use the key.\")\n", + " print(\"πŸŽ‰ You unlocked the door and found the Treasure! Congratulations!\")\n", + " break\n", + "\n", + " # Ask whether to continue each turn (friendly prompt)\n", + " while True:\n", + " keep_playing = input(\"Do you want to continue exploring? (yes/no): \").strip().lower()\n", + " if keep_playing in (\"no\", \"n\", \"quit\", \"done\"):\n", + " print(\"You chose to leave the mansion. Goodbye!\")\n", + " return\n", + " elif keep_playing in (\"yes\", \"y\", \"\"):\n", + " # continue main loop\n", + " break\n", + " else:\n", + " print(\"Please answer 'yes' or 'no' (or type 'quit').\")\n", + "\n", + " else:\n", + " if turn >= max_turns:\n", + " print(\"\\nYou wandered the mansion for too long and decided to leave.\")\n", + " print(\"Thanks for playing!\")\n", + "\n", + "\n", + "if __name__ == \"__main__\":\n", + " run_mansion()\n" ] }, { @@ -176,7 +759,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.13.6" } }, "nbformat": 4,