Skip to content

Instantly share code, notes, and snippets.

@matthewdeanmartin
Created April 3, 2021 16:08
Show Gist options
  • Select an option

  • Save matthewdeanmartin/5265d9dbee4e9cabbdfa2ad1c2224f04 to your computer and use it in GitHub Desktop.

Select an option

Save matthewdeanmartin/5265d9dbee4e9cabbdfa2ad1c2224f04 to your computer and use it in GitHub Desktop.
War card game as a coding kata
# remove the input (dependency injection here)
# prefer returns over prints (I'm violating that here)
# for each ~5 lines of code, break into functions
# start with good names
# start adding assertions and then unit tests to clean up the bugs (also violated here)
# until I do that last part, I'm not really sure if this really works.
import random
def games(input):
while True:
print("players turn up cards until they match (1 in 5), then flip coin to see who gets all turned up.")
game()
if input("play again?") != "y":
break
def one_to(limit):
return int(random.random()* limit + 1)
def game():
players = [{"name": "human",
"up": 0,
"deck":24,
"current_winner":False},
{"name": "computer",
"up":0,
"deck":24,
"current_winner":False}]
game_over = False
while not game_over:
# check for empty decks (redundant?)
for player in players:
if player["deck"] ==0:
print(player["name"] + " loses")
game_over = True
break
for player in players:
print(f"{player['name']} has {player['up']} up and {player['deck']} in the deck")
# handle drawing
for player in players:
# ignore that this could imply a deck with varying contents!
player["draw"] = one_to(5)
if player["deck"] >= 1:
player["up"] +=1
player["deck"] -= 1
else:
print(f"Player {player['name']} lost")
break
# handle war
if players[0]["draw"] == players[1]["draw"]:
handle_war(players)
else:
# no war
pass
def handle_war(players):
# war
print("War!")
pick_winner = one_to(len(players)) - 1
players[pick_winner]["current_winner"] = True
print(f"{players[pick_winner]['name']} won the war")
# gather loser cards
winner_gets = 0
# calc winnings & reset
for player in players:
winner_gets += player["up"]
player["up"] = 0
# find current player, give him winnings
for player in players:
if player["current_winner"]:
# winnings
player["deck"] += winner_gets
player["up"] = 0
# reset flag
for player in players:
player["current_winner"] = False
if __name__ == '__main__':
games(lambda x: "n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment