백엔드 개발 파이썬 튜토리얼 재미있는 단말기 전용 주사위 게임

재미있는 단말기 전용 주사위 게임

Nov 14, 2024 pm 02:24 PM

Fun terminal only dice game

초기 프로젝트 중 하나입니다. 저는 아직도 프로그래밍에 있어서 다양한 요소를 파악하고 있습니다.

킨덤컴 딜리버리스의 주사위 게임을 바탕으로 제가 만든 재미있는 주사위 게임입니다. 터미널에서만 만들었습니다. 주로 저는 여전히 Open Gl 및 기타 그래픽 출력 기능을 사용하려고 노력하고 있기 때문입니다.

어떤 피드백이라도 환영합니다.


import random


# menu to welcome the player
def menu():
    print("""
    Welcome to dice\n
      Would you like to: \n
         1. Review the rule, \n
         2. play a new game \n
         3. review scoring of dice \n
         """)
    try:
        menu_choice = input("")
    except EOFError:
        print("No input received. Please run the program in an interactive environment.")
        return
    if menu_choice == "1":
        print_rules()
    elif menu_choice == "2":
        new_game()
    elif menu_choice == "3":
        print_scroing_values()
        second_meu()
    else:
        print("Invalid choice please choose again")
        second_meu()


#second menu to allow for a alteration of language

def second_meu():
    print("""
  What would you like to do now?
      Would you like to: \n
         1. Review the rule, \n
         2. play a new game \n
         3. review scoring of dice \n
         """)
    menu_choice = input("Please enter your choice: ")
    if menu_choice == "1":
        print_rules()
    elif menu_choice == "2":
        new_game()
    elif menu_choice == "3":
        print_scroing_values()
        second_meu()
    else:
        print("Invalid choice please choose again")
        second_meu()

#explantion of rules
def print_rules():
    print("""
  A player's turn always begins by throwing all six dice. The player then selects and set aside scoring dice, and at least one die must always be set aside. Then the player can throw the remaining dice again and the situation repeats. \n

  Scoring combinations are counted only for the current throw, not the entire turn.\n

  The key element of the game is that if a throw does not produce a single scoring die, then the player's turn is over and all points scored up to that throw are forfeit. It is then the opposing player's turn to throw. \n

  For that reason, it's best to end your turn before the risk that not a single die will score gets too high. Sometimes it's better not to set aside all the scoring dice you you've thrown, so you stand a better chance of scoring higher on the next throw.\n\n
  """)
    second_meu()

#and the scroing system
def print_scroing_values():
    print("""Scoring is as follows:
    - a single 1 is worth 100 points; \n
    - a single 5 is worth 50 points; \n
    - three of a kind is worth 100 points multiplied by the given number, e.g. three 4s are worth 400 points; \n
    - three 1s are worth 1,000 points;\n
    - four or more of a kind is worth double the points of three of a kind, so four 4s are worth 800 points, five 4s are worth 1,600 points etc.\n
    - full straight 1-6 is worth 1500 points.\n
    - partial straight 1-5 is worth 500 points.\n
    - partial straight 2-6 is worth 750 points.\n\n """)


# This die clas allows funtionality to roll a six sided dice and output the value.
class die:
    def __init__(self):
        self.value = 0

    def __repr__(self):
        return f"{self.value}"

    def roll(self):
        self.value = random.randint(1, 6)



#here is where the class objects are created and organised into a list for ease of use.
die1 = die()
die2 = die()
die3 = die()
die4 = die()
die5 = die()
die6 = die()

dice = [die1, die2, die3, die4, die5, die6]


#player class hold the dice values, the player name a method for rolling all 6 dice at one and rerolling specific dice.
class player:
    def __init__(self, name, dice_list, score=4000):
        self.name = name
        self.score = score
        self.dice_list = dice_list

    def deduct_score(self, deduction):
        self.score -= deduction
        return self.score

    def roll_d6(self):
        roll_string: str = ""                  #this funtion rolls all the dice coverts them to string and labels them 1 to 6 producing eg 1: 6, 2: 6, 3: 1, 4: 2, 5: 3, 6: 2
        i = 1
        for die in dice:
            die.roll()
            data = die.value
            str_data = str(data)
            str_i = str(i)
            roll_string += str_i + ": " + str_data + ", "
            i += 1
        return roll_string

    def print_d6(self):                                     #just print the values
        roll_string: str = ""
        i = 1
        for die in dice:
            data = die.value
            str_data = str(data)
            str_i = str(i)
            roll_string += str_i + ": " + str_data + ", "
            i += 1
        return roll_string


    def re_roll(self, index):                         #re rolls dice speficed
        index-=1
        dice[index].roll()
        return dice[index].value


#This is the main game loop it has a lot of moving parts. Take your time reviewing.
def new_game():
    print("Hi so what is your name?\n")
    human_name = input("")
    human_player = player(human_name, dice, 4000)   #creating objects for both human and computer players in the player class
    print("who do you wish to play against?")
    computer_name = input("")
    computer_player = player(computer_name, dice, 4000)
    play = True
    while (play):
        print("""ok here is your roll: 
    you roll a: """)
        print(human_player.roll_d6())     #use of the player class function roll_d6 to give a string of rolled dice
        print("Time to score you dice")
        total_dice_score = possible_to_score(human_player.dice_list)   #this function is below and check to see if any of the dice can score
        print(total_dice_score)
        print("Whould you like to re-roll you any dice? Y/N")  #allowing the player a chance to re roll dice
        lroll = input("")
        roll = lroll.upper()
        if (roll == "Y"):
            dice_choice(human_player)
        #print(dice)
        print("Time to score you dice")
        total_dice_score = possible_to_score(dice)
        print(total_dice_score)
        human_player.deduct_score(total_dice_score)
        print(f"Your score is now {human_player.score}")
        print(f"Ok it's {computer_player.name} go they rolled")
        print(computer_player.roll_d6())
        print("They scored:")
        total_dice_score = possible_to_score(dice)
        print(total_dice_score)
        computer_player.deduct_score(total_dice_score)
        print(f"{computer_player.name} score is now {computer_player.score}")
        input("")
        if human_player.score <= 0 or computer_player.score <= 0:
            if human_player.score <= 0:
                print("You win well done!!")
            else:
                print("You lose to bad.")
            play = False



def possible_to_score(dice):    #dice is a alis for eaither human_player.dice_list or computer_player.dice_list which would look like [1, 2, 3, 4, 5, 6] with random numbers beteen 1 and 6 in each index.
    dice_score = 0
    numbers = count(dice)   #this function count the number of each dice rolled is is a little complex
    #print(dice)             #more functionality checking
    #print(numbers)
    isone = one(numbers)      #each of these are seperate function that check for andy 1s, 5s, any kinds e.g. dice that rolled the same number like four 5s, a full straight or a parital stright
    isfive = five(numbers)
    isthree_of_kind = three_of_kind(numbers)
    isfour_of_kind = four_of_kind(numbers)
    isfive_of_kind = five_of_kind(numbers)
    issix_of_kind = six_of_kind(numbers)
    isfull_straight = full_straight(numbers)
    isone_to_five = one_to_five(numbers)
    istwo_to_six = two_to_six(numbers)
    #print(isone, isfive, isthree_of_kind, isfour_of_kind, isfive_of_kind, issix_of_kind, isfull_straight, isone_to_five, istwo_to_six)      #used this to check the function was working in construction
    if (isone == True):
        dice_score = 10

    if (isfive == True):
        dice_score = 50

    if (isthree_of_kind[0] == True):
        dice_score = 100 * isthree_of_kind[1]    #these function woudl assign score to the dice depeding on valibles

    if (isfour_of_kind[0] == True):
        dice_score = 200 * isfour_of_kind[1]

    if (isfive_of_kind[0]):
        dice_score = 400 * isfive_of_kind[1]

    if (issix_of_kind[0]):
        dice_score = 800 * issix_of_kind[1]

    if (isfull_straight == True):
        temp_dice_score = 1500
        if temp_dice_score > dice_score:
            dice_score = temp_dice_score

    if (isone_to_five == True):
        temp_dice_score = 500
        if temp_dice_score > dice_score:
            dice_score = temp_dice_score
    if (istwo_to_six == True):
        temp_dice_score = 600

        if temp_dice_score > dice_score:
            dice_score = temp_dice_score
    return dice_score

