Skip to content
Open
Show file tree
Hide file tree
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
77 changes: 77 additions & 0 deletions dungeon_game/game.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
from player import Player
from rooms import ROOMS


class Game:
def __init__(self, player_name):
self.player = Player(player_name)
self.running = True

def get_room(self):
return ROOMS[self.player.position]

def look(self):
room = self.get_room()
print(f"\n{room['description']}")
if room["items"]:
print(f"You see: {', '.join(room['items'])}")
print(f"Exits: {', '.join(room['exits'].keys())}")

def move(self, direction):
room = self.get_room()
if direction in room["exits"]:
self.player.position = room["exits"][direction]
self.look()
self.check_enemy()
else:
print("You can't go that way!")

def take(self, item):
room = self.get_room()
if item in room["items"]:
room["items"].remove(item)
self.player.add_item(item)
print(f"You picked up the {item}.")
else:
print("That item isn't here.")

def check_enemy(self):
room = self.get_room()
if "enemy" in room and room["enemy"]:
enemy = room["enemy"]
print(f"\n⚔️ A {enemy['name']} attacks you!")
if self.player.has_item("sword"):
print("You slay it with your sword!")
room["enemy"] = None
else:
damage = enemy["damage"]
if not self.player.take_damage(damage):
print("You have been defeated...")
self.running = False
else:
print(f"You take {damage} damage and flee south!")
self.player.position = room["exits"].get("south", "entrance")

def process_command(self, cmd):
parts = cmd.lower().split()
if not parts:
return

action = parts[0]
arg = parts[1] if len(parts) > 1 else None

if action in ("quit", "q"):
self.running = False
print("Thanks for playing!")
elif action == "look":
self.look()
elif action == "status":
print(self.player)
elif action in ("go", "move") and arg:
self.move(arg)
elif action in ("north", "south", "east", "west"):
self.move(action)
elif action in ("take", "get") and arg:
self.take(arg)
else:
print("Commands: look, go <dir>, take <item>, status, quit")
30 changes: 30 additions & 0 deletions dungeon_game/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#!/usr/bin/env python3
from game import Game


def main():
print("=" * 40)
print(" 🏰 DUNGEON ADVENTURE 🏰")
print("=" * 40)

name = input("Enter your name, adventurer: ").strip() or "Hero"
game = Game(name)

print(f"\nWelcome, {name}! Find the treasure and escape!")
print("Type 'help' for commands.\n")
game.look()

while game.running:
try:
cmd = input("\n> ").strip()
if cmd == "help":
print("Commands: look, go <dir>, take <item>, status, quit")
else:
game.process_command(cmd)
except (KeyboardInterrupt, EOFError):
print("\nGoodbye!")
break


if __name__ == "__main__":
main()
22 changes: 22 additions & 0 deletions dungeon_game/player.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class Player:
def __init__(self, name):
self.name = name
self.health = 100
self.inventory = []
self.position = "entrance"

def take_damage(self, amount):
self.health -= amount
return self.health > 0

def heal(self, amount):
self.health = min(100, self.health + amount)

def add_item(self, item):
self.inventory.append(item)

def has_item(self, item):
return item in self.inventory

def __str__(self):
return f"{self.name} | HP: {self.health} | Items: {', '.join(self.inventory) or 'None'}"
23 changes: 23 additions & 0 deletions dungeon_game/rooms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
ROOMS = {
"entrance": {
"description": "You stand at the dungeon entrance. A torch flickers on the wall.",
"items": ["torch"],
"exits": {"north": "hallway"},
},
"hallway": {
"description": "A dark hallway stretches before you. You hear dripping water.",
"items": [],
"exits": {"south": "entrance", "east": "armory", "north": "treasure"},
},
"armory": {
"description": "Old weapons line the walls. A rusty sword catches your eye.",
"items": ["sword"],
"exits": {"west": "hallway"},
},
"treasure": {
"description": "A chest sits in the center. But a goblin guards it!",
"items": ["gold"],
"enemy": {"name": "Goblin", "health": 30, "damage": 15},
"exits": {"south": "hallway"},
},
}
36 changes: 0 additions & 36 deletions pushpit/binary_search.py

This file was deleted.

57 changes: 57 additions & 0 deletions pushpit/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,46 @@ def is_even(number: int) -> bool:
"""Check if a number is even."""
return number % 2 == 0

def linear_search(arr, target):
"""
Perform a linear search for the target in the given array.

Parameters:
arr (list): The list to search through.
target: The value to search for.

Returns:
int: The index of the target if found, otherwise -1.
"""
for index in range(len(arr)):
if arr[index] == target:
return index
return -1

def binary_search(arr, target):
"""
Perform binary search on a sorted array.

Args:
arr: A sorted list of elements
target: The element to search for

Returns:
Index of target if found, -1 otherwise
"""
left, right = 0, len(arr) - 1

while left <= right:
mid = left + (right - left) // 2

if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1

return -1

def main():
"""Main function to run the program."""
Expand All @@ -31,6 +71,23 @@ def main():
status = "even" if is_even(num) else "odd"
print(f"{num} is {status}")

# Linear search example
my_list = [5, 3, 2, 8, 1]
target_value = 2
result = linear_search(my_list, target_value)
if result != -1:
print(f"Target found at index: {result}")
else:
print("Target not found in the list.")

# Binary search example
numbers = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
target = 7
result = binary_search(numbers, target)
if result != -1:
print(f"Found {target} at index {result}")
else:
print(f"{target} not found in the array")

if __name__ == "__main__":
main()