I’m newbie. I’m trying to find out a solution to an exercise but i’m not so skilled and I made several attempts with no results.
I have to write sort of a game.
To start, the computer has to ask you to decide a number X. If the number is a multiple of 4 the user starts.
Otherwise the computer will.
Taking turn, computer and user subctract a number from 1 to 3 to “X” and get a value Z.
The one who wins the game subtracts the latest balls and lets with no balls to pick the other contestant (in this case the user).
I have to write everything in a fashion that the computer will get the wins, always.
Below, the code I have so far written.
Any hint?
x = int(input("how many marbles?")) if x%4==0: print("you start") y = int(input("subtract 1 or 2 or 3 marbles: ")) z=x-y print("there are ",z," marbles left") else: print("computer starts") if x==x+3: m=x-3 print("there are ",m," marbles left") if x==x+2: m=x-2 print("there are ",m," marbles left") if x==x+1: m=x-1 print("there are ",m," marbles left")
Answer
You would need to place the logic into a loop and implement a winning condition (given that you are somewhat cheating in deciding who starts, the computer will always win).
Also, your computer player should be checking for the modulo 4 of the number of remaining balls which you can verify using x%4 == 1
for example ( x == x+1
will never be True ). And, given that the computer will always play the modulo 4, you don’t need several conditions, you can just use it directly.
x = int(input("quante palline ci sono? ")) player = 'P' if x%4==0 else 'C' # player starts if multiple of 4 while x > 0: if player == 'P': print('tocca a te') # human player y = int(input("togli 1,2 o 3 palline: ")) # ask for balls x -= y # remove them player = 'C' # switch player else: m = x%4 # computer plays x MOD 4 print("il computer toglia",m) # tell the human player x -= m # remove balls player = 'P' # switch player print("sono rimaste",x,"palline") # report balls remaining print('il computer vince') # computer always wins
Sorry if my Italian isn’t great, only did 1 year of it 25 years ago
quante palline ci sono? 12 tocca a te togli 1,2 o 3 palline: 3 sono rimaste 9 palline il computer toglia 1 sono rimaste 8 palline tocca a te togli 1,2 o 3 palline: 3 sono rimaste 5 palline il computer toglia 1 sono rimaste 4 palline tocca a te togli 1,2 o 3 palline: 1 sono rimaste 3 palline il computer toglia 3 sono rimaste 0 palline il computer vince