🎉 سال نو، مهارت نو، مشاوره رایگان نقشه راه برنامه نویسی (آفر ویژه ثبت نام قبل از افزایش قیمت 🔥)
۰ ثانیه
۰ دقیقه
۰ ساعت
۱ Dastmardi
کد سنگ کاغذ قیچی
جامعه پایتون (وب) ایجاد شده در ۰۸ آذر ۱۴۰۱

قسمت config:

GAME_CHOICES = ('r', 'p', 's') 
RULES = {
    'rp': 'p',
    'rs': 'r',
    'ps': 's',
    'pr': 'p',
    'sp': 's',
    'sr': 'r',
}
scoreboard = {
    'user': 0,
    'system': 0,
}

کد اصلی برنامه:

from config import GAME_CHOICES, RULES, scoreboard
import random
def get_input():
    """
    get and validate user input
    choice random of GAME_CHOICES for system
    put them in a list
    """
    final_input = []
    user_input = input('Enter your choice please: (r,p,s)')
    if user_input not in GAME_CHOICES:
        print('Oops!!, wrong choice, try again please ')
        return get_input()
    final_input.append(user_input)
    system_input = random.choice(GAME_CHOICES)
    final_input.append(system_input)
    return final_input
def find_winner(user_system_choice):
    """
    get a list of user and system input and change them to the string and
    compare with game rules if they are not the same
    """
    match = ''.join(user_system_choice)
    if match in RULES:
        return RULES[match]
    else:
        return None
def update_scoreboard(result):
    """
     update scoreboard after each hand of game and show live result
    """
    if result['user'] == 3:
        scoreboard['user'] += 1
        msg = "You have won this game"
    else:
        scoreboard['system'] += 1
        msg = "You lost this game"
    print('#' * 40)
    print('##', f'user: {scoreboard["user"]}'.ljust(34), '##')
    print('##', f'system: {scoreboard["system"]}'.ljust(34), '##')
    print('##', f'msg: {msg}'.ljust(34), '##')
    print('#' * 40)
    return result
def play():
    """
    main play ground handler
    """
    result = {'user': 0, 'system': 0}
    while result['user'] < 3 and result['system'] < 3:
        user_system_choice = get_input()
        winner = find_winner(user_system_choice)
        if user_system_choice[0] == winner:
            result['user'] += 1
            msg = 'You win'
        elif user_system_choice[1] == winner:
            result['system'] += 1
            msg = 'You lose'
        else:
            msg = 'Draw'
        print(f"user: {user_system_choice[0]}\\t system: {user_system_choice[1]}"
              f"\\t result: {msg}")
    update_scoreboard(result)
    play_again = input("Do you want to play again? (y/n) ")
    if play_again == 'y':
        play()
if __name__ == '__main__':
    play()

درود وقتتون بخیر

ممنون از زمانی که گذاشتید و مطالب رو به اشتراک میزاری?

اما اگ تگ تاپیکهای این چنینی رو نکته آموزشی انتخاب کنید (نه سوال) بقیه دوستان هم راحتتر میتونن استفاده کنند

موفق باشید?

بهترین پاسخ
Reza Mobaraki ۰۸ آذر ۱۴۰۱، ۰۸:۴۷