首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 文字冒險遊戲範例:猜檔案與猜數字兩款經典小遊戲

     編輯:更多程式設計知識

適合初學者練習流程控制、隨機數與使用者互動的兩款文字遊戲,改編自《Invent with Python》。程式碼兼容 Python 3。

遊戲一:系統檔案下載(Dragon Realm 改編)


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> ')

遊戲二:三位數存取碼(Guess the Number 改編)


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)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved