Day 047 - Project 47 : Top Trumps

If you have any questions, comments or issues with this project please post them here!

since this isn’t in the solution and nobody has posted here yet, i decided to post my attempt that includes the option to add more cards. it works, but is probably much more convoluted than necessary. my decision to add an “id” key probably didn’t help much either, but that’s what i came up with at the time.

import random,os,time

Trumps={  
  "Admiral Halsey":{"Verbality":70,"Calculussity":31,"Shaperotaterness":17,"id":1},
  "Vice Admiral Beatty":{"Verbality":45,"Calculussity":31,"Shaperotaterness":18,"id":2}
}

def Cardid(i):
  for key, value in Trumps.items():
    if Trumps[key]["id"]==i:
      return key,Trumps[key]

def ran(i):
  num=random.randint(1,len(Trumps))
  while num==i:
    num=random.randint(1,len(Trumps))
  return num
    
def battle(AllStats1,AllStats2,Stat1):
  if AllStats1[1][Stat1]>AllStats2[1][Stat1]:
    print(f"\n{AllStats1[0]}'s {Stat1} of {AllStats1[1][Stat1]} beats {AllStats2[0]}'s {Stat1} of {AllStats2[1][Stat1]}!")
  elif AllStats1[1][Stat1]<AllStats2[1][Stat1]:
    print(f"\n{AllStats1[0]}'s {Stat1} of {AllStats1[1][Stat1]} loses to {AllStats2[0]}'s {Stat1} of {AllStats2[1][Stat1]}!")
  else:
    print("\nIt's a draw!")
  cont=input("\nContinue y/n? > ").strip().lower()
  if cont[0]=="y":
    os.system("clear")
    return
  else:
    exit()

def AddCard():
  name=input("\nName your card > ")
  verb=int(input("Enter a Verbality score > "))
  calc=int(input("Enter a Calculussity score > "))
  shape=int(input("Enter a Shaperotaterness score > "))
  id=len(list(Trumps))+1

  Trumps[name]={"Verbality":verb,"Calculussity":calc,"Shaperotaterness":shape,"id":id}
  print(f"\n{name} has been added.")
  time.sleep(2)
  os.system("clear")
  return

while True:
  print("=Random Character Battle=\nChoose or add your character > \n")
  print("0 - add character")
  for key,value in Trumps.items():
    print(f"{Trumps[key]['id']} - {key}")

  Card1=int(input("> "))
  if Card1==0:
    AddCard()
  else:
    Card2=ran(Card1)
  
    AllStats1={}
    AllStats2={}  
    AllStats1=Cardid(Card1)
    AllStats2=Cardid(Card2)
    
    print("\nChoose your stat:\n")
    Stat1=int(input("1 - Verbality\n2 - Calculussity\n3 - Shaperotaterness\n > "))
    if Stat1==1:
      Stat1="Verbality"
    elif Stat1==2:
      Stat1="Calculussity"
    elif Stat1==3:
      Stat1="Shaperotaterness"      
    
    battle(AllStats1,AllStats2,Stat1)

comments appreciated!

It’s hard to recognize it from the code :rofl: but it seems i’m really into random :upside_down_face: !

# -*- coding: utf-8 -*-
"""
Created on Thu Feb  2 15:50:14 2023

@author: soreen
"""
import random, time

trumps = {}

def numR():
    for i in range(100):
        num = random.randint(1,100)
        return num

def coloR():
    col = ['\033[35m','\033[34m','\033[32m','\033[33m','\033[31m','\033[1m']
    colR = random.choice(col)
    return colR
    