def one(counts):
    if counts[0] >= 1:
        return True
    else:
        return False

def five(counts):
    if counts[4] >= 1:
        return True
    else:
        return False


def three_of_kind(counts):
    if 3 in counts:
        return True, counts.index(3)
    else:
        return False, None


def four_of_kind(counts):
    if 4 in counts:
        return True, counts.index
    else:
        return False, None


def five_of_kind(counts):
    if 5 in counts:
        return True, counts.index
    else:
        return False, None


def six_of_kind(counts):
    if 6 in counts:
        return True, counts.index
    else:
        return False, None


def full_straight(counts):
    if all(value == 1 for value in counts):
        return True
    else:
        return False

def one_to_five(counts):
    if counts[0] <= 1 & counts[1] <= 1 & counts[2] <= 1 & counts[3] <= 1 & counts[4] <= 1:
        return True
    else:
        return False


def two_to_six(counts):
    if counts[1] <= 1 & counts[2] <= 1 & counts[3] <= 1 & counts[4] <= 1 & counts[5] <= 1:
        return True
    else:
        return False

def count(dice):                   #dice is a alis for eaither human_player.dice_list or computer_player.dice_list which would look like [1, 2, 3, 4, 5, 6] with random numbers beteen 1 and 6 in each index.
    value_counts = count_values(dice)
    num_ones = value_counts[1]         #the job of this to take the 1: prefix to all the counts to leave behind only the count itself
    num_twos = value_counts[2]
    num_threes = value_counts[3]
    num_fours = value_counts[4]
    num_fives = value_counts[5]
    num_sixes = value_counts[6]
    numbers_list = [num_ones, num_twos, num_threes, num_fours, num_fives, num_sixes]
    return numbers_list   #this goes back to new game

def count_values(dice_list):
    counts = {i: 0 for i in range(1, 7)}     #this created this {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
    for die in dice_list:
        counts[die.value] += 1 #assins each of the dice to a value in numerical order eg of output {1: 1, 2: 1, 3: 2, 4: 1, 5: 1, 6: 0}
    return counts

def dice_choice(player):    #alis for human_player
    rolling = True
    print("Please type the dice you want to re-roll after each choice press enter. When you finish type exit and press enter.")
    while (rolling):
        player_input = input("")
        if player_input.isdigit():                     #checks is the input is a number
            number = int(player_input)
            if 1 <= number <= 6:                        #checks if it falls between 1 and 6
                player.re_roll(number)                         #rolls the dice specified
            else:
                print("Invalid entry must be a value between 1 and 6")
        elif player_input == "exit":
            print(f"Your new values are: {player.print_d6()} .")              #outputs the results
            rolling = False
        else:
            print("invalid entry must be a number or exit, please try again.")


menu()


로그인 후 복사

위 내용은 재미있는 단말기 전용 주사위 게임의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Python vs. C : 응용 및 사용 사례가 비교되었습니다 Python vs. C : 응용 및 사용 사례가 비교되었습니다 Apr 12, 2025 am 12:01 AM

Python은 데이터 과학, 웹 개발 및 자동화 작업에 적합한 반면 C는 시스템 프로그래밍, 게임 개발 및 임베디드 시스템에 적합합니다. Python은 단순성과 강력한 생태계로 유명하며 C는 고성능 및 기본 제어 기능으로 유명합니다.

2 시간의 파이썬 계획 : 현실적인 접근 2 시간의 파이썬 계획 : 현실적인 접근 Apr 11, 2025 am 12:04 AM

