Compare commits

..

24 Commits

Author SHA1 Message Date
ce3befd167 day 26 - comprehensions 2025-07-17 09:37:07 +02:00
612ad7c549 day 25 - US states game 2025-07-16 18:41:16 +02:00
c34b9d4c52 day 24 - a joke 2025-07-16 14:42:48 +02:00
59a3d6d830 day 23 - crossroads game 2025-07-16 14:17:51 +02:00
697d53f836 day 22 (actually, there's no 21) - finished Pong 2025-07-16 12:47:31 +02:00
670508261b day 21 - pong WIP 2025-07-15 17:43:03 +02:00
6857990be5 day 20 - fixed collision issues 2025-07-15 15:13:04 +02:00
df22e55f4b day 20 2025-07-03 15:18:56 +02:00
eaebdba4bb day 19 - turtles again T_T 2025-06-30 12:43:42 +02:00
10e04f8744 day 18 - boring turtle… 2025-06-30 00:16:25 +02:00
d23a9c9503 day 17 2025-06-27 12:00:57 +02:00
a2691e1e06 day 16 - OOP inside ! 2025-06-24 10:56:01 +02:00
ad068f268d day 15 2025-06-23 15:07:08 +02:00
7f9b263baa day 14 + cleanup 2025-06-20 11:45:12 +02:00
07f37394d9 day 12 2025-06-19 14:10:40 +02:00
71a080fc76 Removed useless variable 2025-06-18 14:53:07 +02:00
171a2574c8 day 11 - fixed a typo 2025-06-18 14:46:51 +02:00
230edd5574 day 11 - Blackjack game 2025-06-18 14:37:23 +02:00
b77a884c67 day 10 2025-06-17 17:44:13 +02:00
3b538250c4 day 9 2025-06-16 12:29:48 +02:00
cb7e9757ad day 8 - easy ! 2025-06-16 11:42:42 +02:00
8c0b19bb6c day 7 - didn't like it 2025-06-15 00:10:07 +02:00
b77a308a84 Merge branch 'main' of ssh://git.erifae.net:2223/tanguy/python_bootcamp 2025-06-13 10:51:14 +02:00
f2806a201b day 6 2025-06-13 10:50:23 +02:00
63 changed files with 5688 additions and 1 deletions

3
.gitignore vendored
View File

@ -1,2 +1,3 @@
.tool-versions
venv
venv
__pycache__

View File

@ -0,0 +1,248 @@
{
"walls": {
"1,1": [
"east"
],
"1,2": [
"east"
],
"1,3": [
"north"
],
"2,5": [
"north"
],
"1,5": [
"north"
],
"3,5": [
"north"
],
"4,5": [
"north"
],
"5,5": [
"north",
"east"
],
"2,3": [
"north",
"east"
],
"2,2": [
"east"
],
"3,2": [
"east"
],
"5,1": [
"east"
],
"5,3": [
"east",
"north"
],
"4,4": [
"east",
"north"
],
"4,2": [
"east"
],
"1,4": [
"east"
],
"5,2": [
"east",
"north"
],
"3,1": [
"north"
]
},
"small_tiles": false,
"rows": 6,
"cols": 6,
"tiles": {
"6,1": [
"mud"
],
"6,2": [
"mud"
],
"6,3": [
"mud"
],
"6,5": [
"mud"
],
"6,6": [
"mud"
],
"5,6": [
"mud"
],
"4,6": [
"mud"
],
"3,6": [
"mud"
],
"2,6": [
"mud"
],
"1,6": [
"mud"
],
"6,4": [
"grass"
],
"5,4": [
"#000000"
],
"5,5": [
"#000000"
],
"4,5": [
"#000000"
],
"3,5": [
"#000000"
],
"3,4": [
"#000000"
],
"4,4": [
"#000000"
],
"4,3": [
"#000000"
],
"3,3": [
"#000000"
],
"3,2": [
"#000000"
],
"4,2": [
"#000000"
],
"5,3": [
"#000000"
],
"5,2": [
"#000000"
],
"5,1": [
"#000000"
],
"4,1": [
"#000000"
],
"3,1": [
"#000000"
],
"2,1": [
"#000000"
],
"2,2": [
"#000000"
],
"2,3": [
"#000000"
],
"2,4": [
"#000000"
],
"2,5": [
"#000000"
],
"1,5": [
"#000000"
],
"1,4": [
"#000000"
],
"1,3": [
"#000000"
],
"1,2": [
"#000000"
],
"1,1": [
"#000000"
]
},
"goal": {
"possible_final_positions": [
[
6,
4
]
],
"position": {
"image": "racing_flag",
"x": 6,
"y": 4
}
},
"robots": [
{
"x": 3,
"y": 4,
"objects": {},
"model": "classic",
"_orientation": 3,
"_is_leaky": true,
"_prev_x": 3,
"_prev_y": 3,
"_prev_orientation": 2,
"_trace_history": [
{
"color": "seagreen",
"thickness": 2,
"prev_x": 140,
"x": 140,
"prev_y": 170,
"y": 210,
"grid_x": 3,
"grid_y": 3
},
{
"color": "seagreen",
"thickness": 2,
"prev_x": 140,
"x": 140,
"prev_y": 200,
"y": 210,
"grid_x": 3,
"grid_y": 3
}
],
"_trace_style": "default",
"_trace_color": "seagreen",
"__id": 80,
"initial_position": [
3,
3
]
}
],
"description": [
"",
"<h1>Lost in a maze</h1>",
"<p>Reeborg was exploring a dark maze and the battery in its flashlight ran out.</p>",
"<p>Write a program using an <code>if/elif/else</code> statement so Reeborg can find the exit. ",
"The secret is to have Reeborg follow along the right edge of the maze, ",
"turning right if it can, going straight ahead if it ",
"cant turn right, or turning left as a last resort.</p>",
"<h3>What you need to know</h3>",
"<ul><li>The functions <code>move()</code> and <code>turn_left()</code>.</li>",
"<li>Either the test <code>front_is_clear()</code> or <code>wall_in_front()</code>,",
"<code>right_is_clear()</code> or <code>wall_on_right()</code>, and <code>at_goal()</code>.</li>",
"<li>How to use a <code>while</code> loop and <code>if/elif/else</code> statements.</li>",
"<li>It might be useful to know how to use the negation of a test (<code>not</code> in Python).</li></ul>",
"DIFFICULTY4",
""
]
}

View File

@ -0,0 +1,248 @@
{
"walls": {
"1,1": [
"east"
],
"1,2": [
"east"
],
"1,3": [
"north"
],
"2,5": [
"north"
],
"1,5": [
"north"
],
"3,5": [
"north"
],
"4,5": [
"north"
],
"5,5": [
"north",
"east"
],
"2,3": [
"north",
"east"
],
"2,2": [
"east"
],
"3,2": [
"east"
],
"5,1": [
"east"
],
"5,3": [
"east",
"north"
],
"4,4": [
"east",
"north"
],
"4,2": [
"east"
],
"1,4": [
"east"
],
"5,2": [
"east",
"north"
],
"3,1": [
"north"
]
},
"small_tiles": false,
"rows": 6,
"cols": 6,
"tiles": {
"6,1": [
"mud"
],
"6,2": [
"mud"
],
"6,3": [
"mud"
],
"6,5": [
"mud"
],
"6,6": [
"mud"
],
"5,6": [
"mud"
],
"4,6": [
"mud"
],
"3,6": [
"mud"
],
"2,6": [
"mud"
],
"1,6": [
"mud"
],
"6,4": [
"grass"
],
"5,4": [
"#000000"
],
"5,5": [
"#000000"
],
"4,5": [
"#000000"
],
"3,5": [
"#000000"
],
"3,4": [
"#000000"
],
"4,4": [
"#000000"
],
"4,3": [
"#000000"
],
"3,3": [
"#000000"
],
"3,2": [
"#000000"
],
"4,2": [
"#000000"
],
"5,3": [
"#000000"
],
"5,2": [
"#000000"
],
"5,1": [
"#000000"
],
"4,1": [
"#000000"
],
"3,1": [
"#000000"
],
"2,1": [
"#000000"
],
"2,2": [
"#000000"
],
"2,3": [
"#000000"
],
"2,4": [
"#000000"
],
"2,5": [
"#000000"
],
"1,5": [
"#000000"
],
"1,4": [
"#000000"
],
"1,3": [
"#000000"
],
"1,2": [
"#000000"
],
"1,1": [
"#000000"
]
},
"goal": {
"possible_final_positions": [
[
6,
4
]
],
"position": {
"image": "racing_flag",
"x": 6,
"y": 4
}
},
"robots": [
{
"x": 3,
"y": 4,
"objects": {},
"model": "classic",
"_orientation": 1,
"_is_leaky": true,
"_prev_x": 3,
"_prev_y": 3,
"_prev_orientation": 2,
"_trace_history": [
{
"color": "seagreen",
"thickness": 2,
"prev_x": 140,
"x": 140,
"prev_y": 170,
"y": 210,
"grid_x": 3,
"grid_y": 3
},
{
"color": "seagreen",
"thickness": 2,
"prev_x": 140,
"x": 140,
"prev_y": 200,
"y": 210,
"grid_x": 3,
"grid_y": 3
}
],
"_trace_style": "default",
"_trace_color": "seagreen",
"__id": 80,
"initial_position": [
3,
3
]
}
],
"description": [
"",
"<h1>Lost in a maze</h1>",
"<p>Reeborg was exploring a dark maze and the battery in its flashlight ran out.</p>",
"<p>Write a program using an <code>if/elif/else</code> statement so Reeborg can find the exit. ",
"The secret is to have Reeborg follow along the right edge of the maze, ",
"turning right if it can, going straight ahead if it ",
"cant turn right, or turning left as a last resort.</p>",
"<h3>What you need to know</h3>",
"<ul><li>The functions <code>move()</code> and <code>turn_left()</code>.</li>",
"<li>Either the test <code>front_is_clear()</code> or <code>wall_in_front()</code>,",
"<code>right_is_clear()</code> or <code>wall_on_right()</code>, and <code>at_goal()</code>.</li>",
"<li>How to use a <code>while</code> loop and <code>if/elif/else</code> statements.</li>",
"<li>It might be useful to know how to use the negation of a test (<code>not</code> in Python).</li></ul>",
"DIFFICULTY4",
""
]
}

View File

@ -0,0 +1,248 @@
{
"walls": {
"1,1": [
"east"
],
"1,2": [
"east"
],
"1,3": [
"north"
],
"2,5": [
"north"
],
"1,5": [
"north"
],
"3,5": [
"north"
],
"4,5": [
"north"
],
"5,5": [
"north",
"east"
],
"2,3": [
"north",
"east"
],
"2,2": [
"east"
],
"3,2": [
"east"
],
"5,1": [
"east"
],
"5,3": [
"east",
"north"
],
"4,4": [
"east",
"north"
],
"4,2": [
"east"
],
"1,4": [
"east"
],
"5,2": [
"east",
"north"
],
"3,1": [
"north"
]
},
"small_tiles": false,
"rows": 6,
"cols": 6,
"tiles": {
"6,1": [
"mud"
],
"6,2": [
"mud"
],
"6,3": [
"mud"
],
"6,5": [
"mud"
],
"6,6": [
"mud"
],
"5,6": [
"mud"
],
"4,6": [
"mud"
],
"3,6": [
"mud"
],
"2,6": [
"mud"
],
"1,6": [
"mud"
],
"6,4": [
"grass"
],
"5,4": [
"#000000"
],
"5,5": [
"#000000"
],
"4,5": [
"#000000"
],
"3,5": [
"#000000"
],
"3,4": [
"#000000"
],
"4,4": [
"#000000"
],
"4,3": [
"#000000"
],
"3,3": [
"#000000"
],
"3,2": [
"#000000"
],
"4,2": [
"#000000"
],
"5,3": [
"#000000"
],
"5,2": [
"#000000"
],
"5,1": [
"#000000"
],
"4,1": [
"#000000"
],
"3,1": [
"#000000"
],
"2,1": [
"#000000"
],
"2,2": [
"#000000"
],
"2,3": [
"#000000"
],
"2,4": [
"#000000"
],
"2,5": [
"#000000"
],
"1,5": [
"#000000"
],
"1,4": [
"#000000"
],
"1,3": [
"#000000"
],
"1,2": [
"#000000"
],
"1,1": [
"#000000"
]
},
"goal": {
"possible_final_positions": [
[
6,
4
]
],
"position": {
"image": "racing_flag",
"x": 6,
"y": 4
}
},
"robots": [
{
"x": 3,
"y": 4,
"objects": {},
"model": "classic",
"_orientation": 2,
"_is_leaky": true,
"_prev_x": 3,
"_prev_y": 3,
"_prev_orientation": 2,
"_trace_history": [
{
"color": "seagreen",
"thickness": 2,
"prev_x": 140,
"x": 140,
"prev_y": 170,
"y": 210,
"grid_x": 3,
"grid_y": 3
},
{
"color": "seagreen",
"thickness": 2,
"prev_x": 140,
"x": 140,
"prev_y": 200,
"y": 210,
"grid_x": 3,
"grid_y": 3
}
],
"_trace_style": "default",
"_trace_color": "seagreen",
"__id": 80,
"initial_position": [
3,
3
]
}
],
"description": [
"",
"<h1>Lost in a maze</h1>",
"<p>Reeborg was exploring a dark maze and the battery in its flashlight ran out.</p>",
"<p>Write a program using an <code>if/elif/else</code> statement so Reeborg can find the exit. ",
"The secret is to have Reeborg follow along the right edge of the maze, ",
"turning right if it can, going straight ahead if it ",
"cant turn right, or turning left as a last resort.</p>",
"<h3>What you need to know</h3>",
"<ul><li>The functions <code>move()</code> and <code>turn_left()</code>.</li>",
"<li>Either the test <code>front_is_clear()</code> or <code>wall_in_front()</code>,",
"<code>right_is_clear()</code> or <code>wall_on_right()</code>, and <code>at_goal()</code>.</li>",
"<li>How to use a <code>while</code> loop and <code>if/elif/else</code> statements.</li>",
"<li>It might be useful to know how to use the negation of a test (<code>not</code> in Python).</li></ul>",
"DIFFICULTY4",
""
]
}

29
006/task.py Normal file
View File

@ -0,0 +1,29 @@
# Code to use at https://reeborg.ca/reeborg.html?lang=en&mode=python&menu=worlds%2Fmenus%2Freeborg_intro_en.json&name=Maze&url=worlds%2Ftutorial_en%2Fmaze1.json
# Reeborg was exploring a dark maze and the battery in its flashlight ran out.
# Write a program using an if/elif/else statement so Reeborg can find the exit. The secret is to have Reeborg follow along the right edge of the maze, turning right if it can, going straight ahead if it cant turn right, or turning left as a last resort.
# What you need to know
# The functions move() and turn_left().
# Either the test front_is_clear() or wall_in_front(), right_is_clear() or wall_on_right(), and at_goal().
# How to use a while loop and if/elif/else statements.
# It might be useful to know how to use the negation of a test (not in Python).
# def turn_right():
# turn_left()
# turn_left()
# turn_left()
# while front_is_clear():
# move()
# turn_left()
# while not at_goal():
# if not wall_on_right():
# turn_right()
# move()
# elif not wall_in_front():
# move()
# else:
# turn_left()

41
007/task.py Normal file
View File

@ -0,0 +1,41 @@
import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
print(chosen_word)
placeholder = "_" * len(chosen_word)
print(placeholder)
found_letters = []
lives = 6
display = placeholder
while "_" in display and lives > 0:
guess = input("Select a letter:\n").lower()
display = ""
found_a_letter = False
for letter in chosen_word:
if letter == guess:
display += letter
found_a_letter = True
found_letters.append(letter)
elif letter in found_letters:
display += letter
else:
display += "_"
if found_a_letter == False:
lives -= 1
print(display)
if lives == 0:
print("Game over!")
else:
print("You won!")

41
008/task.py Normal file
View File

@ -0,0 +1,41 @@
def shift_string(string, offset):
alphabet = "abcdefghijklmnopqrstuvwxyz"
max_offset = len(alphabet) -1
min_offset = 0
output = ""
for letter in string.lower():
letter_index = alphabet.find(letter)
if letter_index == -1:
result = letter
else:
if letter_index + offset > max_offset:
result = alphabet[letter_index - len(alphabet) + offset]
elif letter_index + offset < 0:
result = alphabet[letter_index + len(alphabet) + offset]
else:
result = alphabet[letter_index + offset]
output += result
print(f"Your result is: {output}")
b_continue = "yes"
while b_continue == "yes":
action = input("What do you want to do? \"encode\" or \"decode\"?\n")
message = input("Type your message.\n")
offset = int(input("What is your offset?\n"))
if action == "encode":
shift_string(message, offset)
elif action == "decode":
shift_string(message, -offset)
else:
print("Invalid action - Try again")
b_continue = input("Do you want to continue? \"yes\" or \"no\"\n")

20
009/task.py Normal file
View File

@ -0,0 +1,20 @@
def get_winner(bids):
highest_bid = 0
for bidder in bids:
if bids[bidder] > highest_bid:
winner = bidder
print(f"The winner is {winner} with a bid of {highest_bid}")
auction_continues = "yes"
bids = {}
while auction_continues == "yes":
bidder = input("What is your name? : ")
bid = int(input("What's your bid? : $"))
bids.update({bidder:bid})
auction_continues = input("Are there any other bidders? Type 'yes' or 'no.")
get_winner(bids)

28
010/task.py Normal file
View File

@ -0,0 +1,28 @@
def calc(a, b, operation):
return(eval(f"{a} {operation} {b}"))
a = input("What's your first number?:")
b_calculate = True
while b_calculate:
for operator in ["+", "-", "/", "*"]:
print(operator)
operation = input("Pick an operation:")
b = input("What's the next number?:")
result = str(calc(a, b, operation)).removesuffix(".0")
print(f"{a} {operation} {b} = {result}")
choice = input(f"Type 'y' to continue calculating with {result} or type 'n' to start a new calculation")
match(choice):
case "y":
a = result
case "n":
a = input("What's your first number?:")
case _:
b_calculate = False

83
011/task.py Normal file
View File

@ -0,0 +1,83 @@
import random
def draw_cards(number):
cards = []
for _i in range(0, number):
card = random.randint(2,14)
if card >= 12:
card = 10
if card == 11:
card = "A"
cards.append(card)
return(cards)
def count_score(cards):
score = sum(filter(lambda card: isinstance(card, int), cards))
for _ in filter(lambda card: isinstance(card, str), cards):
if score + 11 > 21:
score += 1
else:
score += 11
return(score)
def display_players_cards(cards, score):
print(f'Your cards: {cards}, current score: {score}')
def display_cpu_cards(cards):
print(f'Computer\'s first card: {cards[0]}')
def dealer_game(cards):
cpu_score = count_score(cards)
if cpu_score < 17:
cards.extend(draw_cards(1))
dealer_game(cards)
def compute_winner(player_cards, cpu_cards):
player_score = count_score(player_cards)
cpu_score = count_score(cpu_cards)
display_players_cards(player_cards, player_score)
display_players_cards(cpu_cards, cpu_score)
if cpu_score > 21:
print("Dealer went over 21 - You win!")
elif cpu_score == player_score:
print("It's a draw!")
elif cpu_score > player_score:
print("You lose!")
else:
print("You win")
def launch_new_game():
wanna_play = input('Do you want to play again? Type "y" or "n":')
if wanna_play == 'y':
play_blackjack([], [])
def play_blackjack(player_cards, cpu_cards):
if player_cards == []:
player_cards = draw_cards(2)
cpu_cards = draw_cards(2)
else:
player_cards.extend(draw_cards(1))
player_score = count_score(player_cards)
display_players_cards(player_cards,player_score)
display_cpu_cards(cpu_cards)
if player_score > 21:
print("You went over 21 - You lose!")
launch_new_game()
action = input('Type "y" to get another card, type "n" to pass:')
if action == 'y':
play_blackjack(player_cards, cpu_cards)
else:
dealer_game(cpu_cards)
compute_winner(player_cards, cpu_cards)
launch_new_game()
wanna_play = input('Do you want to play a game of Blackjack? Type "y" or "n":')
if wanna_play == 'y':
play_blackjack([], [])

41
012/task.py Normal file
View File

@ -0,0 +1,41 @@
import random
def play_attempt(number_to_find):
guess = int(input("Make a guess: "))
if guess > number_to_find:
print("Number is lower")
return(True)
elif guess < number_to_find:
print("Number is higher")
return(True)
else:
print("You won ! - Number to find was {number_to_find}")
return(False)
def play_game(level):
if level == "easy":
attempts_remaining = 10
else:
attempts_remaining = 5
number_to_find = random.randint(1, 100)
for attemps in range(attempts_remaining):
print(f"Attempts remainging: {attempts_remaining}")
b_keep_going = play_attempt(number_to_find)
if b_keep_going == False:
break
attempts_remaining -= 1
if attempts_remaining == 0:
print(f"You lost! - Number to find was {number_to_find}")
return
print("I'm thinking of a number between 1 and 100.")
level = input("Chose a difficulty: 'easy' or 'hard':")
play_game(level)

1
013/task.py Normal file
View File

@ -0,0 +1 @@
# No code on this day! Learnt how to debug online

302
014/game_data.py Normal file
View File

@ -0,0 +1,302 @@
data = [
{
'name': 'Instagram',
'follower_count': 346,
'description': 'Social media platform',
'country': 'United States'
},
{
'name': 'Cristiano Ronaldo',
'follower_count': 215,
'description': 'Footballer',
'country': 'Portugal'
},
{
'name': 'Ariana Grande',
'follower_count': 183,
'description': 'Musician and actress',
'country': 'United States'
},
{
'name': 'Dwayne Johnson',
'follower_count': 181,
'description': 'Actor and professional wrestler',
'country': 'United States'
},
{
'name': 'Selena Gomez',
'follower_count': 174,
'description': 'Musician and actress',
'country': 'United States'
},
{
'name': 'Kylie Jenner',
'follower_count': 172,
'description': 'Reality TV personality and businesswoman and Self-Made Billionaire',
'country': 'United States'
},
{
'name': 'Kim Kardashian',
'follower_count': 167,
'description': 'Reality TV personality and businesswoman',
'country': 'United States'
},
{
'name': 'Lionel Messi',
'follower_count': 149,
'description': 'Footballer',
'country': 'Argentina'
},
{
'name': 'Beyoncé',
'follower_count': 145,
'description': 'Musician',
'country': 'United States'
},
{
'name': 'Neymar',
'follower_count': 138,
'description': 'Footballer',
'country': 'Brasil'
},
{
'name': 'National Geographic',
'follower_count': 135,
'description': 'Magazine',
'country': 'United States'
},
{
'name': 'Justin Bieber',
'follower_count': 133,
'description': 'Musician',
'country': 'Canada'
},
{
'name': 'Taylor Swift',
'follower_count': 131,
'description': 'Musician',
'country': 'United States'
},
{
'name': 'Kendall Jenner',
'follower_count': 127,
'description': 'Reality TV personality and Model',
'country': 'United States'
},
{
'name': 'Jennifer Lopez',
'follower_count': 119,
'description': 'Musician and actress',
'country': 'United States'
},
{
'name': 'Nicki Minaj',
'follower_count': 113,
'description': 'Musician',
'country': 'Trinidad and Tobago'
},
{
'name': 'Nike',
'follower_count': 109,
'description': 'Sportswear multinational',
'country': 'United States'
},
{
'name': 'Khloé Kardashian',
'follower_count': 108,
'description': 'Reality TV personality and businesswoman',
'country': 'United States'
},
{
'name': 'Miley Cyrus',
'follower_count': 107,
'description': 'Musician and actress',
'country': 'United States'
},
{
'name': 'Katy Perry',
'follower_count': 94,
'description': 'Musician',
'country': 'United States'
},
{
'name': 'Kourtney Kardashian',
'follower_count': 90,
'description': 'Reality TV personality',
'country': 'United States'
},
{
'name': 'Kevin Hart',
'follower_count': 89,
'description': 'Comedian and actor',
'country': 'United States'
},
{
'name': 'Ellen DeGeneres',
'follower_count': 87,
'description': 'Comedian',
'country': 'United States'
},
{
'name': 'Real Madrid CF',
'follower_count': 86,
'description': 'Football club',
'country': 'Spain'
},
{
'name': 'FC Barcelona',
'follower_count': 85,
'description': 'Football club',
'country': 'Spain'
},
{
'name': 'Rihanna',
'follower_count': 81,
'description': 'Musician and businesswoman',
'country': 'Barbados'
},
{
'name': 'Demi Lovato',
'follower_count': 80,
'description': 'Musician and actress',
'country': 'United States'
},
{
'name': "Victoria's Secret",
'follower_count': 69,
'description': 'Lingerie brand',
'country': 'United States'
},
{
'name': 'Zendaya',
'follower_count': 68,
'description': 'Actress and musician',
'country': 'United States'
},
{
'name': 'Shakira',
'follower_count': 66,
'description': 'Musician',
'country': 'Colombia'
},
{
'name': 'Drake',
'follower_count': 65,
'description': 'Musician',
'country': 'Canada'
},
{
'name': 'Chris Brown',
'follower_count': 64,
'description': 'Musician',
'country': 'United States'
},
{
'name': 'LeBron James',
'follower_count': 63,
'description': 'Basketball player',
'country': 'United States'
},
{
'name': 'Vin Diesel',
'follower_count': 62,
'description': 'Actor',
'country': 'United States'
},
{
'name': 'Cardi B',
'follower_count': 67,
'description': 'Musician',
'country': 'United States'
},
{
'name': 'David Beckham',
'follower_count': 82,
'description': 'Footballer',
'country': 'United Kingdom'
},
{
'name': 'Billie Eilish',
'follower_count': 61,
'description': 'Musician',
'country': 'United States'
},
{
'name': 'Justin Timberlake',
'follower_count': 59,
'description': 'Musician and actor',
'country': 'United States'
},
{
'name': 'UEFA Champions League',
'follower_count': 58,
'description': 'Club football competition',
'country': 'Europe'
},
{
'name': 'NASA',
'follower_count': 56,
'description': 'Space agency',
'country': 'United States'
},
{
'name': 'Emma Watson',
'follower_count': 56,
'description': 'Actress',
'country': 'United Kingdom'
},
{
'name': 'Shawn Mendes',
'follower_count': 57,
'description': 'Musician',
'country': 'Canada'
},
{
'name': 'Virat Kohli',
'follower_count': 55,
'description': 'Cricketer',
'country': 'India'
},
{
'name': 'Gigi Hadid',
'follower_count': 54,
'description': 'Model',
'country': 'United States'
},
{
'name': 'Priyanka Chopra Jonas',
'follower_count': 53,
'description': 'Actress and musician',
'country': 'India'
},
{
'name': '9GAG',
'follower_count': 52,
'description': 'Social media platform',
'country': 'China'
},
{
'name': 'Ronaldinho',
'follower_count': 51,
'description': 'Footballer',
'country': 'Brasil'
},
{
'name': 'Maluma',
'follower_count': 50,
'description': 'Musician',
'country': 'Colombia'
},
{
'name': 'Camila Cabello',
'follower_count': 49,
'description': 'Musician',
'country': 'Cuba'
},
{
'name': 'NBA',
'follower_count': 47,
'description': 'Club Basketball Competition',
'country': 'United States'
}
]

44
014/task.py Normal file
View File

@ -0,0 +1,44 @@
from game_data import data
import random
def pick_contender(exception = {}) :
contender = exception
while contender == exception:
contender = random.choice(data)
return(contender)
def get_answer():
answer = input("Who has more followers? Type 'A' or 'B':")
if answer.lower() not in ["a", "b"]:
print("Invalid option - try again")
return(get_answer())
return(answer.lower())
def run_round(current_contender, score):
if current_contender == {}:
current_contender = pick_contender()
new_contender = pick_contender(current_contender)
print(f"Compare A: {current_contender['name']}, a {current_contender['description']}, from {current_contender['country']}")
print(f"Against B: {new_contender['name']}, a {new_contender['description']}, from {new_contender['country']}")
answer = get_answer()
if current_contender['follower_count'] > new_contender['follower_count']:
winner = "a"
else:
winner = "b"
if answer == winner:
score +=1
print("Correct!")
print(f"Current score: {score}")
run_round(new_contender, score)
else:
print("Wrong!")
print(f"Game over! Your final score: {score}")
run_round({}, 0)

98
015/main.py Normal file
View File

@ -0,0 +1,98 @@
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"money": 0.0,
}
b_is_on = True
def print_report():
print(f"Water: {str(resources['water'])} ml")
print(f"Milk: {str(resources['milk'])} ml")
print(f"Coffe: {str(resources['coffee'])} ml")
print(f"Money: ${str(resources['money'])}")
def check_resources(drink):
for ingredient in MENU[drink]['ingredients']:
if MENU[drink]['ingredients'][ingredient] > resources[ingredient]:
print(f'Sorry there is not enough {ingredient}')
return False
return True
def collect_coins(drink):
coins = {
"quarters": 0.25,
"dimes": 0.10,
"nickels": 0.05,
"pennies": 0.01,
}
print("Please insert coins.")
total_input = 0
for coin in coins:
coins_number = input(f"How many {coin}? ")
total_input += int(coins_number) * coins[coin]
if total_input < MENU[drink]['cost']:
print("Sorry that's not enough money. Money refunded.")
return False
else:
if total_input > MENU[drink]['cost']:
print(f"Here is ${total_input - MENU[drink]['cost']} in change.")
resources['money'] = total_input + resources['money']
return True
def make_drink(drink):
for ingredient in MENU[drink]['ingredients']:
resources[ingredient] = MENU[drink]['ingredients'][ingredient] - resources[ingredient]
print(f"Here is your {drink} ☕️. Enjoy!")
def prepare_drink(drink):
if drink not in MENU.keys():
print("Invalid drink - Try again")
return
if not check_resources(drink):
return
if not collect_coins(drink):
return
make_drink(drink)
while b_is_on == True:
choice = input('What would you like? (espresso/latte/cappuccino):')
match(choice):
case "off":
b_is_on = False
case "report":
print_report()
case _:
prepare_drink(choice)

