In: Computer Science
Q3. Write a program that simulates the 4-digit lock of the suitcase. You need to represent each rotatable cyllinder with some variable, it's value is going to reflect what state your lock is in. Digits are going to be 0 through 9. If 9 rotates further, it gets back to 0. If 0 rotates back, it becomes 9, just like in real suitcase locks.
Then, pick a combination that opens your suitcase, like:
1-9-9-5
And pick a random starting combination.
Write functions to allow you to change 1 digit at a time. After each change, you should check whether all 4 digits match the opening combo. If they do, show the last state and stop program, if they do not, just display the state of your lock and allow user to keep rotating.
Code in Python:-
import random
def lock():
a,b,c,d = 1,9,9,5
i = random.randint(0,9)
j = random.randint(0,9)
k = random.randint(0,9)
l = random.randint(0,9)
print('RULES:-----')
print(' 1). Enter the value of place (between -1 to -4 or 1 to 4 inclusive) to change the integer at that place by 1 ')
print(' 2). positive integer is for forward rotation i.e 9 to 0')
print(' 3). negative integer is for backward rotation i.e 0 to 9')
print('\n')
if input('Want to play this game?(y/n)') == 'y':
print("Initial Lock Configuration---> ",i,j,k,l)
while True:
input_choice = int(input('Enter the place of key you want to rotate:- '))
if abs(input_choice) == 1:
if abs(input_choice) == input_choice:
i = (i+1)%10
else:
i = (i-1+10)%10 # +10 to check for negative cases
elif abs(input_choice) == 2:
if abs(input_choice) == input_choice:
j = (j+1)%10
else:
j = (j-1+10)%10
elif abs(input_choice) == 3:
if abs(input_choice) == input_choice:
k = (k+1)%10
else:
k = (k-1+10)%10
elif abs(input_choice) == 4:
if abs(input_choice) == input_choice:
l = (l+1)%10
else:
l = (l-1+10)%10
else:
print('Invalid key ! Enter number between -1 to -4 or 1 to 4')
if (a == i and b == j and c == k and d == l):
print('-----------------LOCK Open ------------> KEY = ',a,b,c,d)
break
else:
print('LOCKED! Try again--->',i,j,k,l)
else:
print('Will play next time')
lock()
Output:-
Snapshot of the code:-