ใช้ Python สร้างเกม Rock Paper Scissors (เป่ายิ้งฉุบ) สนุกๆ ใช้ random.randint() สุ่มเลือกของคอมพิวเตอร์
กติกาเกม
- ค้อน (Rock) ชนะ กรรไกร (Scissors)
- กระดาษ (Paper) ชนะ ค้อน (Rock)
- กรรไกร (Scissors) ชนะ กระดาษ (Paper)
- เหมือนกัน = เสมอ
โค้ดตัวอย่างสมบูรณ์ (แก้ไขบั๊กจากต้นฉบับ)
import random
print("Rules of Rock Paper Scissors:")
print("Rock vs Paper -> Paper wins")
print("Rock vs Scissors -> Rock wins")
print("Paper vs Scissors -> Scissors wins\n")
choices = {1: 'Rock', 2: 'Paper', 3: 'Scissors'}
while True:
print("Enter your choice:")
print("1. Rock")
print("2. Paper")
print("3. Scissors")
try:
ch = int(input("Your turn: "))
except ValueError:
print("Please enter a number 1-3")
continue
while ch < 1 or ch > 3:
ch = int(input("Enter valid input (1-3): "))
choice_name = choices[ch]
print(f"Your choice: {choice_name}")
print("\nComputer's turn...")
comp_choice = random.randint(1, 3)
# คอมพิวเตอร์สุ่มใหม่ถ้าเหมือนกัน (optional - ปกติไม่ต้องทำ)
while comp_choice == ch:
comp_choice = random.randint(1, 3)
comp_choice_name = choices[comp_choice]
print(f"Computer choice: {comp_choice_name}")
print(f"{choice_name} vs {comp_choice_name}")
# กำหนดผู้ชนะ
if ((ch == 1 and comp_choice == 2) or (ch == 2 and comp_choice == 1)):
result = "Paper"
print("Paper wins => ", end="")
elif ((ch == 1 and comp_choice == 3) or (ch == 3 and comp_choice == 1)):
result = "Rock"
print("Rock wins => ", end="")
else:
result = "Scissors"
print("Scissors wins => ", end="")
if result == choice_name:
print("<== You win! ==>")
else:
print("<== Computer wins ==>")
print("\nPlay again? (Y/N)")
ans = input().lower()
if ans == 'n':
break
print("\nThanks for playing!")
ผลลัพธ์ตัวอย่าง
Rules of Rock Paper Scissors:
Rock vs Paper -> Paper wins
Rock vs Scissors -> Rock wins
Paper vs Scissors -> Scissors wins
Enter your choice:
1. Rock
2. Paper
3. Scissors
Your turn: 1
Your choice: Rock
Computer's turn...
Computer choice: Paper
Rock vs Paper
Paper wins => <== Computer wins ==>
Play again? (Y/N)
y
Enter your choice:
1. Rock
2. Paper
3. Scissors
Your turn: 2
Your choice: Paper
Computer's turn...
Computer choice: Rock
Paper vs Rock
Paper wins => <== You win! ==>
Play again? (Y/N)
n
Thanks for playing!
การปรับปรุงจากโค้ดต้นฉบับ
- ใช้ dictionary
choicesแทน if-elif ซ้ำ - เพิ่ม error handling สำหรับ input ที่ไม่ใช่ตัวเลข
- ใช้ f-string ทำให้อ่านง่าย
- แก้ typo:
elifch→elif ch - เพิ่ม
.lower()สำหรับ input Y/N
ขยายต่อ: เกมแบบ best of 3
def play_best_of(n):
player_wins = 0
comp_wins = 0
while player_wins < n//2 + 1 and comp_wins < n//2 + 1:
# ... game logic ...
if result == choice_name:
player_wins += 1
else:
comp_wins += 1
print(f"Score: You {player_wins} - {comp_wins} Computer")
return "You" if player_wins > comp_wins else "Computer"
print(f"Champion: {play_best_of(3)}")