Python 提供豐富的模組,方便開發各種應用程式。本文示範如何使用 Python 建立網頁自動開啟工具和終端機版的猜字遊戲。網頁自動開啟工具可以設定使用者最愛的網址,並定時開啟瀏覽器導航到這些網址,提醒使用者休息。猜字遊戲則是一個經典的終端機遊戲,玩家需要猜測一個單字,程式會根據玩家的猜測提供反饋。兩個程式都使用了 Python 的核心模組,例如 timewebbrowserjsonrandom,展現了 Python 在不同應用場景下的實用性。

自動化休息提醒系統

系統功能

  1. 設定最愛網址:允許使用者設定和取得最愛的網址。
  2. 計時器:可以測量2小時的時間間隔。
  3. 開啟瀏覽器:在設定的時間間隔後,自動開啟瀏覽器並導航到其中一個設定的網址。
  4. 迴圈提醒:系統會持續迴圈執行以上步驟,提供定期的休息提醒。

實作方法

  • 設定最愛網址:使用Python的json模組來儲存和讀取使用者的最愛網址。
  • 計時器:利用Python的time模組來實作計時功能。
  • 開啟瀏覽器:使用Python的webbrowser模組來開啟瀏覽器並導航到指定的網址。

程式碼實作

import time
import webbrowser
import json

def get_favorite_urls():
    # 從json檔案中讀取最愛網址
    with open('favorite_urls.json', 'r') as f:
        return json.load(f)

def set_favorite_urls(urls):
    # 將最愛網址寫入json檔案
    with open('favorite_urls.json', 'w') as f:
        json.dump(urls, f)

def open_browser(url):
    # 開啟瀏覽器並導航到指定的網址
    webbrowser.open(url)

def main():
    # 設定最愛網址
    favorite_urls = get_favorite_urls()
    
    # 計時器
    while True:
        time.sleep(2 * 60 * 60)  # 2小時
        # 從最愛網址中隨機選擇一個
        url = random.choice(favorite_urls)
        open_browser(url)

if __name__ == '__main__':
    main()

終端機版Hangman遊戲

遊戲描述

Hangman是一個簡單的字謎遊戲,玩家需要猜測一個單字,系統會根據玩家的猜測提供反饋,直到玩家正確猜出單字或錯誤次數達到一定限制。

遊戲實作

import random

def hangman():
    # 從words.json中隨機選擇一個單字
    with open('words.json', 'r') as f:
        words = json.load(f)
        word = random.choice(words)
    
    # 初始化猜測結果
    guessed = ['_'] * len(word)
    tries = 6
    
    print("Let's play Hangman!")
    
    while tries > 0 and '_' in guessed:
        # 顯示目前的猜測結果
        print(' '.join(guessed))
        
        # 玩家猜測
        guess = input("Guess a letter: ").upper()
        
        # 檢查猜測結果
        if guess in word:
            # 更新猜測結果
            for i, letter in enumerate(word):
                if letter == guess:
                    guessed[i] = guess
        else:
            # 減少剩餘嘗試次數
            tries -= 1
            print(f"Incorrect! You have {tries} tries left.")
    
    # 遊戲結束
    if '_' not in guessed:
        print(' '.join(guessed))
        print("Congratulations! You won!")
    else:
        print(f"Game over! The word was {word}.")

if __name__ == '__main__':
    hangman()

遊戲執行

  1. 執行hangman.py指令碼。 2.開始猜測單字。

基礎的Hangman遊戲實作

Hangman是一種經典的文字遊戲,玩家需要猜測一個未知的單詞,每次猜測一個字母,如果字母出現在單詞中,則填入相應的位置,如果字母不在單詞中,則繪製一個部分的繩索人。以下是基礎的Hangman遊戲實作:

遊戲初始化

import json
import random

def get_word():
    with open('words.json') as json_file:
        data = json.load(json_file)
    word_array = data["word_list"]
    word = random.choice(word_array)
    word = word.upper()
    return word

遊戲主函式

def play(word):
    word_completion = ["_"] * len(word)
    guessed = False
    guessed_letters = []
    guessed_words = []
    tries = 6

    print("Let's play Hangman!")
    print(display_hangman(tries))
    print(" ".join(word_completion))

繪製繩索人

def display_hangman(tries):
    stages = [  # final state: head, torso, both arms, and both legs
                """
                   --------
                   |      |
                   |      O
                   |     \\|/
                   |      |
                   |     / \\
                   -
                """,
                # head, torso, both arms, and one leg
                """
                   --------
                   |      |
                   |      O
                   |     \\|/
                   |      |
                   |     / 
                   -
                """,
                # head, torso, and both arms
                """
                   --------
                   |      |
                   |      O
                   |     \\|/
                   |      |
                   |      
                   -
                """,
                # head, torso, and one arm
                """
                   --------
                   |      |
                   |      O
                   |     \\|
                   |      |
                   |     
                   -
                """,
                # head and torso
                """
                   --------
                   |      |
                   |      O
                   |      |
                   |      |
                   |     
                   -
                """,
                # head
                """
                   --------
                   |      |
                   |      O
                   |    
                   |      
                   |     
                   -
                """,
                # initial empty state
                """
                   --------
                   |      |
                   |      
                   |    
                   |      
                   |     
                   -
                """
    ]
    return stages[tries]

遊戲迴圈

while not guessed and tries > 0:
    guess = input("請輸入一個字母或單詞:").upper()
    if len(guess) == 1 and guess.isalpha():
        if guess in guessed_letters:
            print("你已經猜過這個字母了。")
        elif guess not in word:
            print("這個字母不在單詞中。")
            tries -= 1
            guessed_letters.append(guess)
        else:
            print("這個字母在單詞中!")
            guessed_letters.append(guess)
            word_as_list = list(word)
            indices = [i for i, letter in enumerate(word_as_list) if letter == guess]
            for index in indices:
                word_completion[index] = guess
    elif len(guess) == len(word) and guess.isalpha():
        if guess in guessed_words:
            print("你已經猜過這個單詞了。")
        elif guess != word:
            print("這個單詞不正確。")
            tries -= 1
            guessed_words.append(guess)
        else:
            guessed = True
            word_completion = list(guess)
    else:
        print("請輸入一個有效的字母或單詞。")
    print(display_hangman(tries))
    print(" ".join(word_completion))

遊戲結束

if guessed:
    print("恭喜你!你猜到了單詞。")
else:
    print("抱歉,你沒有猜到單詞。單詞是 " + word)

完整程式碼

import json
import random

def get_word():
    with open('words.json') as json_file:
        data = json.load(json_file)
    word_array = data["word_list"]
    word = random.choice(word_array)
    word = word.upper()
    return word

def display_hangman(tries):
    stages = [  # final state: head, torso, both arms, and both legs
                """
                   --------
                   |      |
                   |      O
                   |     \\|/
                   |      |
                   |     / \\
                   -
                """,
                # head, torso, both arms, and one leg
                """
                   --------
                   |      |
                   |      O
                   |     \\|/
                   |      |
                   |     / 
                   -
                """,
                # head, torso, and both arms
                """
                   --------
                   |      |
                   |      O
                   |     \\|/
                   |      |
                   |      
                   -
                """,
                # head, torso, and one arm
                """
                   --------
                   |      |
                   |      O
                   |     \\|
                   |      |
                   |     
                   -
                """,
                # head and torso
                """
                   --------
                   |      |
                   |      O
                   |      |
                   |      |
                   |     
                   -
                """,
                # head
                """
                   --------
                   |      |
                   |      O
                   |    
                   |      
                   |     
                   -
                """,
                # initial empty state
                """
                   --------
                   |      |
                   |      
                   |    
                   |      
                   |     
                   -
                """
    ]
    return stages[tries]

