MAINT: Add type annotations / use functions

This commit is contained in:
Martin Thoma
2022-03-07 22:00:41 +01:00
parent 528df5215e
commit 8cf8bab742
5 changed files with 240 additions and 198 deletions

4
01_Acey_Ducey/python/acey_ducey.py Normal file → Executable file
View File

@@ -23,7 +23,7 @@ cards = {
}
def play_game():
def play_game() -> None:
"""Play the game"""
cash = 100
while cash > 0:
@@ -63,7 +63,7 @@ def play_game():
print("Sorry, friend, but you blew your wad")
def main():
def main() -> None:
"""Main"""
keep_playing = True

View File

@@ -11,41 +11,43 @@
#
######################################################
from typing import List
class Card:
def __init__(self, suit, rank):
def __init__(self, suit: str, rank: int):
self.suit = suit
self.rank = rank
def __str__(self):
r = self.rank
if r == 11:
def __str__(self) -> str:
r = str(self.rank)
if r == "11":
r = "J"
elif r == 12:
elif r == "12":
r = "Q"
elif r == 13:
elif r == "13":
r = "K"
elif r == 14:
elif r == "14":
r = "A"
return f"{r}{self.suit}"
class Deck:
def __init__(self):
self.cards = []
self.cards: List[Card] = []
self.build()
def build(self):
def build(self) -> None:
for suit in ["\u2665", "\u2666", "\u2663", "\u2660"]:
for rank in range(2, 15):
self.cards.append(Card(suit, rank))
def shuffle(self):
def shuffle(self) -> None:
import random
random.shuffle(self.cards)
def deal(self):
def deal(self) -> Card:
return self.cards.pop()
@@ -58,7 +60,7 @@ class Game:
self.money = 100
self.not_done = True
def play(self):
def play(self) -> None:
while self.not_done:
while self.money > 0:
card_a = self.card_a
@@ -90,9 +92,9 @@ class Game:
print("Chicken!")
print(f"Your deal should have been: {player_card}")
if card_a.rank < player_card.rank < card_b.rank:
print(f"You could have won!")
print("You could have won!")
else:
print(f"You would lose, so it was wise of you to chicken out!")
print("You would lose, so it was wise of you to chicken out!")
self.not_done = False
break

View File

@@ -30,13 +30,13 @@ import random
# to start with more or less than $100."
DEFAULT_BANKROLL = 100
# functions
def deal_card_num():
def deal_card_num() -> int:
"""Get card number"""
return random.randint(0, 12)
def get_card_name(number):
def get_card_name(number: int) -> str:
"""Get card name"""
card_names = (
" 2",
@@ -56,7 +56,7 @@ def get_card_name(number):
return card_names[number]
def display_bankroll(bank_roll):
def display_bankroll(bank_roll: int) -> None:
"""Print current bankroll"""
if BANK_ROLL > 0:
print("You now have %s dollars\n" % bank_roll)
@@ -103,9 +103,9 @@ while KEEP_PLAYING:
# Get and handle player bet choice
BET_IS_VALID = False
while not BET_IS_VALID:
curr_bet = input("What is your bet? ")
curr_bet_str = input("What is your bet? ")
try:
curr_bet = int(curr_bet)
curr_bet = int(curr_bet_str)
except ValueError:
# Bad input? Just loop back up and ask again...
pass