適合初學者練習流程控制、隨機數與使用者互動的兩款文字遊戲,改編自《Invent with Python》。程式碼兼容 Python 3。
import random, time
print('\n[--system--] one file is bad the other is good ..guess the right one.\n')
print('connecting....')
for _ in range(4):
time.sleep(1)
print('....')
print('\nconnection established')
def display_intro():
print('------------')
print('SYSTEM FILES')
print('------------\n')
print('1.) file.')
print('2.) file.\n')
def choose_option():
option = ''
while option not in ('1', '2'):
option = input('which file to download? 1 or 2\nuser> ')
return option
def check_option(chosen):
print('\ninitialising download....')
time.sleep(1)
print('accessing file....')
time.sleep(1)
print('downloading....')
for _ in range(3):
time.sleep(1)
print('....')
good = random.randint(1, 2)
if chosen == str(good):
print('\ndownload complete.\nGAME OVER')
else:
print('\nfile corrupt\nsystem infected.\nGAME OVER')
play = 'yes'
while play == 'yes':
display_intro()
opt = choose_option()
check_option(opt)
play = input('\ndownload again? (yes or no)\nuser> ')
import random, time
guesses = 0
print('\n[--system--] enter code in 15 trys to avoid lockout\n')
print('connecting....')
for _ in range(4):
time.sleep(1)
print('....')
print('connection established\n')
print('---------------------')
print(' MAINFRAME - LOGIN ')
print('---------------------\n')
print('enter 3 digit access code..')
code = random.randint(0, 999)
while guesses < 15:
guess = int(input('user> '))
guesses += 1
if guess < code:
print('\nACCESS - DENIED - code too low')
elif guess > code:
print('\nACCESS - DENIED - code too high')
else:
break
if guess == code:
print('\nverifying ....')
time.sleep(1)
print('authenticating ....')
time.sleep(1)
print('....')
time.sleep(1)
print('\nACCESS - GRANTED\nGAME OVER')
else:
print('\n....')
time.sleep(1)
print('\nSYSTEM LOCKED - the code was %d' % code)
random.randint 產生隨機數。time.sleep 增加戲劇張力。while 迴圈控制遊戲流程與重玩邏輯。int() 可能拋出例外,實務上需 try/except)。