search
HomeBackend DevelopmentPython TutorialFun terminal only dice game

Fun terminal only dice game

This is one of early projects. I.m still getting to grips with a variety of elements when it come to programming.

This is a fun dice game that I made based on the dice game from kindom come deliverence. I have created it in terminal only. Mostly due to the fact that I'm still trying to grip with open gl and other graphical oputputs.

Any feed back would be really welcome.


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] 




          

            
        

The above is the detailed content of Fun terminal only dice game. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Mathematical Modules in Python: StatisticsMathematical Modules in Python: StatisticsMar 09, 2025 am 11:40 AM

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Serialization and Deserialization of Python Objects: Part 1Serialization and Deserialization of Python Objects: Part 1Mar 08, 2025 am 09:39 AM

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

How to solve the permissions problem encountered when viewing Python version in Linux terminal?How to solve the permissions problem encountered when viewing Python version in Linux terminal?Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

Scraping Webpages in Python With Beautiful Soup: Search and DOM ModificationScraping Webpages in Python With Beautiful Soup: Search and DOM ModificationMar 08, 2025 am 10:36 AM

This tutorial builds upon the previous introduction to Beautiful Soup, focusing on DOM manipulation beyond simple tree navigation. We'll explore efficient search methods and techniques for modifying HTML structure. One common DOM search method is ex

What are some popular Python libraries and their uses?What are some popular Python libraries and their uses?Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to Create Command-Line Interfaces (CLIs) with Python?How to Create Command-Line Interfaces (CLIs) with Python?Mar 10, 2025 pm 06:48 PM

This article guides Python developers on building command-line interfaces (CLIs). It details using libraries like typer, click, and argparse, emphasizing input/output handling, and promoting user-friendly design patterns for improved CLI usability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version