29
016/coffee_maker.py Normal file
View File

@ -0,0 +1,29 @@
class CoffeeMaker:
"""Models the machine that makes the coffee"""
def __init__(self):
self.resources = {
"water": 300,
"milk": 200,
"coffee": 100,
}
def report(self):
"""Prints a report of all resources."""
print(f"Water: {self.resources['water']}ml")
print(f"Milk: {self.resources['milk']}ml")
print(f"Coffee: {self.resources['coffee']}g")
def is_resource_sufficient(self, drink):
"""Returns True when order can be made, False if ingredients are insufficient."""
can_make = True
for item in drink.ingredients:
if drink.ingredients[item] > self.resources[item]:
print(f"Sorry there is not enough {item}.")
can_make = False
return can_make
def make_coffee(self, order):
"""Deducts the required ingredients from the resources."""
for item in order.ingredients:
self.resources[item] -= order.ingredients[item]
print(f"Here is your {order.name} ☕️. Enjoy!")

22
016/main.py Normal file
View File

@ -0,0 +1,22 @@
from menu import Menu
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine
my_coffee_maker = CoffeeMaker()
my_menu = Menu()
my_money_machine = MoneyMachine()
is_on = True
while is_on == True:
choice = input(f"What would you like? ({my_menu.get_items()}):")
if choice == "report":
my_coffee_maker.report()
my_money_machine.report()
elif choice == "off":
is_on = False
else:
order = my_menu.find_drink(choice)
if order and my_coffee_maker.is_resource_sufficient(order) and my_money_machine.make_payment(order.cost):
my_coffee_maker.make_coffee(order)

