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

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  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] 




          

            
        

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

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

Python과 C는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1) Python은 간결한 구문 및 동적 타이핑으로 인해 빠른 개발 및 데이터 처리에 적합합니다. 2) C는 정적 타이핑 및 수동 메모리 관리로 인해 고성능 및 시스템 프로그래밍에 적합합니다.

Python vs. C : 프로젝트를 위해 어떤 언어를 선택해야합니까?Python vs. C : 프로젝트를 위해 어떤 언어를 선택해야합니까?Apr 21, 2025 am 12:17 AM

Python 또는 C를 선택하는 것은 프로젝트 요구 사항에 따라 다릅니다. 1) 빠른 개발, 데이터 처리 및 프로토 타입 설계가 필요한 경우 Python을 선택하십시오. 2) 고성능, 낮은 대기 시간 및 근접 하드웨어 제어가 필요한 경우 C를 선택하십시오.

파이썬 목표에 도달 : 매일 2 시간의 힘파이썬 목표에 도달 : 매일 2 시간의 힘Apr 20, 2025 am 12:21 AM

매일 2 시간의 파이썬 학습을 투자하면 프로그래밍 기술을 효과적으로 향상시킬 수 있습니다. 1. 새로운 지식 배우기 : 문서를 읽거나 자습서를 시청하십시오. 2. 연습 : 코드를 작성하고 완전한 연습을합니다. 3. 검토 : 배운 내용을 통합하십시오. 4. 프로젝트 실무 : 실제 프로젝트에서 배운 것을 적용하십시오. 이러한 구조화 된 학습 계획은 파이썬을 체계적으로 마스터하고 경력 목표를 달성하는 데 도움이 될 수 있습니다.

2 시간 극대화 : 효과적인 파이썬 학습 전략2 시간 극대화 : 효과적인 파이썬 학습 전략Apr 20, 2025 am 12:20 AM

2 시간 이내에 Python을 효율적으로 학습하는 방법 : 1. 기본 지식을 검토하고 Python 설치 및 기본 구문에 익숙한 지 확인하십시오. 2. 변수, 목록, 기능 등과 같은 파이썬의 핵심 개념을 이해합니다. 3. 예제를 사용하여 마스터 기본 및 고급 사용; 4. 일반적인 오류 및 디버깅 기술을 배우십시오. 5. 목록 이해력 사용 및 PEP8 스타일 안내서와 같은 성능 최적화 및 모범 사례를 적용합니다.

Python과 C : The Hight Language 중에서 선택Python과 C : The Hight Language 중에서 선택Apr 20, 2025 am 12:20 AM

Python은 초보자 및 데이터 과학에 적합하며 C는 시스템 프로그래밍 및 게임 개발에 적합합니다. 1. 파이썬은 간단하고 사용하기 쉽고 데이터 과학 및 웹 개발에 적합합니다. 2.C는 게임 개발 및 시스템 프로그래밍에 적합한 고성능 및 제어를 제공합니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

Python vs. C : 프로그래밍 언어의 비교 분석Python vs. C : 프로그래밍 언어의 비교 분석Apr 20, 2025 am 12:14 AM

Python은 데이터 과학 및 빠른 개발에 더 적합한 반면 C는 고성능 및 시스템 프로그래밍에 더 적합합니다. 1. Python Syntax는 간결하고 학습하기 쉽고 데이터 처리 및 과학 컴퓨팅에 적합합니다. 2.C는 복잡한 구문을 가지고 있지만 성능이 뛰어나고 게임 개발 및 시스템 프로그래밍에 종종 사용됩니다.

하루 2 시간 : 파이썬 학습의 잠재력하루 2 시간 : 파이썬 학습의 잠재력Apr 20, 2025 am 12:14 AM

파이썬을 배우기 위해 하루에 2 시간을 투자하는 것이 가능합니다. 1. 새로운 지식 배우기 : 목록 및 사전과 같은 1 시간 안에 새로운 개념을 배우십시오. 2. 연습 및 연습 : 1 시간을 사용하여 소규모 프로그램 작성과 같은 프로그래밍 연습을 수행하십시오. 합리적인 계획과 인내를 통해 짧은 시간에 Python의 핵심 개념을 마스터 할 수 있습니다.

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

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

See all articles

핫 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 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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