Python Projects
Notes from two small projects in the “Experience” hub.
Coffee Machine
Comparing key-values between two dictionaries
resource = {
"water": 500,
"milk": 500,
"coffee": 500,
}
ingredients = {
"water": 200,
"milk": 200,
"coffee": 200,
}
def is_resource_sufficient():
for item in ingredients:
if ingredients[item] < resource[item]:
return False
print(f"There is insufficient {item}")
# the item is the KEY, i.e., "water", "milk".Pong Game
Turtle — moving by coordinate, not heading
If you want to move an object without changing its orientation, change its x and y coordinates instead of setting heading.
new_x = self.xcor() + 10
new_y = self.ycor() + 10
item.goto(new_x, new_y)Bounce logic
Reverse the movement on y or x. If y was adding 10, then subtract 10.
Hit detection (without distance())
Check if the ball passes the paddle’s y-axis and if it is close to the middle of the paddle.
Calling functions inside the initializer
You can call functions inside the initializer (__init__).
See next
- Python-Turtle-Graphics — turtle module reference
- Python-Data-Structures — the Coffee Machine relies heavily on dicts