def play(word):
    word_completion = ["_"] * len(word)
    guessed = False
    guessed_letters = []
    guessed_words = []
    tries = 6

    print("Let's play Hangman!")
    print(display_hangman(tries))
    print(" ".join(word_completion))

    while not guessed and tries > 0:
        guess = input("請輸入一個字母或單詞:").upper()
        if len(guess) == 1 and guess.isalpha():
            if guess in guessed_letters:
                print("你已經猜過這個字母了。")
            elif guess not in word:
                print("這個字母不在單詞中。")
                tries -= 1
                guessed_letters.append(guess)
            else:
                print("這個字母在單詞中!")
                guessed_letters.append(guess)
                word_as_list = list(word)
                indices = [i for i, letter in enumerate(word_as_list) if letter == guess]
                for index in indices:
                    word_completion[index] = guess
        elif len(guess) == len(word) and guess.isalpha():
            if guess in guessed_words:
                print("你已經猜過這個單詞了。")
            elif guess != word:
                print("這個單詞不正確。")
                tries -= 1
                guessed_words.append(guess)
            else:
                guessed = True
                word_completion = list(guess)
        else:
            print("請輸入一個有效的字母或單詞。")
        print(display_hangman(tries))
        print(" ".join(word_completion))

    if guessed:
        print("恭喜你!你猜到了單詞。")
    else:
        print("抱歉,你沒有猜到單詞。單詞是 " + word)

word = get_word()
play(word)

執行結果

Let's play Hangman!
 --------
|      |
|      
|    
|      
|     
-
_ _ _ _ _ _

請輸入一個字母或單詞:

遊戲開發:猜字遊戲

遊戲流程

猜字遊戲是一種簡單而有趣的文字遊戲,玩家需要猜測一個未知的單字。以下是遊戲的基本流程:

  1. 初始化:遊戲開始時,系統會隨機選擇一個單字,並將其存放在 word 變數中。
  2. 顯示單字長度:系統會顯示單字的長度,讓玩家知道需要猜測的單字有多少個字母。
  3. 猜測迴圈:玩家可以不斷地猜測單字,直到猜對或用盡所有猜測機會(tries)。

程式碼實作

以下是猜字遊戲的部分程式碼實作:

print(word_completion)

print("\n")

print("Length of the word: ", len(word))
print("\n")

while not guessed and tries > 0:
    guess = input("Please guess a letter or the word: ").upper()

    if len(guess) == 1 and guess.isalpha():
        if guess in guessed_letters:
            print("You already guessed the letter", guess)
        elif guess not in word:
            print(guess, "is not in the word.")
            tries -= 1
            guessed_letters.append(guess)
        else:
            # 將正確猜到的字母加入到 guessed_letters 清單中
            guessed_letters.append(guess)
            # 更新 word_completion,以反映正確猜到的字母
            word_completion = [letter if letter == guess else "_" for letter in word]
            print(" ".join(word_completion))
    else:
        print("Invalid input. Please enter a single letter or the word.")

遊戲邏輯

在遊戲迴圈中,系統會不斷地詢問玩家猜測一個字母或整個單字。玩家輸入的內容會被轉換為大寫,以便與單字進行比較。

  • 如果玩家猜測的字母已經在 guessed_letters 清單中,系統會顯示一個訊息,提醒玩家已經猜過這個字母。
  • 如果玩家猜測的字母不在單字中,系統會顯示一個訊息,提醒玩家這個字母不在單字中,並將 tries 數量減 1。
  • 如果玩家猜測的字母在單字中,系統會將這個字母加入到 guessed_letters 清單中,並更新 word_completion,以反映正確猜到的字母。

圖表翻譯

以下是遊戲流程的 Mermaid 圖表:

  flowchart TD
    A[遊戲開始] --> B[初始化單字]
    B --> C[顯示單字長度]
    C --> D[猜測迴圈]
    D --> E[猜測字母]
    E --> F[檢查猜測結果]
    F --> G[猜對] --> H[更新 word_completion]
    F --> I[猜錯] --> J[減少 tries]
    J --> D
    G --> D

遊戲開發:猜字遊戲

遊戲邏輯

