Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เกม Hangman ใน Python: โค้ดตัวอย่างครบถ้วน

Hangman เป็นเกมทายคำคลาสสิก: ทายตัวอักษรทีละตัว ก่อนที่โอกาสจะหมด สร้างได้ง่ายด้วย Python เหมาะสำหรับมือใหม่

โค้ดเต็ม: Hangman Game

import time
import random

def play_hangman():
    #ต้อนรับผู้เล่น
    name = input("What is your name? ")
    print(f"Hello, {name}! Time to play Hangman!")
    print()
    
    time.sleep(1)
    print("Start guessing...")
    time.sleep(0.5)
    
    # คำลับ (สามารถเปลี่ยนหรือสุ่มจากลิสต์ได้)
    secret_word = "secret".lower()
    
    # ตัวแปรเกม
    guesses = ''           # ตัวอักษรที่ทายแล้ว
    turns = 12             # จำนวนโอกาส
    
    # เกมหลัก
    while turns > 0:
        failed = 0  # นับตัวอักษรที่ยังทายไม่ถูก
        
        # แสดงสถานะคำ: ตัวอักษรที่ทายถูก หรือ _ สำหรับที่ยังไม่ทาย
        for char in secret_word:
            if char in guesses:
                print(char, end=' ')
            else:
                print('_', end=' ')
                failed += 1
        print()  # new line
        
        # ตรวจสอบชนะ
        if failed == 0:
            print("\nYou won! 🎉")
            break
        
        # รับคำทาย
        guess = input("Guess a character: ").lower()
        guesses += guess
        
        # ตรวจสอบคำทาย
        if guess not in secret_word:
            turns -= 1
            print("Wrong! ❌")
            print(f"You have {turns} more guesses.")
            
            if turns == 0:
                print(f"\nYou Lose! 😢 The word was: {secret_word}")
        else:
            print("Good guess! ✅")

if __name__ == "__main__":
    play_hangman()

ตัวอย่างการเล่น

What is your name? Somchai
Hello, Somchai! Time to play Hangman!

Start guessing...
_ _ _ _ _ _
Guess a character: s
s _ _ _ _ s
Good guess! ✅
Guess a character: e
s e _ _ e s
Good guess! ✅
Guess a character: c
s e c _ e s
Good guess! ✅
Guess a character: r
s e c r e s
Good guess! ✅
Guess a character: t
s e c r e t

You won! 🎉

ปรับปรุงเกมให้สนุกขึ้น (Enhanced Version)

import random

WORDS = [
    "python", "programming", "computer", "algorithm", "database",
    "network", "software", "hardware", "internet", "keyboard"
]

HANGMAN_PICS = [
    """
     +---+
     |   |
         |
         |
         |
         |
    =========""",
    """
     +---+
     |   |
     O   |
         |
         |
         |
    =========""",
    # ... เพิ่มรูป hangman ต่อไปจนครบ 6-7 รูป
]

def play_enhanced_hangman():
    word = random.choice(WORDS).lower()
    guessed = set()
    wrong_guesses = 0
    max_wrong = 6
    
    print("🎮 Welcome to Hangman!")
    
    while wrong_guesses < max_wrong:
        # แสดงรูป
        print(HANGMAN_PICS[wrong_guesses])
        
        # แสดงคำ
        display = ' '.join([c if c in guessed else '_' for c in word])
        print(f"\nWord: {display}")
        print(f"Guessed: {' '.join(sorted(guessed))}")
        print(f"Lives left: {max_wrong - wrong_guesses}")
        
        # ตรวจสอบชนะ
        if all(c in guessed for c in word):
            print(f"\n🎉 You won! The word was: {word}")
            return
        
        # รับคำทาย
        guess = input("Guess a letter: ").lower()
        
        if len(guess) != 1 or not guess.isalpha():
            print("Please enter a single letter.")
            continue
        
        if guess in guessed:
            print("You already guessed that!")
            continue
        
        guessed.add(guess)
        
        if guess not in word:
            wrong_guesses += 1
            print(f"❌ Wrong! '{guess}' not in word.")
        else:
            print(f"✅ Good guess! '{guess}' is in the word.")
    
    # แพ้
    print(HANGMAN_PICS[wrong_guesses])
    print(f"\n💀 Game Over! The word was: {word}")

if __name__ == "__main__":
    play_enhanced_hangman()

แนวคิดการเขียนเกม (Game Loop Pattern)

ส่วน คำอธิบาย
Initializationตั้งค่าเริ่มต้น: คำลับ, โอกาส, ตัวแปรติดตาม
Displayแสดงสถานะปัจจุบัน (คำ, โอกาส, รูป)
Inputรับคำทายจากผู้เล่น
Validationตรวจสอบ input ถูกต้อง (ตัวอักษรเดี่ยว, ไม่ซ้ำ)
Updateอัปเดต state (เพิ่ม guessed, ลด turns)
Check Win/Loseตรวจสอบเงื่อนไขจบเกม
Loopทำซ้ำจนกว่าเกมจะจบ

ไอเดียขยายต่อ

  • เพิ่มระดับความยาก (คำยาว/สั้น, โอกาสมาก/น้อย)
  • Category words (สัตว์, ผลไม้, ประเทศ, ภาษาโปรแกรม)
  • High score system (บันทึกคะแนนลงไฟล์)
  • Multiplayer mode (สลับกันทาย)
  • GUI ด้วย tkinter หรือ pygame