터미널에서 파이썬을 사용하여 바위, 종이, 가위 놀이하기

내용물


  • Summary

  • Code
  • Let's talk logic
  • Of all things random
  • Validating user input
  • Validating user provided name
  • Validating user provided input


  • Bonus
  • Clearing screen for readibility
  • Displaying a scoreboard
  • Ascii art

  • Putting it all together

  • 요약

    I have always enjoyed an occasional game of Rock, paper and scissors with my friends. What better way to demonstrate the use of randomness generator in python. We could have just done a simple head and tails, but why not this. Walk with me and see how we can create a simple Rock, paper, scissors game that we can play on the terminal.

    LINK TO GITHUB VIDEO - HOW THE GAME WORKS ON A TERMINAL



    암호

    논리를 말해보자

    Rock beats scissors, scissors beats paper, and paper beats rock. When playing against an opponent, the possibilities are that either you and your opponent will pick the same or will pick two different elements. If you both pick the same element it will be considered a draw, and if you and your opponent pick different elements, one will win, and the other will lose the round.

    The following table demostrates who would win if both pick different elements.

    TABLE
    Payer 1 Player 2 Who wins?
    ---------- ---------- -----------
    Rock Paper Player 2
    Rock Scissors Player 1
    Paper Scissors Player 2
    Paper Rock Player 1
    Scissors Rock Player 2
    Scissors Paper Player 1

    While keeping scores, each player gets a point every time they win a round. One point is assigned to a draw column every time it is a draw, which means both players picked the same element. At the end of five rounds, the total score for both players is calculated and the winner is declared. If they both score same, it is a tie.

    In our case we will play against the computer. To simplify things, instead of entering 'Rock', 'Paper' and 'Scissors' as characters, which eventually we (I) would mispell, I choose to assign numbers to the elements. 'Rock' == 1, 'Paper' == 2 and 'Scissors' == 3.

    To quickly check who wins, we can validate the difference between the value of the element picked by the computer vs the value of the element picked by us. For the computer to win, the difference between its value and ours will either be '-2' or '1'.

    모든 것 중에서 무작위로

    Making the computer choose randomly from a list of choices. The dictionary provided to the computer is {'Rock':1, 'Paper':2, 'Scissors':3}. The values from the dict is used as a list input to a random generator. We use the random module 컴퓨터가 값 목록에서 하나의 값을 선택하도록 하기 위해 random.choice을 사용합니다.

    >>> import random
    >>> print(machine_choices)
    {'Rock': 1, 'Paper': 2, 'Scissors': 3}
    >>> def get_machine_choice():
    ...     return(random.choice(list(machine_choices.values())))
    ... 
    >>> get_machine_choice()
    1
    >>> get_machine_choice()
    3
    >>> get_machine_choice()
    2
    >>> get_machine_choice()
    2
    >>> get_machine_choice()
    2
    >>> get_machine_choice()
    1
    


    사용자 제공 입력 검증

    사용자 제공 이름 유효성 검사

    Store the user provided name in a global variable. If the name is empty assign a default name Bob.

    def validate_user_input_name():
        global user_input_name # Declaring the name provided by the user to modify the global variable.
        user_input_name = input("\nEnter your name: ") # Take user input for name
        if len(user_input_name.strip()) == 0: # If a space / carriage return is provided instead of a name, default to a name, in our case, Bob. We love Bob.
            user_input_name = 'Bob'
    
    # OUTPUT
    
    >> def validate_user_input_name():
    ...     global user_input_name # Declaring the name provided by the user to modify the global variable.
    ...     user_input_name = input("\nEnter your name: ") # Take user input for name
    ...     if len(user_input_name.strip()) == 0: # If a space / carriage return is provided instead of a name, default to a name, in our case, Bob. We love Bob.
    ...         user_input_name = 'Bob'
    ... 
    >>> validate_user_input_name()
    Enter your name: Sb
    >>> print(user_input_name)
    Sb
    >>> validate_user_input_name()
    Enter your name: 
    >>> print(user_input_name)
    Bob
    

    사용자 제공 입력 유효성 검사

    Return True if user provided input is either '1' or '2' or '3'. If it is anything else return False, including for empty spaces and carriage returns.

    def validate_user_input():
        global user_input # Declaring the user_input provided by the user to modify the global variable.
        user_input = input("\nEnter either 'Rock':1, 'Paper':2 or 'Scissors':3: ")
        if len((str(user_input)).strip()) == 0: # Removing all carriage returns / empty space cases
            return False
        elif int(user_input) not in list(machine_choices.values()): # Removing all invalid integer cases
            return False
        else:
            user_input = int(user_input)
            return True
    
    >>> def validate_user_input():
    ...     global user_input
    ...     user_input = input("\nEnter either 'Rock':1, 'Paper':2 or 'Scissors':3: ")
    ...     if len((str(user_input)).strip()) == 0:
    ...         return False
    ...     elif int(user_input) not in list(machine_choices.values()):
    ...         return False
    ...     else:
    ...         user_input = int(user_input)
    ...         return True
    ... 
    >>> validate_user_input()
    Enter either 'Rock':1, 'Paper':2 or 'Scissors':3: 1
    True
    >>> validate_user_input()
    Enter either 'Rock':1, 'Paper':2 or 'Scissors':3: 11
    False
    >>> validate_user_input()
    Enter either 'Rock':1, 'Paper':2 or 'Scissors':3: 
    False
    >>> validate_user_input()
    Enter either 'Rock':1, 'Paper':2 or 'Scissors':3:        
    False
    

    보너스

    가독성을 위해 화면 지우기

    to mod hoce hood to the stormation 1046716104104161041041616104666716104101610 Linux 환경에서 화면을 지우려면 clear 명령을 사용하거나 Windows 환경의 경우 cls 명령을 사용합니다.

    import os
    x = import.system('clear') # Linux environments
    
    x = import.system('cls') # Windows environments
    


    그만큼 DataFrame OS를 통해 점수 표시

    system() . 다음 코드를 사용하여 pandas를 설치할 수 있습니다.

    python3.10 -m pip install pandas
    


    우리가 디자인한 스코어보드는 판다를 사용하고 있습니다.

    >>> score_board = pandas.DataFrame(columns=["Player_1_score_card","Player_2_score_card",'Draws'],index=['Round 1','Round 2','Round 3','Round 4','Round 5'])
    >>> score_board = score_board.fillna(0)
    >>> score_board
             Player_1_score_card  Player_2_score_card  Draws
    Round 1                    0                    0      0
    Round 2                    0                    0      0
    Round 3                    0                    0      0
    Round 4                    0                    0      0
    Round 5                    0                    0      0
    


    아스키 아트의 세계에 오신 것을 환영합니다

    pandas 또는
    
       ###     ######   ######  #### ####       ###    ########  ######## 
      ## ##   ##    ## ##    ##  ##   ##       ## ##   ##     ##    ##    
     ##   ##  ##       ##        ##   ##      ##   ##  ##     ##    ##    
    ##     ##  ######  ##        ##   ##     ##     ## ########     ##    
    #########       ## ##        ##   ##     ######### ##   ##      ##    
    ##     ## ##    ## ##    ##  ##   ##     ##     ## ##    ##     ##    
    ##     ##  ######   ######  #### ####    ##     ## ##     ##    ##    
    
    
    웹사이트를 이미 방문하고 있습니다. 터미널 코드에 ASCII 그래픽을 추가하는 것은 재미있습니다. 우리 친구 "Machine"은 여기에서 왔습니다.

    모르는 경우 이것저것 종합해보면

    this 페이지에서 터미널에서 할 수 있는 가위바위보 게임을 만들기 위한 전체 코드를 확인하세요.

    좋은 웹페이지 즐겨찾기