cari
Rumahpembangunan bahagian belakangTutorial PythonPermainan dadu terminal sahaja yang menyeronokkan

Fun terminal only dice game

Ini adalah salah satu projek awal. Saya masih memahami pelbagai elemen mengenai pengaturcaraan.

Ini adalah permainan dadu yang menyeronokkan yang saya buat berdasarkan permainan dadu dari kindom come deliverance. Saya telah menciptanya dalam terminal sahaja. Kebanyakannya disebabkan oleh fakta bahawa saya masih cuba menggunakan gl terbuka dan oputput grafik yang lain.

Sebarang maklum balas akan sangat dialu-alukan.


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] 




          

            
        

Atas ialah kandungan terperinci Permainan dadu terminal sahaja yang menyeronokkan. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Apakah beberapa operasi biasa yang boleh dilakukan pada tatasusunan python?Apakah beberapa operasi biasa yang boleh dilakukan pada tatasusunan python?Apr 26, 2025 am 12:22 AM

PythonArraysSupportVariousoperations: 1) SlicingExtractsSubsets, 2) Menambah/ExtendingAddSelements, 3) InsertingPlaceSelementSatSatSatSpecifics, 4) RemovingDeleteselements, 5) Sorting/ReversingChangesOrder,

Dalam jenis aplikasi yang biasa digunakan oleh numpy?Dalam jenis aplikasi yang biasa digunakan oleh numpy?Apr 26, 2025 am 12:13 AM

NumpyarraysareessentialforapplicationRequiringeficientnumericalcomputationsanddatamanipulation.theyarecrucialindaSascience, machinelearning, fizik, kejuruteraan, danfinanceduetotheirabilitytOHandlelarge-Scaledataefisien.Forexample, infinancialanal

Bilakah anda memilih untuk menggunakan array di atas senarai di Python?Bilakah anda memilih untuk menggunakan array di atas senarai di Python?Apr 26, 2025 am 12:12 AM

UseanArray.arrayoveralistinpythonwhendealingwithhomogeneousdata, criticalcode prestasi, orinterfacingwithccode.1) homogeneousdata: arrayssavemememorywithtypedelements.2)

Adakah semua operasi senarai disokong oleh tatasusunan, dan sebaliknya? Mengapa atau mengapa tidak?Adakah semua operasi senarai disokong oleh tatasusunan, dan sebaliknya? Mengapa atau mengapa tidak?Apr 26, 2025 am 12:05 AM

Tidak, notalllistoperationsaresuportedByArrays, andviceversa.1) arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing, whyimpactsperformance.2) listsdonotguaranteeconstantTimeComplexityFordirectacesscesscesscesscesscesscesscesscesscesessd.

Bagaimana anda mengakses elemen dalam senarai python?Bagaimana anda mengakses elemen dalam senarai python?Apr 26, 2025 am 12:03 AM

ToaccesselementsinaPythonlist,useindexing,negativeindexing,slicing,oriteration.1)Indexingstartsat0.2)Negativeindexingaccessesfromtheend.3)Slicingextractsportions.4)Iterationusesforloopsorenumerate.AlwayschecklistlengthtoavoidIndexError.

Bagaimana tatasusunan digunakan dalam pengkomputeran saintifik dengan python?Bagaimana tatasusunan digunakan dalam pengkomputeran saintifik dengan python?Apr 25, 2025 am 12:28 AM

Arraysinpython, terutamanya yang, arecrucialinscientificificputingputingfortheirefficiencyandversatility.1) mereka yang digunakan untuk

Bagaimana anda mengendalikan versi python yang berbeza pada sistem yang sama?Bagaimana anda mengendalikan versi python yang berbeza pada sistem yang sama?Apr 25, 2025 am 12:24 AM

Anda boleh menguruskan versi python yang berbeza dengan menggunakan Pyenv, Venv dan Anaconda. 1) Gunakan pyenv untuk menguruskan pelbagai versi python: Pasang pyenv, tetapkan versi global dan tempatan. 2) Gunakan VENV untuk mewujudkan persekitaran maya untuk mengasingkan kebergantungan projek. 3) Gunakan Anaconda untuk menguruskan versi python dalam projek sains data anda. 4) Simpan sistem python untuk tugas peringkat sistem. Melalui alat dan strategi ini, anda dapat menguruskan versi Python yang berbeza untuk memastikan projek yang lancar.

Apakah beberapa kelebihan menggunakan array numpy melalui array python standard?Apakah beberapa kelebihan menggunakan array numpy melalui array python standard?Apr 25, 2025 am 12:21 AM

Numpyarrayshaveseveraladvantagesoverstanderardpythonarrays: 1) thearemuchfasterduetoc-assedimplementation, 2) thearemorememory-efficient, antyedlargedataSets, and3) theyofferoptimized, vectorizedfuncionsformathhematicalicalicalicialisation

See all articles

Alat AI Hot

Undresser.AI Undress

Undresser.AI Undress

Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover

AI Clothes Remover

Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool

Undress AI Tool

Gambar buka pakaian secara percuma

Clothoff.io

Clothoff.io

Penyingkiran pakaian AI

Video Face Swap

Video Face Swap

Tukar muka dalam mana-mana video dengan mudah menggunakan alat tukar muka AI percuma kami!

Alat panas

VSCode Windows 64-bit Muat Turun

VSCode Windows 64-bit Muat Turun

Editor IDE percuma dan berkuasa yang dilancarkan oleh Microsoft

Muat turun versi mac editor Atom

Muat turun versi mac editor Atom

Editor sumber terbuka yang paling popular

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Persekitaran pembangunan bersepadu PHP yang berkuasa

MinGW - GNU Minimalis untuk Windows

MinGW - GNU Minimalis untuk Windows

Projek ini dalam proses untuk dipindahkan ke osdn.net/projects/mingw, anda boleh terus mengikuti kami di sana. MinGW: Port Windows asli bagi GNU Compiler Collection (GCC), perpustakaan import yang boleh diedarkan secara bebas dan fail pengepala untuk membina aplikasi Windows asli termasuk sambungan kepada masa jalan MSVC untuk menyokong fungsi C99. Semua perisian MinGW boleh dijalankan pada platform Windows 64-bit.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) ialah aplikasi web PHP/MySQL yang sangat terdedah. Matlamat utamanya adalah untuk menjadi bantuan bagi profesional keselamatan untuk menguji kemahiran dan alatan mereka dalam persekitaran undang-undang, untuk membantu pembangun web lebih memahami proses mengamankan aplikasi web, dan untuk membantu guru/pelajar mengajar/belajar dalam persekitaran bilik darjah Aplikasi web keselamatan. Matlamat DVWA adalah untuk mempraktikkan beberapa kelemahan web yang paling biasa melalui antara muka yang mudah dan mudah, dengan pelbagai tahap kesukaran. Sila ambil perhatian bahawa perisian ini