trumps["Allah"] = {"Intelligence": numR(), "Speed": numR(), "HP": numR(), "Weight": numR()}
trumps["Jesus"] = {"Intelligence": numR(), "Speed": numR(), "HP": numR(), "Weight": numR()}
trumps["Budha"] = {"Intelligence": numR(), "Speed": numR(), "HP": numR(), "Weight": numR()}
trumps["Hera"] = {"Intelligence": numR(), "Speed": numR(), "HP": numR(), "Weight": numR()}
trumps["Zeus"] = {"Intelligence": numR(), "Speed": numR(), "HP": numR(), "Weight": numR()}
trumps["Trump"] = {"Intelligence": numR(), "Speed": numR(), "HP": numR(), "Weight": numR()}
trumps["Putin"] = {"Intelligence": numR(), "Speed": numR(), "HP": numR(), "Weight": numR()}
trumps["Xi"] = {"Intelligence": numR(), "Speed": numR(), "HP": numR(), "Weight": numR()}

print()

start_string = "Let's GO!\n\n"

while True:
#    for i in start_string.upper():
#        print(i, end="")
    print("And the fighters are: \n\n")    
    for key in trumps:
        print(coloR(),key)
    user = input("\033[0m\nChoose your fighter: ").capitalize()
    
    comp = random.choice(list(trumps.keys()))
    print("\nYour computer is choosing hero: ")
    for i in range(20):
        print(".", end="")
        time.sleep(0.15)
    time.sleep(0.2)
    print(f"\nYour computer has picked {coloR()}{comp}\033[0m! 👹 ...")
    print()
    for i in start_string.upper():
        print(i, end="")
    
    print("Choose stats to compare: Intelligence, Speed, HP or Weight")
    answer = input("\n> ").capitalize()
    
    print(f"{user}: {trumps[user][answer]}")
    print(f"{comp}: {trumps[comp][answer]}")
    
    if trumps[user][answer] > trumps[comp][answer]:
        print(f"{coloR()}{user} \033[0mWins")
    elif trumps[user][answer] < trumps[comp][answer]:
        print(f"{coloR()}{comp} \033[0mWins")
    else:
        print("It's a draw!")

Please note: i’m sort of TheGrandfather in coding (age=51) so i might be a bit politically incorrect! No dissent intended - it’s just for fun!

4 Likes

I really liked the made up stat names :)))

what is the meaning of the word TRUMP?

Hey @WaayeelkaCraxma welcome to the forums!

I think its the name of a game played in the UK.

1 Like

‘Trump’ is a word used in card games when you win due to a better ranking card. That would be your ‘Trump Card’

Fun Fact:
In Germany there is a saying: “Heart is Trump.” It means, Heart beats all other cards, but it also applies to Real Life! :wink:

2 Likes

You aren’t alone sir! Random makes certain decisions so much easier lol lovely coding!

I feel like my code is pretty helpful. I struggled a lot with this one! I think I also fixed some bugs in the solution (like inputting invalid names, and stats, as well as ensuring the computer does not pick the same character as me. ). The output is not very pretty though lol. If anyone has any suggestions to make it a bit nicer on the terminal and overall easier on the eyes I would love to hear it! I am also not really sure how the block quote works!

import random,time, os

trump = {}

trump["Goku"] = {"Intelligence": 50, "Strength": 95, "Speed": 94, "Versatility": 92}
trump["Vegeta"]= {"Intelligence": 90, "Strength": 94, "Speed": 93, "Versatility": 98}
trump["Gohan"] = {"Intelligence": 98, "Strength": 94, "Speed": 98, "Versatility": 88}
trump["Piccolo"] = {"Intelligence": 99, "Strength": 91, "Speed": 92, "Versatility": 99}

while True:
  for key in trump:
    print (key)
  user = input ("Player 1 Name your Character > ").strip().title()
  if user not in trump:
    print ("Not an option")
    time.sleep(1)
    os.system('clear')
    continue
  characters_available = list(trump.keys())
  characters_available.remove(user)
  computer = random.choice(characters_available)
  print (f'Computer has picked {computer}')
  time.sleep(1)
  os.system('clear')
  while True:
    print ("Pick your Stat > Intelligence, Strength, Speed, Versatility")
    stat = input ('Choose your stat > ').strip().title()
    if stat not in trump[key]:
      print ('Not an option')
      time.sleep(1)
      os.system('clear')
    else:
      break

  print (f"{user}: {trump[user][stat]}")
  print (f"{computer}: {trump[computer][stat]}")

  if trump[user][stat]>trump[computer][stat]:
    print(user, "wins!")
    time.sleep(2)
    os.system('clear')
  elif trump[computer][stat]>trump[user][stat]:
    print(computer, "wins!")
    time.sleep(2)
    os.system('clear')
  else:
    print ("It is a draw!")
    time.sleep(2)
    os.system('clear')

Please explain this code to me

import os, time, random
trumps = {}
trumps["David"] = {"Intelligence": 178, "Speed": 4, "Guile": 80, "Baldness Level": 99}
trumps["Mr Spock"] = {"Intelligence": 200, "Speed": 50, "Guile": 50, "Baldness Level": 0}
trumps["Moica from Friends"] = {"Intelligence": 150, "Speed": 50, "Guile": 50, "Baldness Level": 0}
trumps["Professor X"] = {"Intelligence": 250, "Speed": 1, "Guile": 200, "Baldness Level": 101}
while True:
  print("TOP TRUMPS")
  print()
  print("Characters")
  print()
  for key in trumps:
    print(key)
  user = input("Pick your character\n> ")
  comp = random.choice(list(trumps.keys()))
  print("Computer has picked", comp)
  print("Choose your stat: Intelligence, Speed, Guile & Baldness Level")
  answer = input("> ")
  print(f"{user}: {trumps[user][answer]}")
  print(f"{comp}: {trumps[comp][answer]}")
  if trumps[user][answer] > trumps[comp][answer]:
    print(user, "wins")
  elif trumps[user][answer] < trumps[comp][answer]:
    print(comp, "wins")
  else:
    print("Draw")
  time.sleep(2)
  os.system("clear")

This code is a simple implementation of the game “Top Trumps” using a dictionary in Python. Here’s a breakdown of how the code works:

  1. Importing Modules: The code begins by importing the necessary modules: os, time, and random. These modules provide functionalities for clearing the console, adding delays, and generating random choices, respectively.
  2. Dictionary Initialization: The code creates a dictionary named trumps to store information about different characters. Each character is represented as a key in the dictionary, and the corresponding value is another dictionary containing attributes such as “Intelligence,” “Speed,” “Guile,” and “Baldness Level.” The values associated with these attributes represent the character’s level or score for each attribute.
  3. Game Loop: The code enters an infinite loop using while True:. This loop allows the game to continue until it is manually interrupted.
  4. Printing Character List: Inside the loop, the code prints the header “TOP TRUMPS” and displays the list of available characters from the trumps dictionary.
  5. User Input: The code prompts the user to pick a character by inputting the character’s name.
  6. Computer Selection: The code randomly chooses a character from the trumps dictionary as the computer’s selection.
  7. Attribute Selection: The code prompts the user to choose an attribute (“Intelligence,” “Speed,” “Guile,” or “Baldness Level”) to compare between the user’s and computer’s characters.
  8. Attribute Comparison: The code retrieves the attribute values for the user’s and computer’s characters from the trumps dictionary and compares them. If the user’s value is higher, the user wins. If the computer’s value is higher, the computer wins. Otherwise, it’s a draw.
  9. Printing Results: The code prints the attribute values for both the user’s and computer’s characters, as well as the result of the comparison.
  10. Delay and Clearing Console: The code adds a delay of 2 seconds using time.sleep(2) to allow the user to see the result. Then it clears the console using os.system("clear") (assuming the code is run on a Unix-based system) to prepare for the next round.

The loop continues, and the game repeats until it is manually interrupted.

print(f”{user}: {trumps[user][answer]}”)
print(f"{comp}: {trumps[comp][answer]}")
if trumps[user][answer] > trumps[comp][answer]:
print(user, “wins”)
elif trumps[user][answer] < trumps[comp][answer]:
print(comp, “wins”)

Can you also explain about this part

print(f"{user}: {trumps[user][answer]}")
print(f"{comp}: {trumps[comp][answer]}")

These lines of code are responsible for printing the selected character’s value for the chosen stat. It uses f-strings (formatted strings) to concatenate the values of user , comp , answer , and the corresponding values from the trumps dictionary. For example, if the user chose “David” as the character and “Intelligence” as the stat, it would print “David: 178” as the output.

if trumps[user][answer] > trumps[comp][answer]:
    print(user, "wins")
elif trumps[user][answer] < trumps[comp][answer]:
    print(comp, "wins")
else:
    print("Draw")

These lines of code determine the winner of the comparison based on the selected stat. It compares the values from the trumps dictionary for the selected stat between the user’s character (user) and the computer’s character (comp).

  • If the user’s value is greater than the computer’s value, it prints “{user} wins” where {user} is the name of the user’s character.
  • If the user’s value is less than the computer’s value, it prints “{comp} wins” where {comp} is the name of the computer’s character.
  • If the values are equal, it prints “Draw” indicating that the comparison resulted in a tie.

Overall, these lines of code compare the selected stat values of the user’s character and the computer’s character and print the corresponding winner or draw result.

1 Like

I’ve been going through these, and Day 47’s project was challenging!

I really want to understand how to do this, so I spent time over 2 or 3 days working on Day 47.

Ultimately, I ended up asking ChatGPT to help me troubleshoot some aspects, and also to clarify when I didn’t understand something. Sometimes my code didn’t work merely because I used " double quotes " inside a print function, instead of ’ single quotes ’ —ChatGPT helped me figure out that problem real fast, and I’m sure I won’t forget for a while. :stuck_out_tongue:

Here’s my really odd Tops Trumps script.

Users can add as many new items as they want, and then play against the computer.
They can either select their own card, or have it randomly selected.

import random, os, time

trumps = {}

trumps = {"ice cream":{"intelligence":10,"taste":11,"sleepiness":2}, 
          "dogs":{"intelligence":3,"taste":2,"sleepiness":8},
          "bbq":{"intelligence":1,"taste":8,"sleepiness":7}
         }

trumps["bananas"]={"intelligence":6,"taste":7,"sleepiness":1}

def prettyPrint(player, stats):
  print(f"\033[35m{player.capitalize()}")
  print("\033[0m")
  time.sleep(1)

def userSelect():
  p1=None
  p2=None
  userChoice=input("1. Select your own item?\n2. Randomly be assigned an item.\n > ")
  if userChoice=="1":
    print()
    print("Your options:\n")
    print(list(trumps))
    print()
    p1=input("type your choice\n > \033[36m")
    print("\033[0m")
    
    while p1 not in trumps:
      p1=input("Not a valid option.\nType your choice.\n > \033[36m")
      print("\033[0m")

    p1_stats=trumps[p1]
    time.sleep(1)
    os.system('clear')
    print("Player 1: ",end="")
    prettyPrint(p1, p1_stats)
    
  else:
    p1=random.choice(list(trumps))
    p1_stats=trumps[p1]
    
    time.sleep(1)
    os.system('clear')
    print("Player 1: ",end="")
    prettyPrint(p1,p1_stats)   
    
  p2=random.choice(list(trumps))
  p2_stats=trumps[p2]
  
  while p1==p2:
    p2=random.choice(list(trumps))
    p2_stats=trumps[p2]

  print("Computer is randomly selected.")
  time.sleep(1)
  print()
  time.sleep(1)
  os.system('clear')
  print("Computer: ",end="")
  prettyPrint(p2,p2_stats)
  return p1, p1_stats, p2, p2_stats
  
def addNewBattleItem():
  name=input("pick the thing > ").strip().lower()
  intel=int(input("intelligence > "))
  taste=int(input("pick the taste number > "))
  sleep=int(input("rate sleepiness > "))

  return name,intel,taste,sleep

def battle(p1, p1_stats, p2, p2_stats):
  #user select stat to battle
  time.sleep(1)
  os.system("clear")
  print(f"\033[35m{p1.capitalize()} \033[31mvs \033[35m{p2.capitalize()}")
  time.sleep(1)
  print()
  print("\033[33mSelect your stat to battle:\033[0m\n1. intelligence\n2. taste\n3. sleepiness\n(type, 1, 2, or 3)\n")
  battleStat=input("> \033[32m")
  print("\033[0m")
  if battleStat=="1":
    #intelligence
    if p1_stats['intelligence']>p2_stats['intelligence']:
      print(f"{p1}'s {p1_stats['intelligence']} beats {p2}'s {p2_stats['intelligence']}.\n\n{p1.upper()} wins")
    elif p1_stats['intelligence']<p2_stats['intelligence']:
      print(f"{p2}'s {p2_stats['intelligence']} beats {p1}'s {p1_stats['intelligence']}.\n\n{p2.upper()} wins")
    else:
      print("Draw.")
  if battleStat=="2":
    #taste
    if p1_stats['taste']>p2_stats['taste']:
      print(f"{p1}'s {p1_stats['taste']} beats {p2}'s {p2_stats['taste']}.\n\n{p1.upper()} wins")
    elif p1_stats['taste']<p2_stats['taste']:
      print(f"{p2}'s {p2_stats['taste']} beats {p1}'s {p1_stats['taste']}.\n\n{p2.upper()} wins")
    else:
      print("Draw.")
  if battleStat=="3":
    #sleepiness
        #taste
    if p1_stats['sleepiness']>p2_stats['sleepiness']:
      print(f"{p1}'s {p1_stats['sleepiness']} beats {p2}'s {p2_stats['sleepiness']}.]n\n{p1.upper()} wins")
    elif p1_stats['sleepiness']<p2_stats['sleepiness']:
      print(f"{p2}'s {p2_stats['sleepiness']} beats {p1}'s {p1_stats['sleepiness']}.\n\n{p2.upper()} wins")
    else:
      print("Draw.")
  
while True:
  print()
  print("...loading")
  time.sleep(2)
  os.system("clear")
  print("\033[36mTops Trumps Item Battler")
  time.sleep(1)
  print()
  menu=input("\033[0m1. Play\n2. Add new thing\n(type 1 or 2)\n\n> \033[32m")
  print("\033[0m")
  time.sleep(1)
  os.system("clear")
  if menu=="1":
    print()
    p1, p1_stats, p2, p2_stats=userSelect()
    time.sleep(3)
    os.system("clear")
    battle(p1, p1_stats, p2, p2_stats)
  if menu=="2":
    print()
    name, intel, taste, sleep = addNewBattleItem()
    trumps[name]={"intelligence":intel,"taste":taste,"sleepiness":sleep}
1 Like

Both should work, though?

1 Like

Take this code for instance:

print(f"{p1}'s {p1_stats['intelligence']} beats {p2}'s {p2_stats['intelligence']}.\n\n{p1.upper()} wins")

That works, but what doesn’t work is putting intelligence in double quotes.

print(f"{p1}'s {p1_stats["intelligence"]} beats {p2}'s {p2_stats["intelligence"]}.\n\n{p1.upper()} wins")

The above code doesn’t work because it’s already inside the double quotes of the print(f"...") function. I had to use the single quotes so I stopped confusing my print function! :stuck_out_tongue:

well explained thank you

If anyone wants to see the code that does everything (adding new cards and both playing versus the computer or another player) or wants to try Brooklyn 99 Top Trumps, here’s mine

https://replit.com/@annabelgangster/Top-Trumps-Brooklyn-99-47100

This is my very British attempt at Top Trumps!

https://replit.com/@MichaelDaburn/day47100

A quick edit to the def topTrumps(): to add a while True: for incorrect entries and shortened the card selection process.

2 Likes

The reason for alternating between single and double quotes is to avoid confusion for the interpreter. You have to enclose the keys as 'intelligence'. This helps the interpreter recognize where the string starts and ends without becoming confused by the inner quotes.

1 Like