34
016/menu.py Normal file
View File

@ -0,0 +1,34 @@
class MenuItem:
"""Models each Menu Item."""
def __init__(self, name, water, milk, coffee, cost):
self.name = name
self.cost = cost
self.ingredients = {
"water": water,
"milk": milk,
"coffee": coffee
}
class Menu:
"""Models the Menu with drinks."""
def __init__(self):
self.menu = [
MenuItem(name="latte", water=200, milk=150, coffee=24, cost=2.5),
MenuItem(name="espresso", water=50, milk=0, coffee=18, cost=1.5),
MenuItem(name="cappuccino", water=250, milk=50, coffee=24, cost=3),
]
def get_items(self):
"""Returns all the names of the available menu items"""
options = ""
for item in self.menu:
options += f"{item.name}/"
return options
def find_drink(self, order_name):
"""Searches the menu for a particular drink by name. Returns that item if it exists, otherwise returns None"""
for item in self.menu:
if item.name == order_name:
return item
print("Sorry that item is not available.")

40
016/money_machine.py Normal file
View File

@ -0,0 +1,40 @@
class MoneyMachine:
CURRENCY = "$"
COIN_VALUES = {
"quarters": 0.25,
"dimes": 0.10,
"nickles": 0.05,
"pennies": 0.01
}
def __init__(self):
self.profit = 0
self.money_received = 0
def report(self):
"""Prints the current profit"""
print(f"Money: {self.CURRENCY}{self.profit}")
def process_coins(self):
"""Returns the total calculated from coins inserted."""
print("Please insert coins.")
for coin in self.COIN_VALUES:
self.money_received += int(input(f"How many {coin}?: ")) * self.COIN_VALUES[coin]
return self.money_received
def make_payment(self, cost):
"""Returns True when payment is accepted, or False if insufficient."""
self.process_coins()
if self.money_received >= cost:
change = round(self.money_received - cost, 2)
print(f"Here is {self.CURRENCY}{change} in change.")
self.profit += cost
self.money_received = 0
return True
else:
print("Sorry that's not enough money. Money refunded.")
self.money_received = 0
return False

