You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python数字广度测试项目求助:OOP实现、数组问题及失败状态开发

Digit Span Test: Fixes and OOP Implementation

Here's a revised, OOP-based version of your digit span test that addresses all three issues:

import time
import random
import os

class DigitSpanTest:
    DIFFICULTY_SETTINGS = {
        1: {"name": "EASY", "display_time": 2.0},
        2: {"name": "MEDIUM", "display_time": 1.6},
        3: {"name": "HARD", "display_time": 1.2},
        4: {"name": "VIRTUALLY IMPOSSIBLE", "display_time": 0.7}
    }

    def __init__(self, difficulty):
        self.difficulty = difficulty
        self.display_duration = self.DIFFICULTY_SETTINGS[difficulty]["display_time"]
        self.current_span = 5  # Starting length of digit sequence
        self.is_running = True
        self.clear_screen()
        self.show_welcome_message()

    def clear_screen(self):
        os.system('cls' if os.name == 'nt' else 'clear')

    def show_welcome_message(self):
        print("Welcome to the digit span test.")
        time.sleep(1)
        self.clear_screen()
        time.sleep(1)
        print(f"Difficulty [{self.DIFFICULTY_SETTINGS[self.difficulty]['name']}] selected.")
        time.sleep(1)
        self.clear_screen()

    def generate_sequence(self):
        # Generate a new sequence of current_span length each time
        return [random.randint(1, 9) for _ in range(self.current_span)]

    def show_sequence(self, sequence):
        print("Get ready.")
        time.sleep(1)
        self.clear_screen()
        for digit in sequence:
            print(digit)
            time.sleep(self.display_duration)
            self.clear_screen()
            time.sleep(0.2)  # Short pause between digits for readability

    def get_user_input(self):
        user_sequence = []
        print(f"Enter the {self.current_span} digits one by one:")
        for _ in range(self.current_span):
            while True:
                try:
                    digit = int(input("> "))
                    if 1 <= digit <= 9:
                        user_sequence.append(digit)
                        break
                    else:
                        print("Please enter a single digit between 1-9.")
                except ValueError:
                    print("Invalid input. Enter a digit between 1-9.")
        return user_sequence

    def check_answer(self, correct_sequence, user_sequence):
        if user_sequence == correct_sequence:
            print("Nice! You got it right.")
            self.current_span += 1  # Increase span length for next round
            time.sleep(1.5)
            self.clear_screen()
            return True
        else:
            print("Uh oh, that's wrong. Game over!")
            print(f"Final score: {self.current_span - 1}")
            self.is_running = False  # Trigger lose state
            time.sleep(3)
            return False

    def run_game(self):
        while self.is_running:
            sequence = self.generate_sequence()
            self.show_sequence(sequence)
            user_input = self.get_user_input()
            self.check_answer(sequence, user_input)

def main():
    while True:
        try:
            gamediff = int(input("Input Difficulty (1 - 4): "))
            if gamediff in DigitSpanTest.DIFFICULTY_SETTINGS:
                game = DigitSpanTest(gamediff)
                game.run_game()
            else:
                print("Invalid Difficulty selected. Enter 1-4.")
        except ValueError:
            print("Invalid input. Enter a number between 1-4.")
        
        play_again = input("Play again? (y/n): ").lower().strip()
        if play_again != 'y':
            break

if __name__ == "__main__":
    main()

1. Fixing the Random Sequence Duplication

Your original code used a global randomlist that kept appending digits every round. The fix here is:

  • Generate a new sequence from scratch for each round using generate_sequence() instead of reusing a global list.
  • Increase the sequence length by 1 after each correct answer (not 5), which aligns with standard digit span test logic.

2. OOP Implementation Breakdown

We encapsulated all game logic into a DigitSpanTest class to organize state and behavior:

  • Attributes: Store difficulty settings, display time, current sequence length, and game running state.
  • Methods: Split functionality into focused methods (clear_screen, generate_sequence, show_sequence, etc.) for readability and reusability.
  • Difficulty Settings: Use a class-level dictionary to map difficulty levels to their display times, making it easy to adjust or add new levels later.

3. Implementing the Lose State

The lose state is handled by:

  • Tracking is_running as an instance attribute. When the user answers incorrectly, we set is_running = False to exit the game loop.
  • Displaying the final score (the highest span the user completed) when the game ends.
  • Adding a "play again" prompt after each game to improve user experience.

内容的提问来源于stack exchange,提问作者Lester Bemberton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 06:35:19