有趣的终端骰子游戏
来源:dev.to
2024-11-21 10:43:01
0浏览
收藏
本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《有趣的终端骰子游戏》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

这是早期项目之一。在编程方面,我仍在掌握各种元素。
这是一个有趣的骰子游戏,是我根据kindom come deliverence的骰子游戏制作的。我仅在终端中创建它。主要是因为我仍在尝试掌握 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()
理论要掌握,实操不能落!以上关于《有趣的终端骰子游戏》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
版本声明
本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
Win10系统更新到一半突然暂停或取消怎么办
- 上一篇
- Win10系统更新到一半突然暂停或取消怎么办
- 下一篇
- 安卓开发中“空指针错误”:如何避免因空指针导致的“源码与字节码不匹配”?
查看更多
最新文章
-
- 文章 · python教程 | 8分钟前 |
- Python函数嵌套调用技巧与应用
- 106浏览 收藏
-
- 文章 · python教程 | 49分钟前 |
- Python继承方法重写全解析
- 227浏览 收藏
-
- 文章 · python教程 | 1小时前 |
- Arrow文件高效合并技巧提升rechunk性能
- 168浏览 收藏
-
- 文章 · python教程 | 1小时前 |
- Dash多值输入与类型转换技巧详解
- 458浏览 收藏
-
- 文章 · python教程 | 10小时前 |
- NumPy位异或归约操作全解析
- 259浏览 收藏
-
- 文章 · python教程 | 11小时前 |
- Python遍历读取所有文件技巧
- 327浏览 收藏
-
- 文章 · python教程 | 11小时前 |
- Python中index的作用及使用方法
- 358浏览 收藏
-
- 文章 · python教程 | 11小时前 |
- Python快速访问嵌套字典键值对
- 340浏览 收藏
-
- 文章 · python教程 | 12小时前 |
- Python中ch代表字符的用法解析
- 365浏览 收藏
-
- 文章 · python教程 | 12小时前 |
- NumPy1D近邻查找:向量化优化技巧
- 391浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- ChatExcel酷表
- ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
- 3206次使用
-
- Any绘本
- 探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
- 3419次使用
-
- 可赞AI
- 可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
- 3448次使用
-
- 星月写作
- 星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
- 4557次使用
-
- MagicLight
- MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
- 3826次使用
查看更多
相关文章
-
- Flask框架安装技巧:让你的开发更高效
- 2024-01-03 501浏览
-
- Django框架中的并发处理技巧
- 2024-01-22 501浏览
-
- 提升Python包下载速度的方法——正确配置pip的国内源
- 2024-01-17 501浏览
-
- Python与C++:哪个编程语言更适合初学者?
- 2024-03-25 501浏览
-
- 品牌建设技巧
- 2024-04-06 501浏览