在猜字遊戲中,玩家需要猜測一個未知的單字。每次猜測,系統會反饋猜測的字母是否在單字中。如果猜測正確,系統會填充相應的空格;如果猜測錯誤,系統會扣除玩家的嘗試次數。

程式碼實作

以下是猜字遊戲的部分程式碼實作:

# 猜字遊戲邏輯
def guess_word(word, guess, guessed_letters, word_completion):
    # 檢查猜測的字母是否在單字中
    if guess in word:
        print("Good job,", guess, "is in the word!")
        guessed_letters.append(guess)
        
        # 更新單字的完成狀態
        word_as_list = list(word_completion)
        indices = [i for i, letter in enumerate(word) if letter == guess]
        for index in indices:
            word_as_list[index] = guess
        word_completion = "".join(word_as_list)
        
        # 檢查是否猜測完成
        if "_" not in word_completion:
            return True, word_completion
        else:
            return False, word_completion
    else:
        # 猜測錯誤,扣除嘗試次數
        print(guess, "is not in the word.")
        return False, word_completion

# 主遊戲迴圈
def game_loop(word):
    guessed = False
    guessed_letters = []
    word_completion = ["_"] * len(word)
    word_completion = "".join(word_completion)
    
    while not guessed:
        guess = input("請猜一個字母:")
        
        # 檢查猜測的字母是否已經猜過
        if guess in guessed_letters:
            print("You already guessed the letter", guess)
        else:
            guessed, word_completion = guess_word(word, guess, guessed_letters, word_completion)
            guessed_letters.append(guess)
            
            # 顯示目前的單字完成狀態
            print(word_completion)
            
        # 檢查是否猜測完成
        if guessed:
            print(" Congratulations, you guessed the word!")
            break

# 測試遊戲
word = "python"
game_loop(word)

內容解密

上述程式碼實作了猜字遊戲的基本邏輯。玩家可以猜測一個未知的單字,系統會反饋猜測的字母是否在單字中。如果猜測正確,系統會填充相應的空格;如果猜測錯誤,系統會扣除玩家的嘗試次數。遊戲會繼續直到玩家猜測完成單字。

圖表翻譯

以下是猜字遊戲的流程圖:

  flowchart TD
    A[開始] --> B[猜一個字母]
    B --> C[檢查猜測的字母是否在單字中]
    C -->|是| D[填充相應的空格]
    C -->|否| E[扣除嘗試次數]
    D --> F[檢查是否猜測完成]
    E --> F
    F -->|是| G[結束遊戲]
    F -->|否| B

上述流程圖顯示了猜字遊戲的基本流程。玩家可以猜測一個未知的單字,系統會反饋猜測的字母是否在單字中。如果猜測正確,系統會填充相應的空格;如果猜測錯誤,系統會扣除玩家的嘗試次數。遊戲會繼續直到玩家猜測完成單字。

基礎的繩索遊戲程式設計

從使用者經驗視角來看,本次分享涵蓋了多個程式設計練習,從簡易的休息提醒系統到終端機版的Hangman遊戲,皆展現了Python在不同應用場景的實用性。分析這些程式碼範例,可以發現開發者逐步提升了程式設計的邏輯思維,例如Hangman遊戲中對於使用者輸入的處理、遊戲流程的控制,以及圖形化介面的設計,都體現了程式設計技巧的提升。然而,這些程式碼仍有改進空間,例如錯誤處理機制可以更加完善,以提升程式的穩定性。此外,程式碼的模組化設計可以進一步最佳化,提高程式碼的可讀性和可維護性。展望未來,這些程式設計練習可以作為基礎,進一步發展更複雜的應用程式,例如結合GUI框架開發圖形化介面版本的Hangman遊戲,或是整合網路功能實作多人線上遊戲。玄貓認為,持續練習並精程式式設計技巧,將有助於開發者在軟體開發領域取得更大的成就。對於初學者而言,應著重於理解程式碼的邏輯和運作方式,並逐步嘗試修改和擴充套件程式功能,累積實務經驗。