14
017/data.py Normal file
View File

@ -0,0 +1,14 @@
question_data = [
{"text": "A slug's blood is green.", "answer": "True"},
{"text": "The loudest animal is the African Elephant.", "answer": "False"},
{"text": "Approximately one quarter of human bones are in the feet.", "answer": "True"},
{"text": "The total surface area of a human lungs is the size of a football pitch.", "answer": "True"},
{"text": "In West Virginia, USA, if you accidentally hit an animal with your car, you are free to take it home to eat.", "answer": "True"},
{"text": "In London, UK, if you happen to die in the House of Parliament, you are entitled to a state funeral.", "answer": "False"},
{"text": "It is illegal to pee in the Ocean in Portugal.", "answer": "True"},
{"text": "You can lead a cow down stairs but not up stairs.", "answer": "False"},
{"text": "Google was originally called 'Backrub'.", "answer": "True"},
{"text": "Buzz Aldrin's mother's maiden name was 'Moon'.", "answer": "True"},
{"text": "No piece of square dry paper can be folded in half more than 7 times.", "answer": "False"},
{"text": "A few ounces of chocolate can to kill a small dog.", "answer": "True"},
]

19
017/main.py Normal file
View File

@ -0,0 +1,19 @@
from question_model import Question
from quiz_brain import QuizBrain
import httpx
r = httpx.get("https://opentdb.com/api.php?amount=20&difficulty=easy&type=boolean")
question_data = r.json()
question_bank = []
for a_question in question_data['results']:
question_bank.append(Question(a_question['question'], a_question['correct_answer']))
quiz = QuizBrain(question_bank)
while quiz.still_has_question():
quiz.next_question()
print("You've completed the quiz")
print(f"You final score was {quiz.score}/{quiz.question_number}")

