Skip to content

Commit 3ad1000

Browse files
committed
OOP Function
1 parent ffdab44 commit 3ad1000

File tree

13 files changed

+404
-4
lines changed

13 files changed

+404
-4
lines changed

basics/OOP/ClassAndObject.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,5 @@ class Character:
1616
character1.name = "Night"
1717
character2.name = "Day"
1818
print(character1.name)
19-
print(character2.name)
19+
print(character2.name)
20+
print(vars(character1))

basics/OOP/Constructor.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ def __init__(self,name,hp,mp,attack,lv): #Initializes the attributes of the clas
66
self.mp = mp
77
self.attack = attack
88
self.lv = lv
9-
print(f"{name}!, Your Character Created")
9+
print(f"{self.name}!, Your Character Created")
1010

1111
char1 = Character("Night",100,50,12,1)
1212
print(vars(char1))

basics/OOP/ObjectFunction.py

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
class Animal:
2+
def __init__(self, type, voice):
3+
self.type = type
4+
self.voice = voice
5+
def speak(self):
6+
print(f"{self.type} says {self.voice}")
7+
8+
dog = Animal("Dog", "Bark")
9+
dog.speak()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
def add(x,y):
2+
return x + y
3+
4+
def ready(coffee):
5+
print(f"Your {coffee} is ready!")
6+
def done(coffee):
7+
print(f"Im Done in my {coffee}!")
+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
from function import add , ready ,done
2+
3+
def coffee(coffee,c1 ,c2):
4+
c1(coffee)
5+
print(f"Im drinking my {coffee}")
6+
c2(coffee)
7+
8+
if __name__ == "__main__":
9+
print(add(1,3))
10+
coffee("Latte",ready,done)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
def ready():
2+
print("Im drinking my coffee")
3+
4+
call = lambda x : (
5+
print("Your Coffee is ready"),
6+
x()
7+
)
8+
call(ready)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
import sqlite3
2+
import datetime
3+
4+
5+
class Inventory:
6+
def __init__(self):
7+
"""Initialize database and create tables if they don't exist."""
8+
self.conn = sqlite3.connect("inventory.db")
9+
self.cursor = self.conn.cursor()
10+
11+
# Create inventory table
12+
self.cursor.execute("""
13+
CREATE TABLE IF NOT EXISTS inventory (
14+
id INTEGER PRIMARY KEY AUTOINCREMENT,
15+
name TEXT UNIQUE,
16+
price INTEGER,
17+
quantity INTEGER
18+
)
19+
""")
20+
21+
# Create history table with total_price for tracking sales revenue
22+
self.cursor.execute("""
23+
CREATE TABLE IF NOT EXISTS history (
24+
id INTEGER PRIMARY KEY AUTOINCREMENT,
25+
action TEXT,
26+
item_id INTEGER,
27+
item_name TEXT,
28+
quantity INTEGER,
29+
price INTEGER,
30+
total_price INTEGER,
31+
timestamp TEXT,
32+
FOREIGN KEY (item_id) REFERENCES inventory(id) ON DELETE CASCADE
33+
)
34+
""")
35+
self.conn.commit()
36+
37+
def log_history(self, action, item_name, quantity=None, price=None):
38+
"""Log actions in the history table."""
39+
self.cursor.execute(
40+
"SELECT id FROM inventory WHERE name=?", (item_name,))
41+
item = self.cursor.fetchone()
42+
item_id = item[0] if item else None
43+
44+
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
45+
46+
# Calculate total price for sales transactions
47+
total_price = price * quantity if action == "Sold" and price and quantity else None
48+
49+
self.cursor.execute("""
50+
INSERT INTO history (action, item_id, item_name, quantity, price, total_price, timestamp)
51+
VALUES (?, ?, ?, ?, ?, ?, ?)
52+
""", (action, item_id, item_name, quantity, price, total_price, timestamp))
53+
self.conn.commit()
54+
55+
def add(self, **kwargs):
56+
"""Add an item to inventory and log the action."""
57+
try:
58+
self.cursor.execute(
59+
"INSERT INTO inventory (name, price, quantity) VALUES (:name, :price, :quantity)", kwargs)
60+
self.conn.commit()
61+
self.log_history(
62+
"Added", kwargs['name'], kwargs['quantity'], kwargs['price'])
63+
print(f"{kwargs['name']} added to inventory.")
64+
except sqlite3.IntegrityError:
65+
print(f"Error: {kwargs['name']} already exists.")
66+
67+
def edit(self, item_name):
68+
"""Edit item price or quantity and log the action."""
69+
self.cursor.execute(
70+
"SELECT * FROM inventory WHERE name=?", (item_name,))
71+
item = self.cursor.fetchone()
72+
73+
if not item:
74+
return print(f"{item_name} not found.")
75+
76+
updates = {}
77+
78+
new_price = input(f"New price for {item_name} (Enter to skip): ")
79+
new_quantity = input(f"New quantity for {item_name} (Enter to skip): ")
80+
81+
if new_price:
82+
updates["price"] = int(new_price)
83+
if new_quantity:
84+
updates["quantity"] = int(new_quantity)
85+
86+
if updates:
87+
set_clause = ", ".join(f"{col}=?" for col in updates.keys())
88+
self.cursor.execute(
89+
f"UPDATE inventory SET {set_clause} WHERE name=?", (*updates.values(), item_name))
90+
self.conn.commit()
91+
92+
# Log changes in history
93+
if "price" in updates:
94+
self.log_history("Price Edited", item_name,
95+
price=updates["price"])
96+
if "quantity" in updates:
97+
self.log_history("Quantity Edited", item_name,
98+
quantity=updates["quantity"])
99+
100+
print(f"{item_name} updated.")
101+
else:
102+
print("No changes made.")
103+
104+
def remove(self, item_name):
105+
"""Remove an item from inventory and log the action."""
106+
self.cursor.execute(
107+
"SELECT id FROM inventory WHERE name=?", (item_name,))
108+
item = self.cursor.fetchone()
109+
110+
if not item:
111+
return print(f"Error: {item_name} not found in inventory.")
112+
113+
# Remove the item
114+
self.cursor.execute("DELETE FROM inventory WHERE name=?", (item_name,))
115+
self.conn.commit()
116+
117+
# Log removal action
118+
self.log_history("Removed", item_name)
119+
print(f"{item_name} removed successfully.")
120+
121+
def sell(self, item_name, quantity):
122+
"""Sell an item, update inventory, and log the action."""
123+
self.cursor.execute(
124+
"SELECT * FROM inventory WHERE name=?", (item_name,))
125+
if not (item := self.cursor.fetchone()):
126+
return print(f"{item_name} not found.")
127+
128+
if item[3] < quantity:
129+
return print(f"Not enough stock. Available: {item[3]}")
130+
131+
new_qty = item[3] - quantity
132+
if new_qty:
133+
self.cursor.execute(
134+
"UPDATE inventory SET quantity=? WHERE name=?", (new_qty, item_name))
135+
else:
136+
self.remove(item_name)
137+
138+
self.conn.commit()
139+
total_price = item[2] * quantity # price * quantity
140+
self.log_history("Sold", item_name, quantity, item[2])
141+
print(f"Sold {quantity} {item_name}(s) for ${total_price}")
142+
input()
143+
144+
def view_history(self):
145+
"""Display history of transactions with total price for sales."""
146+
self.cursor.execute("SELECT * FROM history ORDER BY timestamp DESC")
147+
history = self.cursor.fetchall()
148+
if not history:
149+
return print("No history available.")
150+
151+
print("\nTransaction History:\n" + "-" * 70)
152+
print(
153+
f"{'No.':<5} {'Action':<10} {'Item':<15} {'Qty':<8} {'Price':<8} {'Total':<10} {'Timestamp':<20}")
154+
for i, (id, action, item_id, name, qty, price, total_price, timestamp) in enumerate(history, 1):
155+
print(
156+
f"{i:<5} {action:<10} {name:<15} {qty if qty else '-':<8} {price if price else '-':<8} {total_price if total_price else '-':<10} {timestamp:<20}")
157+
print("-" * 70)
158+
159+
def display(self):
160+
"""Display inventory in a well-formatted table."""
161+
self.cursor.execute("SELECT * FROM inventory")
162+
items = self.cursor.fetchall()
163+
164+
if not items:
165+
return print("Inventory is empty.")
166+
167+
print("\nInventory List:\n" + "-" * 50)
168+
print(f"{'No.':<5} {'Name':<20} {'Price':<10} {'Quantity':<10}")
169+
print("-" * 50)
170+
171+
for i, (id, name, price, qty) in enumerate(items, 1):
172+
print(f"{i:<5} {name:<20} {price:<10} {qty:<10}")
173+
174+
print("-" * 50)
175+
176+
def __del__(self):
177+
"""Close database connection."""
178+
self.conn.close()
179+
print("Inventory closed.")
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from Inventory import Inventory
2+
import os
3+
4+
5+
def main():
6+
inventory = Inventory()
7+
menu = {
8+
"1": ("Add Item", lambda: inventory.add(
9+
name=input("Enter item name: "),
10+
price=int(input("Enter item price: ")),
11+
quantity=int(input("Enter item quantity: "))
12+
)),
13+
"2": ("Edit Item", lambda: inventory.edit(input("Enter item name to edit: "))),
14+
"3": ("Remove Item", lambda: inventory.remove(input("Enter item name to remove: "))),
15+
"4": ("Sell Item", lambda: inventory.sell(
16+
input("Enter item name to sell: "),
17+
int(input("Enter quantity to sell: "))
18+
)),
19+
"5": ("View Inventory", inventory.display),
20+
"6": ("View History", inventory.view_history), # Added option
21+
"7": ("Exit", exit)
22+
}
23+
24+
while True:
25+
os.system("cls") if os.name == "nt" else os.system("clear")
26+
print("\n--- Inventory Management ---")
27+
for key, (desc, _) in menu.items():
28+
print(f"{key}. {desc}")
29+
30+
action = menu.get(input("Enter your choice: "),
31+
(None, lambda: print("Invalid choice, try again!")))[1]
32+
action()
33+
input("\nPress Enter to continue...")
34+
35+
36+
if __name__ == "__main__":
37+
main()

basics/RealTimeProject/RPG.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747
print("Good bye!")
4848
break
4949
elif choice.isdigit() and 1 <= int(choice) <= len(shop):
50-
# Chosen Item Explaination
50+
# Chosen Item Explanation
5151
'''
5252
* chosenItem
5353
``
@@ -71,7 +71,7 @@
7171
money -= shop[chosenItem]["price"]
7272
print(f"You've bought {chosenItem}. Balance: ${money}")
7373
else:
74-
print("Insuffucient Balance")
74+
print("Insufficient Balance")
7575
else:
7676
print("Invalid Choice: Please Try Again!")
7777

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import os
2+
import random
3+
from Character import Hero, Slime
4+
5+
6+
def clear_screen():
7+
os.system('cls' if os.name == 'nt' else 'clear')
8+
9+
10+
def show_actions():
11+
print("+-------------------------+")
12+
print("| 1. Attack 2. Run |")
13+
print("| 3. Inventory |")
14+
print("+-------------------------+")
15+
16+
17+
def start_game():
18+
hero = Hero(input("Enter your hero's name: "))
19+
print(f"Welcome, {hero.name}!")
20+
21+
while hero.health > 0:
22+
print("+----------------------------+")
23+
print("| 1. Adventure 2. Inventory |")
24+
print("+----------------------------+")
25+
action = input("Choose: ").strip()
26+
clear_screen()
27+
28+
if action == '2':
29+
hero.show_inventory()
30+
continue
31+
32+
if random.choice([True, False]):
33+
if random.choice([True, False]):
34+
slime = Slime()
35+
print(f"A wild {slime.name} appears!")
36+
37+
while hero.health > 0 and slime.health > 0:
38+
show_actions()
39+
action = input("Choose: ").strip()
40+
clear_screen()
41+
42+
if action == '1':
43+
loot = slime.take_damage(
44+
random.randint(1, hero.attack_power))
45+
if loot:
46+
hero.add_loot(loot)
47+
if slime.health > 0:
48+
slime.attack(hero)
49+
elif action == '2':
50+
print("You run away!")
51+
break
52+
elif action == '3':
53+
hero.show_inventory()
54+
else:
55+
print("You sense something but nothing happens...")
56+
57+
else:
58+
print("You find nothing...")
59+
60+
if input("Continue? (yes/no): ").strip().lower() != 'yes':
61+
print("Thanks for playing!")
62+
break
63+
64+
65+
if __name__ == "__main__":
66+
start_game()

0 commit comments

Comments
 (0)