Pygame 簡單的文字遊戲

在本文中,我們將演示如何建立一個簡單的猜謎遊戲。遊戲的目標是猜出正確的數字。

Pygame 猜數遊戲示例

下面是程式執行的的例子,

$ python game.py
Guess the number below 10:
Guess: 5
Wrong guess
Guess: 2
Wrong guess
Guess: 1
Wrong guess
Guess: 7
Wrong guess
Guess: 

隨機數

將要求使用者猜測隨機數。我們先選擇隨機數:

from random import randint
 
x = randint(1,9)

randint() 函式將選擇 1 到 10 之間的偽隨機數。然後我們必須繼續,直到找到正確的數字:

guess = -1
 
print("Guess the number below 10:")
while guess != x:
    guess = int(raw_input("Guess: "))
 
    if guess != x:
        print("Wrong guess")
    else:
        print("Guessed correctly")

Python 猜猜遊戲

下面的程式碼啟動遊戲:

from random import randint
 
x = randint(1,9)
guess = -1
 
print "Guess the number below 10:"
while guess != x:
    guess = int(raw_input("Guess: "))
 
    if guess != x:
        print("Wrong guess")
    else:
        print("Guessed correctly")

程式執行的例子,

Guess the number below 10:
Guess: 3
Wrong guess
Guess: 6
Wrong guess
..