4
017/question_model.py Normal file
View File

@ -0,0 +1,4 @@
class Question:
def __init__(self, text, answer):
self.text = text
self.answer = answer

25
017/quiz_brain.py Normal file
View File

@ -0,0 +1,25 @@
class QuizBrain:
def __init__(self, questions_list):
self.question_number = 0
self.questions_list = questions_list
self.score = 0
def still_has_question(self):
return self.question_number < len(self.questions_list)
def next_question(self):
current_question = self.questions_list[self.question_number]
self.question_number += 1
user_answer = input(f"Q.{self.question_number}: {current_question.text} (True/False)?: ")
is_correct = self.check_answer(user_answer, current_question.answer)
def check_answer(self, user_answer, expected_answer):
if user_answer.lower() == expected_answer.lower():
print("You got it right!")
self.score +=1
else:
print("That's wrong")
print(f"The correct answer was: {expected_answer}")
print(f"You current score is {self.score} / {self.question_number}")
print("\n")

BIN
018/image.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

55
018/main.py Normal file
View File

@ -0,0 +1,55 @@
import colorgram
import turtle
import random
def create_colorset(colors_nb):
colors = colorgram.extract('/Users/tanguy/Workspace/python/bootcamp/018/image.jpg', colors_nb)
return(colors)
def extract_random_color_from_set(colorset):
color = random.choice(colorset)
return(color.rgb)
def set_initial_position(t):
t.pu()
t.backward(400)
t.left(90)
t.backward(400)
t.right(90)
def draw_line(t):
for _ in range(11):
t.pd()
t.dot(20, extract_random_color_from_set(colorset))
t.pu()
t.forward(40)
def go_to_next_line(t):
t.left(90)
t.forward(40)
t.left(90)
t.forward(440)
t.right(180)
colorset = create_colorset(20)
t = turtle.Turtle()
turtle.colormode(255)
t.speed("fastest")
t.hideturtle()
set_initial_position(t)
for _ in range(10):
draw_line(t)
go_to_next_line(t)
screen = turtle.Screen()
screen.exitonclick()

52
018/sandbox.py Normal file
View File

@ -0,0 +1,52 @@
from turtle import Turtle, Screen
import random
def draw_square(turtle):
for _ in range(4):
turtle.forward(100)
turtle.right(90)
def draw_dashed_line(turtle):
for i in range(30):
if i % 2 == 0:
turtle.up()
else:
turtle.down()
turtle.forward(10)
def draw_shapes(turtle):
for sides_number in range(3, 11):
rgb = ()
for _ in range(3):
rgb += (random.random(),)
turtle.pencolor(rgb[0], rgb[1] ,rgb[2])
angle = 360 / sides_number
for _ in range(0, sides_number):
turtle.forward(100)
turtle.right(angle)
def draw_spirograph(turtle, nb_circles):
angle = 360 / nb_circles
for _ in range(0, nb_circles):
rgb = ()
for _ in range(3):
rgb += (random.random(),)
turtle.pencolor(rgb[0], rgb[1] ,rgb[2])
turtle.circle(100)
turtle.left(angle)
turtle = Turtle()
turtle.speed("fastest")
# draw_square(turtle)
# draw_dashed_line(turtle)
# draw_shapes(turtle)
draw_spirograph(turtle, 180)
screen = Screen()
screen.exitonclick()
turtle.pencolor

55
019/main.py Normal file
View File

@ -0,0 +1,55 @@
from turtle import Turtle, Screen
import random
screen = Screen()
screensize = screen.screensize()
current_top_position = -screen.window_width() / 2 + 20
ending_point = -current_top_position
colors = ["red", "green", "blue", "purple", "orange", "yellow", "black", "pink"]
turtles = []
winner = None
def init_turtles(turtles):
for i in range(8):
t = Turtle()
t.pu()
t.color(colors[i])
t.shape("turtle")
t.teleport(x=current_top_position, y = i * 50 - 200)
turtles.append(t)
return turtles
def race(turtles, current_top_position):
for i in range(8):
speed = random.randint(1,20)
turtles[i].forward(speed)
if turtles[i].xcor() > current_top_position:
current_top_position = turtles[i].xcor()
if turtles[i].xcor() >= ending_point:
print("finished")
return current_top_position, i
return current_top_position, None
user_bet = screen.textinput("Place your bet", "Which turtle color will you bet on?")
init_turtles(turtles)
while winner == None:
current_top_position, winner = race(turtles, current_top_position)
winning_turtle = turtles[winner].color()[0]
print(f"Race ended ! Winner is {winning_turtle} !")
if winning_turtle == user_bet:
print("You won your bet!")
else:
print("You lost your bet!")
screen.exitonclick()

33
019/sandbox.py Normal file
View File

@ -0,0 +1,33 @@
from turtle import Turtle, Screen
turtle = Turtle()
screen = Screen()
def move_forward():
turtle.forward(10)
def move_backward():
turtle.backward(10)
def rotate_right():
heading = turtle.heading() - 10
turtle.setheading(heading)
def rotate_left():
heading = turtle.heading() + 10
turtle.setheading(heading)
def clear():
turtle.clear()
turtle.pu()
turtle.home()
turtle.pd()
screen.listen()
screen.onkey(move_forward, "Up")
screen.onkey(move_backward, "Down")
screen.onkey(rotate_left, "Left")
screen.onkey(rotate_right, "Right")
screen.onkey(clear, "c")
screen.exitonclick()

23
020/food.py Normal file
View File

@ -0,0 +1,23 @@
from turtle import Turtle, Screen
import random
class Food(Turtle):
def __init__(self, screen_x_size, screen_y_size):
super().__init__()
self.shape("square")
self.color("cyan")
self.pu()
x_limit = int((screen_x_size-20)/40)
y_limit = int((screen_y_size-20)/40)
x_pos = random.randint(-x_limit, x_limit)*20
y_pos = random.randint(-y_limit, y_limit)*20
self.teleport(x=x_pos, y=y_pos)
def get_position(self):
return self.xcor(), self.ycor()
def hide(self):
self.hideturtle()

69
020/game.py Normal file
View File

@ -0,0 +1,69 @@
from turtle import Screen, Turtle
from snake import Snake
from food import Food
import time
class GameManager:
BOARD_WIDTH=600
BOARD_HEIGHT=600
def __init__(self):
self.screen = Screen()
self.screen.setup(width=self.BOARD_WIDTH, height=self.BOARD_HEIGHT)
self.screen.bgcolor("black")
self.screen.title("Snake game")
self.screen.tracer(0)
self.snake = Snake()
self.screen.update()
self.food_on_screen = False
self.game_on = True
def control_snake(self):
self.screen.listen()
self.screen.onkey(self.snake.up, "Up")
self.screen.onkey(self.snake.right, "Right")
self.screen.onkey(self.snake.down, "Down")
self.screen.onkey(self.snake.left, "Left")
self.snake.move()
self.screen.update()
def check_collision(self):
x, y = self.snake.get_head_position()
wall_collision = x >= self.BOARD_WIDTH/2 or x <= -self.BOARD_WIDTH/2 or y >= self.BOARD_HEIGHT/2 or y <= -self.BOARD_HEIGHT/2
snake_collision = self.snake.tailbite()
return wall_collision or snake_collision
def is_food_eaten(self):
snake_head = self.snake.get_head()
if snake_head.distance(self.food) <= 15:
self.food.hide()
self.snake.extend()
self.food_on_screen = False
def game_round(self):
if not self.food_on_screen:
self.food = Food(self.BOARD_WIDTH, self.BOARD_HEIGHT)
self.food_on_screen = True
self.control_snake()
if self.check_collision():
self.game_on = False
self.game_over()
self.is_food_eaten()
time.sleep(0.1)
def get_screen(self):
return self.screen
def game_over(self):
turtle = Turtle()
turtle.color("yellow")
turtle.write("Game over!", move=False, align='center', font=('Arial', 32, 'normal'))

9
020/main.py Normal file
View File

@ -0,0 +1,9 @@
from game import GameManager
import time
game = GameManager()
while game.game_on == True:
game.game_round()
game.get_screen().exitonclick()

64
020/snake.py Normal file
View File

@ -0,0 +1,64 @@
from turtle import Turtle
class Snake:
def __init__(self):
self.segments = []
self.length = 3
self.extend_snake = False
for i in range(self.length):
turtle = Turtle(shape="square")
turtle.color("white")
turtle.pu()
x_pos = -i *20
turtle.teleport(x=x_pos)
self.segments.append(turtle)
def move(self):
tail_position = self.segments[-1].position()
for i in range(len(self.segments) - 1, 0, -1):
self.segments[i].goto(self.segments[i-1].position())
self.segments[0].forward(20)
if self.extend_snake == True:
turtle = Turtle(shape="square")
turtle.color("white")
turtle.pu()
turtle.goto(tail_position)
self.segments.append(turtle)
self.extend_snake = False
def up(self):
if self.segments[0].heading() != 270:
for segment in self.segments:
segment.setheading(90)
def right(self):
if self.segments[0].heading() != 180:
for segment in self.segments:
segment.setheading(0)
def down(self):
if self.segments[0].heading() != 90:
for segment in self.segments:
segment.setheading(270)
def left(self):
if self.segments[0].heading() != 0:
for segment in self.segments:
segment.setheading(180)
def get_head_position(self):
return self.segments[0].xcor(), self.segments[0].ycor()
def get_head(self):
return self.segments[0]
def tailbite(self):
for i in range(len(self.segments) - 1, 0, -1):
if self.segments[0].distance(self.segments[i]) <= 15:
return True
return False
def extend(self):
self.extend_snake = True

28
022/ball.py Normal file
View File

@ -0,0 +1,28 @@
from turtle import Turtle
import random
class Ball(Turtle):
def __init__(self):
super().__init__()
self.shape("circle")
self.color("white")
self.speed("fastest")
self.pu()
self.move_speed = 0.1
self.angle = random.randint(0,45)
self.setheading(self.angle)
print(self.angle)
def move(self):
self.forward(20)
def bounce_wall(self):
self.angle = -self.angle
self.setheading(self.angle)
def bounce_paddle(self):
self.angle = 180 - self.angle
self.setheading(self.angle)

85
022/game.py Normal file
View File

@ -0,0 +1,85 @@
from turtle import Turtle, Screen
from paddle import Paddle
from ball import Ball
from score import Score
import time
class GameManager():
BOARD_WIDTH=800
BOARD_HEIGHT=600
def __init__(self):
self.screen = Screen()
self.screen.setup(width=self.BOARD_WIDTH, height=self.BOARD_HEIGHT)
self.screen.bgcolor("black")
self.screen.title("PONG")
self.screen.tracer(0)
self.draw_delimiter()
self.screen.update()
self.game_on = True
self.right_paddle = Paddle(350)
self.left_paddle = Paddle(-370)
self.right_score = Score(30)
self.left_score = Score(-30)
self.ball = Ball()
def draw_delimiter(self):
delimiter = Turtle()
max_y = int(self.BOARD_HEIGHT/2)
delimiter.color("white")
delimiter.shape("square")
delimiter.pen(pensize=3)
delimiter.hideturtle()
delimiter.pu()
delimiter.goto(x=0, y=-max_y)
for i in range(-max_y, max_y, 20):
delimiter.goto(x=0, y=i+10)
delimiter.pu()
delimiter.goto(x=0, y=i+20)
delimiter.pd()
def game_round(self):
self.control_paddle()
self.ball.move()
if self.ball.xcor() > 400:
self.game_on = False
self.left_score.increment()
self.left_score.update()
if self.ball.xcor() < -400:
self.game_on = False
self.right_score.increment()
self.right_score.update()
if self.game_on == False:
self.ball.clear()
self.ball = Ball()
self.right_paddle.reset_position(350)
self.left_paddle.reset_position(-370)
self.game_on = True
if abs(self.ball.ycor()) > 280:
self.ball.bounce_wall()
if (abs(self.ball.xcor() - self.right_paddle.xcor()) <= 20 and abs(self.ball.ycor() - self.right_paddle.ycor()) < 50) or (abs(self.ball.xcor() - self.left_paddle.xcor()) <= 20 and abs(self.ball.ycor() - self.left_paddle.ycor()) < 50):
self.ball.bounce_paddle()
self.ball.move_speed = self.ball.move_speed * 0.1
time.sleep(self.ball.move_speed)
def control_paddle(self):
self.screen.listen()
self.screen.onkey(self.right_paddle.up, "Up")
self.screen.onkey(self.right_paddle.down, "Down")
self.screen.onkey(self.left_paddle.up, "q")
self.screen.onkey(self.left_paddle.down, "w")
self.screen.update()

7
022/main.py Normal file
View File

@ -0,0 +1,7 @@
from game import GameManager
from paddle import Paddle
game = GameManager()
while game.game_on == True:
game.game_round()
game.screen.exitonclick()

20
022/paddle.py Normal file
View File

@ -0,0 +1,20 @@
from turtle import Turtle
class Paddle(Turtle):
def __init__(self, x_pos):
super().__init__()
self.shape("square")
self.shapesize(stretch_wid=5, stretch_len=1)
self.color("white")
self.pu()
self.teleport(x=x_pos, y=0)
def reset_position(self, x_pos):
self.teleport(x=x_pos, y=0)
def up(self):
self.goto(x=self.xcor(), y=self.ycor()+20)
def down(self):
self.goto(x=self.xcor(), y=self.ycor()-20)

18
022/score.py Normal file
View File

@ -0,0 +1,18 @@
from turtle import Turtle
class Score(Turtle):
def __init__(self, x_pos):
super().__init__()
self.score = 0
self.color("white")
self.hideturtle()
self.pu()
self.goto(x=x_pos, y=270)
self.write(self.score, move=False, align='center', font=('Arial', 24, 'normal'))
def increment(self):
self.score += 1
def update(self):
self.clear()
self.write(self.score, move=False, align='center', font=('Arial', 24, 'normal'))

43
023/car_manager.py Normal file
View File

@ -0,0 +1,43 @@
import random
from turtle import Turtle
class CarManager:
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
CAR_GENERATION_PROBABILITY = 5
def __init__(self):
self.cars = []
self.add_car()
def execute_round(self, level):
if self.should_generate_car_on_turn():
self.add_car()
speed = 5 + (level - 1) * 10
self.move(speed)
def should_generate_car_on_turn(self):
return random.randint(1,self.CAR_GENERATION_PROBABILITY) % self.CAR_GENERATION_PROBABILITY == 0
def move(self, speed):
for car in self.cars:
car.goto(x=car.xcor()-speed, y=car.ycor())
def add_car(self):
car = Turtle()
car.color(random.choice(self.COLORS))
car.shape("square")
car.shapesize(stretch_wid=1, stretch_len=2)
car.pu()
car.goto(x=300, y=random.randint(-260, 280))
self.cars.append(car)
def check_collision(self, player):
for car in self.cars:
if abs(player.ycor() - car.ycor()) < 10 and abs(player.xcor() - car.xcor()) < 30:
return True
return False

34
023/main.py Normal file
View File

@ -0,0 +1,34 @@
import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard
screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
screen.bgcolor("white")
game_is_on = True
player = Player()
scoreboard = Scoreboard()
cars = CarManager()
while game_is_on:
screen.listen()
screen.onkey(player.move_up, "Up")
cars.execute_round(scoreboard.level)
if cars.check_collision(player):
game_is_on = False
scoreboard.game_over()
time.sleep(0.1)
screen.update()
if player.has_won():
player.reset_position()
scoreboard.level += 1
scoreboard.update_score(scoreboard.level)
print("Finished")
screen.exitonclick()

27
023/player.py Normal file
View File

@ -0,0 +1,27 @@
from turtle import Turtle
class Player(Turtle):
STARTING_POSITION = (0, -280)
MOVE_DISTANCE = 10
FINISH_LINE_Y = 280
def __init__(self):
super().__init__()
self.shape("turtle")
self.color("black")
self.pu()
self.setheading(90)
self.goto(self.STARTING_POSITION)
def move_up(self):
self.goto(x=self.xcor(), y=self.ycor() + self.MOVE_DISTANCE)
print(self.ycor())
def has_won(self):
if self.ycor() >= self.FINISH_LINE_Y:
return True
return False
def reset_position(self):
self.clear()
self.goto(self.STARTING_POSITION)

23
023/scoreboard.py Normal file
View File

@ -0,0 +1,23 @@
from turtle import Turtle
class Scoreboard(Turtle):
FONT = ("Courier", 24, "normal")
def __init__(self):
super().__init__()
self.color("black")
self.pu()
self.hideturtle()
self.goto(-280, 260)
self.level = 1
self.update_score(self.level)
def update_score(self, level):
self.clear()
self.write(f"Level: {level}", False, align="left", font=self.FONT)
def game_over(self):
self.goto(0,0)
self.write("GAME OVER", False, align="center", font=self.FONT)

View File

@ -0,0 +1,7 @@
Dear [name],
You are invited to my birthday this Saturday.
Hope you can make it!
Angela

View File

@ -0,0 +1,8 @@
Aang
Zuko
Appa
Katara
Sokka
Momo
Uncle Iroh
Toph

20
024/main.py Normal file
View File

@ -0,0 +1,20 @@
#TODO: Create a letter using starting_letter.txt
#for each name in invited_names.txt
#Replace the [name] placeholder with the actual name.
#Save the letters in the folder "ReadyToSend".
#Hint1: This method will help you: https://www.w3schools.com/python/ref_file_readlines.asp
#Hint2: This method will also help you: https://www.w3schools.com/python/ref_string_replace.asp
#Hint3: THis method will help you: https://www.w3schools.com/python/ref_string_strip.asp
with open("input/names/invited_names.txt") as n:
for name in n.readlines():
name = name.strip()
output_letter = ""
with open("input/letters/starting_letter.txt") as l:
for letter_line in l:
output_letter += letter_line.replace("[name]", name)
with open(f"output/ready_to_send/to_{name}.txt", "w") as final:
final.write(output_letter)

View File

@ -0,0 +1,7 @@
Dear Aang,
You are invited to my birthday this Saturday.
Hope you can make it!
Angela

View File

@ -0,0 +1,7 @@
Dear Aang,
You are invited to my birthday this Saturday.
Hope you can make it!
Angela

View File

@ -0,0 +1,7 @@
Dear Appa,
You are invited to my birthday this Saturday.
Hope you can make it!
Angela

View File

@ -0,0 +1,7 @@
Dear Katara,
You are invited to my birthday this Saturday.
Hope you can make it!
Angela

View File

@ -0,0 +1,7 @@
Dear Momo,
You are invited to my birthday this Saturday.
Hope you can make it!
Angela

View File

@ -0,0 +1,7 @@
Dear Sokka,
You are invited to my birthday this Saturday.
Hope you can make it!
Angela

View File

@ -0,0 +1,7 @@
Dear Toph,
You are invited to my birthday this Saturday.
Hope you can make it!
Angela

View File

@ -0,0 +1,7 @@
Dear Uncle Iroh,
You are invited to my birthday this Saturday.
Hope you can make it!
Angela

View File

@ -0,0 +1,7 @@
Dear Zuko,
You are invited to my birthday this Saturday.
Hope you can make it!
Angela

51
025/50_states.csv Normal file
View File