2 시간 이내에 Python의 기본 프로그래밍 개념과 기술을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우기, 2. 마스터 제어 흐름 (조건부 명세서 및 루프), 3. 기능의 정의 및 사용을 이해하십시오. 4. 간단한 예제 및 코드 스 니펫을 통해 Python 프로그래밍을 신속하게 시작하십시오.

파이썬 : 게임, Guis 등 파이썬 : 게임, Guis 등 Apr 13, 2025 am 12:14 AM

Python은 게임 및 GUI 개발에서 탁월합니다. 1) 게임 개발은 Pygame을 사용하여 드로잉, 오디오 및 기타 기능을 제공하며 2D 게임을 만드는 데 적합합니다. 2) GUI 개발은 Tkinter 또는 PYQT를 선택할 수 있습니다. Tkinter는 간단하고 사용하기 쉽고 PYQT는 풍부한 기능을 가지고 있으며 전문 개발에 적합합니다.

2 시간 안에 얼마나 많은 파이썬을 배울 수 있습니까? 2 시간 안에 얼마나 많은 파이썬을 배울 수 있습니까? Apr 09, 2025 pm 04:33 PM

2 시간 이내에 파이썬의 기본 사항을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우십시오. 이를 통해 간단한 파이썬 프로그램 작성을 시작하는 데 도움이됩니다.

Python vs. C : 학습 곡선 및 사용 편의성 Python vs. C : 학습 곡선 및 사용 편의성 Apr 19, 2025 am 12:20 AM

Python은 배우고 사용하기 쉽고 C는 더 강력하지만 복잡합니다. 1. Python Syntax는 간결하며 초보자에게 적합합니다. 동적 타이핑 및 자동 메모리 관리를 사용하면 사용하기 쉽지만 런타임 오류가 발생할 수 있습니다. 2.C는 고성능 응용 프로그램에 적합한 저수준 제어 및 고급 기능을 제공하지만 학습 임계 값이 높고 수동 메모리 및 유형 안전 관리가 필요합니다.

파이썬과 시간 : 공부 시간을 최대한 활용 파이썬과 시간 : 공부 시간을 최대한 활용 Apr 14, 2025 am 12:02 AM

제한된 시간에 Python 학습 효율을 극대화하려면 Python의 DateTime, Time 및 Schedule 모듈을 사용할 수 있습니다. 1. DateTime 모듈은 학습 시간을 기록하고 계획하는 데 사용됩니다. 2. 시간 모듈은 학습과 휴식 시간을 설정하는 데 도움이됩니다. 3. 일정 모듈은 주간 학습 작업을 자동으로 배열합니다.

파이썬 : 기본 응용 프로그램 탐색 파이썬 : 기본 응용 프로그램 탐색 Apr 10, 2025 am 09:41 AM

Python은 웹 개발, 데이터 과학, 기계 학습, 자동화 및 스크립팅 분야에서 널리 사용됩니다. 1) 웹 개발에서 Django 및 Flask 프레임 워크는 개발 프로세스를 단순화합니다. 2) 데이터 과학 및 기계 학습 분야에서 Numpy, Pandas, Scikit-Learn 및 Tensorflow 라이브러리는 강력한 지원을 제공합니다. 3) 자동화 및 스크립팅 측면에서 Python은 자동화 된 테스트 및 시스템 관리와 ​​같은 작업에 적합합니다.

파이썬 : 자동화, 스크립팅 및 작업 관리 파이썬 : 자동화, 스크립팅 및 작업 관리 Apr 16, 2025 am 12:14 AM

파이썬은 자동화, 스크립팅 및 작업 관리가 탁월합니다. 1) 자동화 : 파일 백업은 OS 및 Shutil과 같은 표준 라이브러리를 통해 실현됩니다. 2) 스크립트 쓰기 : PSUTIL 라이브러리를 사용하여 시스템 리소스를 모니터링합니다. 3) 작업 관리 : 일정 라이브러리를 사용하여 작업을 예약하십시오. Python의 사용 편의성과 풍부한 라이브러리 지원으로 인해 이러한 영역에서 선호하는 도구가됩니다.

See all articles