관리
← All articles

Small Python Project 1: Making an Escape-Room Game

This article was translated from its source language with AI assistance. Please check technical terms and equations against the original.

An Escape-Room Game in Python

Hello. Let's make a simple escape-room game using Python. The rules are simple: discover a randomly chosen three-digit password to escape. Ten or more incorrect attempts, or entering 're' during play, restarts the game. It can be built using basic input/output, conditionals, and loops.

Small Python Project 1: Making an Escape-Room Game — Original concept illustration
Original concept illustration

 

Starting the Game

First generate a random password. Use Python's random module to choose three digits from zero to nine and set them as the password.

 

import random

def generate_password():
    return [str(random.randint(0, 9)) for _ in range(3)]

 

Entering and Checking the Password


Accept password input from the user. Check each digit as it is entered. If correct, prompt for the next; if incorrect, give a hint stating whether the entered digit is larger or smaller than the answer.

 

def check_password(correct_password):
    attempt_count = 0
    wrong_count = 0

    for i in range(3):
        while True:
            user_input = input(f"{i+1}번째 자리의 숫자를 입력하고 엔터를 누르세요 (재시작하려면 're' 입력): ")
            if user_input.lower() == 're':
                print("게임을 재시작합니다.")
                return False
            attempt_count += 1
            if attempt_count >= 10:
                print("10회 이상 틀렸습니다. 게임을 다시 시작합니다.")
                return False
            if user_input == correct_password[i]:
                print("정확합니다! 다음 자리수를 입력하세요.")
                break
            else:
                wrong_count += 1
                print("틀렸습니다. 다시 시도해주세요.")
                if user_input < correct_password[i]:
                    print("힌트: 입력하신 숫자는 정답보다 작습니다.")
                else:
                    print("힌트: 입력하신 숫자는 정답보다 큽니다.")

 

Restart Feature

Entering 're' during play lets the user restart at any time.

Small Python Project 1: Making an Escape-Room Game — Original illustration of the key points
Original illustration of the key points

Completing the Game and Attempt Counts

When every digit is correct, report how many mistakes were made and print a success message. Ten or more mistakes automatically restart the game.

 

def check_password(correct_password):
    attempt_count = 0
    wrong_count = 0

    for i in range(3):
        while True:
            user_input = input(f"{i+1}번째 자리의 숫자를 입력하고 엔터를 누르세요 (재시작하려면 're' 입력): ")
            if user_input.lower() == 're':
                print("게임을 재시작합니다.")
                return False
            attempt_count += 1
            if attempt_count >= 10:
                print("10회 이상 틀렸습니다. 게임을 다시 시작합니다.")
                return False
            if user_input == correct_password[i]:
                print("정확합니다! 다음 자리수를 입력하세요.")
                break
            else:
                wrong_count += 1
                print("틀렸습니다. 다시 시도해주세요.")
                if user_input < correct_password[i]:
                    print("힌트: 입력하신 숫자는 정답보다 작습니다.")
                else:
                    print("힌트: 입력하신 숫자는 정답보다 큽니다.")

 

Finally, the complete program combining the code above follows.

import random

# 비밀번호를 랜덤으로 생성하는 함수입니다.
def generate_password():
    return [str(random.randint(0, 9)) for _ in range(3)]

# 사용자가 입력한 비밀번호를 검증하고 힌트를 제공하는 함수입니다.
def check_password(correct_password):
    attempt_count = 0  # 시도 횟수를 카운트하는 변수입니다.
    wrong_count = 0    # 잘못된 입력 횟수를 카운트하는 변수입니다.

    for i in range(3):
        while True:
            user_input = input(f"{i+1}번째 자리의 숫자를 입력하고 엔터를 누르세요 (재시작하려면 're' 입력): ")
            if user_input.lower() == 're':
                print("게임을 재시작합니다.")
                return False  # 게임 재시작을 위해 False를 반환합니다.
            attempt_count += 1
            if attempt_count >= 10:
                print("10회 이상 틀렸습니다. 게임을 다시 시작합니다.")
                return False
            if user_input == correct_password[i]:
                print("정확합니다! 다음 자리수를 입력하세요.")
                break
            else:
                wrong_count += 1
                print("틀렸습니다. 다시 시도해주세요.")
                if user_input < correct_password[i]:
                    print("힌트: 입력하신 숫자는 정답보다 작습니다.")
                else:
                    print("힌트: 입력하신 숫자는 정답보다 큽니다.")

    print(f"비밀번호를 맞추기 위해 총 {wrong_count}번 틀렸습니다.")
    return True

# 게임을 시작하는 함수입니다.
def start_game():
    print("방탈출 게임에 오신 것을 환영합니다. 비밀번호는 3자리 숫자입니다.")

    while True:
        correct_password = generate_password()
        print(f"비밀번호가 설정되었습니다. (테스트를 위해 비밀번호를 출력합니다: {''.join(correct_password)})")
        if check_password(correct_password):
            print("비밀번호가 모두 맞습니다! 방탈출에 성공하셨습니다!")
            break

# 게임을 시작합니다.
start_game()

 

Original illustrations created to help explain this article.

Original on Tistory ↗