@ -0,0 +1,51 @@
state,x,y
Alabama,139,-77
Alaska,-204,-170
Arizona,-203,-40
Arkansas,57,-53
California,-297,13
Colorado,-112,20
Connecticut,297,96
Delaware,275,42
Florida,220,-145
Georgia,182,-75
Hawaii,-317,-143
Idaho,-216,122
Illinois,95,37
Indiana,133,39
Iowa,38,65
Kansas,-17,5
Kentucky,149,1
Louisiana,59,-114
Maine,319,164
Maryland,288,27
Massachusetts,312,112
Michigan,148,101
Minnesota,23,135
Mississippi,94,-78
Missouri,49,6
Montana,-141,150
Nebraska,-61,66
Nevada,-257,56
New Hampshire,302,127
New Jersey,282,65
New Mexico,-128,-43
New York,236,104
North Carolina,239,-22
North Dakota,-44,158
Ohio,176,52
Oklahoma,-8,-41
Oregon,-278,138
Pennsylvania,238,72
Rhode Island,318,94
South Carolina,218,-51
South Dakota,-44,109
Tennessee,131,-34
Texas,-38,-106
Utah,-189,34
Vermont,282,154
Virginia,234,12
Washington,-257,193
West Virginia,200,20
Wisconsin,83,113
Wyoming,-134,90
1 state x y
2 Alabama 139 -77
3 Alaska -204 -170
4 Arizona -203 -40
5 Arkansas 57 -53
6 California -297 13
7 Colorado -112 20
8 Connecticut 297 96
9 Delaware 275 42
10 Florida 220 -145
11 Georgia 182 -75
12 Hawaii -317 -143
13 Idaho -216 122
14 Illinois 95 37
15 Indiana 133 39
16 Iowa 38 65
17 Kansas -17 5
18 Kentucky 149 1
19 Louisiana 59 -114
20 Maine 319 164
21 Maryland 288 27
22 Massachusetts 312 112
23 Michigan 148 101
24 Minnesota 23 135
25 Mississippi 94 -78
26 Missouri 49 6
27 Montana -141 150
28 Nebraska -61 66
29 Nevada -257 56
30 New Hampshire 302 127
31 New Jersey 282 65
32 New Mexico -128 -43
33 New York 236 104
34 North Carolina 239 -22
35 North Dakota -44 158
36 Ohio 176 52
37 Oklahoma -8 -41
38 Oregon -278 138
39 Pennsylvania 238 72
40 Rhode Island 318 94
41 South Carolina 218 -51
42 South Dakota -44 109
43 Tennessee 131 -34
44 Texas -38 -106
45 Utah -189 34
46 Vermont 282 154
47 Virginia 234 12
48 Washington -257 193
49 West Virginia 200 20
50 Wisconsin 83 113
51 Wyoming -134 90

BIN
025/blank_states_img.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

52
025/main.py Normal file
View File

@ -0,0 +1,52 @@
from turtle import Turtle, Screen
import pandas as pd
FONT = ("Courier", 14, "normal")
screen = Screen()
screen.setup(725,491)
screen.bgpic('blank_states_img.gif')
screen.tracer(0)
data = pd.read_csv("50_states.csv")
# state, x, y
game_on = True
states_remaining = len(data)
found_states = []
while len(found_states) < 50:
guess = str(screen.textinput(f"{states_remaining} states to find", "Find a state:"))
if guess == "None":
missing_states = [ s for s in data.states if s not in found_states ]
output = pd.DataFrame(missing_states)
output.to_csv("missing_states.csv")
exit()
state = data[data.state == guess.title()]
# if the subset is not empty, it means the state is in the list
if len(state) > 0:
x_pos = state.x.item() #state.iloc[0]["x"]
y_pos = state.y.item() #state.iloc[0]["y"]
state_name = state.iloc[0]["state"]
if state_name in found_states:
continue
states_remaining -= 1
found_states.append(state_name)
text = Turtle()
text.pu()
text.color("black")
text.hideturtle()
text.goto(x_pos, y_pos)
text.write(state_name, align="center", font=FONT)
screen.update()
screen.mainloop()

48
025/missing_states.csv Normal file
View File

@ -0,0 +1,48 @@
Alabama
Alaska
Arkansas
California
Colorado
Connecticut
Delaware
Florida
Georgia
Hawaii
Idaho
Illinois
Indiana
Iowa
Kansas
Kentucky
Louisiana
Maine
Maryland
Massachusetts
Michigan
Minnesota
Mississippi
Missouri
Montana
Nebraska
Nevada
New Hampshire
New Jersey
New Mexico
New York
North Carolina
North Dakota
Oklahoma
Oregon
Pennsylvania
Rhode Island
South Carolina
South Dakota
Tennessee
Texas
Utah
Vermont
Virginia
Washington
West Virginia
Wisconsin
Wyoming
1 Alabama
2 Alaska
3 Arkansas
4 California
5 Colorado
6 Connecticut
7 Delaware
8 Florida
9 Georgia
10 Hawaii
11 Idaho
12 Illinois
13 Indiana
14 Iowa
15 Kansas
16 Kentucky
17 Louisiana
18 Maine
19 Maryland
20 Massachusetts
21 Michigan
22 Minnesota
23 Mississippi
24 Missouri
25 Montana
26 Nebraska
27 Nevada
28 New Hampshire
29 New Jersey
30 New Mexico
31 New York
32 North Carolina
33 North Dakota
34 Oklahoma
35 Oregon
36 Pennsylvania
37 Rhode Island
38 South Carolina
39 South Dakota
40 Tennessee
41 Texas
42 Utah
43 Vermont
44 Virginia
45 Washington
46 West Virginia
47 Wisconsin
48 Wyoming

3024
025/squirrels.csv Normal file

File diff suppressed because it is too large Load Diff

54
025/task.py Normal file
View File

@ -0,0 +1,54 @@
# data = []
# with open("weather_data.csv") as f:
# for line in f.readlines():
# data.append(line.strip().split(','))
# print(data)
# ------------------------------------------------------------------------
# import csv
# temperatures = []
# with open("weather_data.csv") as f:
# reader = csv.reader(f)
# next(reader)
# for row in reader:
# temperatures.append(int(row[1]))
# print(temperatures)
# ------------------------------------------------------------------------
# import pandas as pd
# data = pd.read_csv("weather_data.csv", delimiter=",")
# print(data["temp"].mean())
# print(data["temp"].max())
# output = data[data.temp == data.temp.max()]
# print(output)
# ------------------------------------------------------------------------
import pandas as pd
data = pd.read_csv("squirrels.csv")
colors = data["Primary Fur Color"].unique()
output_colors = []
output_count = []
for color in colors:
if type(color) != str:
continue
count = len(data[data["Primary Fur Color"] == color])
output_colors.append(color)
output_count.append(count)
output = {"color": output_colors, "count": output_count}
df = pd.DataFrame(output)
print(df.to_csv(index=False))

8
025/weather_data.csv Normal file
View File

@ -0,0 +1,8 @@
day,temp,condition
Monday,12,Sunny
Tuesday,14,Rain
Wednesday,15,Rain
Thursday,14,Cloudy
Friday,21,Sunny
Saturday,22,Sunny
Sunday,24,Sunny
1 day temp condition
2 Monday 12 Sunny
3 Tuesday 14 Rain
4 Wednesday 15 Rain
5 Thursday 14 Cloudy
6 Friday 21 Sunny
7 Saturday 22 Sunny
8 Sunday 24 Sunny

15
026/main.py Normal file
View File

@ -0,0 +1,15 @@
import pandas as pd
# Keyword Method with iterrows()
# {new_key:new_value for (index, row) in df.iterrows()}
#TODO 1. Create a dictionary in this format:
# {"A": "Alfa", "B": "Bravo"}
data = pd.read_csv("nato_phonetic_alphabet.csv")
dict = { row.letter:row.code for (index, row) in data.iterrows() }
#TODO 2. Create a list of the phonetic code words from a word that the user inputs.
input = list(input("Which word do you want to spell?\n"))
print([ dict[letter.upper()] for letter in input])

View File

@ -0,0 +1,27 @@
letter,code
A,Alfa
B,Bravo
C,Charlie
D,Delta
E,Echo
F,Foxtrot
G,Golf
H,Hotel
I,India
J,Juliet
K,Kilo
L,Lima
M,Mike
N,November
O,Oscar
P,Papa
Q,Quebec
R,Romeo
S,Sierra
T,Tango
U,Uniform
V,Victor
W,Whiskey
X,X-ray
Y,Yankee
Z,Zulu
1 letter code
2 A Alfa
3 B Bravo
4 C Charlie
5 D Delta
6 E Echo
7 F Foxtrot
8 G Golf
9 H Hotel
10 I India
11 J Juliet
12 K Kilo
13 L Lima
14 M Mike
15 N November
16 O Oscar
17 P Papa
18 Q Quebec
19 R Romeo
20 S Sierra
21 T Tango
22 U Uniform
23 V Victor
24 W Whiskey
25 X X-ray
26 Y Yankee
27 Z Zulu

5
026/task.py Normal file
View File

@ -0,0 +1,5 @@
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
new_numbers = [ n for n in numbers if n % 2 == 1 ]
print(new_numbers)