关键词

3个适合新手练习的python小游戏

当你正在学习 Python 时,练习写小游戏是非常有意义的,它可以增加你的编程技能和对语言的熟悉程度。这里给出了三个适合新手练习的 Python 小游戏:猜数字游戏、Tic Tac Toe 井字游戏和 Hangman 字谜游戏。

猜数字游戏

这个游戏很简单,它会在 1 到 100 的范围内生成一个随机数,玩家需要猜出这个数字。如果猜测错误,程序会告诉玩家是偏大还是偏小,让他们继续猜测。

import random

number = random.randint(1, 100)
guess = int(input("Guess the number between 1 and 100: "))

while guess != number:
    if guess < number:
        guess = int(input("Too low, try again: "))
    else:
        guess = int(input("Too high, try again: "))

print("Congratulations! You guessed the number.")

Tic Tac Toe 井字游戏

Tic Tac Toe 是一款经典的小游戏,可以用于练习逻辑和决策流程。

import numpy as np

board = np.array([['-', '-', '-'],
                  ['-', '-', '-'],
                  ['-', '-', '-']])

player = 1
moves = 0

def check_win(board):
    # 检查行
    for i in range(3):
        if board[i][0] == board[i][1] == board[i][2] != '-':
            return True

    # 检查列
    for j in range(3):
        if board[0][j] == board[1][j] == board[2][j] != '-':
            return True

    # 检查对角线
    if board[0][0] == board[1][1] == board[2][2] != '-' or \
        board[2][0] == board[1][1] == board[0][2] != '-':
        return True

    return False

while True:
    # 打印井字游戏棋盘
    print(board)

    # 获取玩家输入的下棋位置
    row = int(input(f"Player {player}, pick a row (0, 1, or 2): "))
    col = int(input(f"Player {player}, pick a col (0, 1, or 2): "))

    # 判断此处是否已经有棋子
    if board[row][col] != '-':
        print("This spot is already taken!")
        continue

    # 放置棋子
    if player == 1:
        board[row][col] = "X"
        player = 2
    else:
        board[row][col] = "O"
        player = 1

    moves += 1

    # 检查游戏是否结束
    if check_win(board):
        print(board)
        print(f"Player {player} wins!")
        break

    if moves == 9:
        print(board)
        print("It's a tie!")
        break

Hangman 字谜游戏

Hangman 是一款经典的单词猜谜游戏,游戏会随机选取一个单词并将其每个字母替换成下划线,玩家需要猜测出这个单词。

import random

words = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape"]
word = random.choice(words)

guessed = []
tries = 7

while tries > 0:
    # 打印下划线和已经猜测过的字母
    output = ""
    for letter in word:
        if letter in guessed:
            output += letter
        else:
            output += "_"
    print(output)

    # 获取玩家输入的猜测字母
    guess = input("Guess a letter: ")

    if guess in guessed:
        print("You already guessed that letter!")
    elif guess in word:
        guessed.append(guess)
        print("Correct!")
    else:
        tries -= 1
        print("Wrong. You have", tries, "tries left.")

    # 检查玩家是否已经猜测出了整个单词
    if set(word) == set(guessed):
        print("Congratulations! You guessed the word.")
        break

if tries == 0:
    print("Sorry, you ran out of tries. The word was", word)

以上就是三个适合新手练习的 Python 小游戏的详细攻略。希望能够帮助你提高编程技能。

本文链接:http://task.lmcjl.com/news/14843.html

展开阅读全文