Fall 2020 Berkeley cs61a Hog Project
**
Fall 2020 Berkeley cs61a Hog Project
**
Fall 2020 的Hog和之前project有些变化,Github找不到,所以分享一下~
"""CS 61A Presents The Game of Hog."""from dice import six_sided, four_sided, make_test_dice
from ucb import main, trace, interactGOAL_SCORE = 100 # The goal of Hog is to score 100 points.
FIRST_101_DIGITS_OF_PI = 31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679######################
# Phase 1: Simulator #
######################def roll_dice(num_rolls, dice=six_sided):"""Simulate rolling the DICE exactly NUM_ROLLS > 0 times. Return the sum ofthe outcomes unless any of the outcomes is 1. In that case, return 1.num_rolls: The number of dice rolls that will be made.dice: A function that simulates a single dice roll outcome."""# These assert statements ensure that num_rolls is a positive integer.assert type(num_rolls) == int, 'num_rolls must be an integer.'assert num_rolls > 0, 'Must roll at least once.'# BEGIN PROBLEM 1"*** YOUR CODE HERE ***"sum = 0mark = 0while num_rolls >= 1:current_dice = dice()sum = sum + current_diceif current_dice == 1:mark = 1num_rolls = num_rolls - 1if mark == 1:sum = 1return sum# END PROBLEM 1def free_bacon(score):"""Return the points scored from rolling 0 dice (Free Bacon).score: The opponent's current score."""assert score < 100, 'The game should be over.'pi = FIRST_101_DIGITS_OF_PI# Trim pi to only (score + 1) digit(s)# BEGIN PROBLEM 2"*** YOUR CODE HERE ***"pi = pi // 10**(100-score)sum = pi % 10 + 3return sum# END PROBLEM 2return pi % 10 + 3def take_turn(num_rolls, opponent_score, dice=six_sided):"""Simulate a turn rolling NUM_ROLLS dice, which may be 0 (Free Bacon).Return the points scored for the turn by the current player.num_rolls: The number of dice rolls that will be made.opponent_score: The total score of the opponent.dice: A function that simulates a single dice roll outcome."""# Leave these assert statements here; they help check for errors.assert type(num_rolls) == int, 'num_rolls must be an integer.'assert num_rolls >= 0, 'Cannot roll a negative number of dice in take_turn.'assert num_rolls <= 10, 'Cannot roll more than 10 dice.'assert opponent_score < 100, 'The game should be over.'# BEGIN PROBLEM 3"*** YOUR CODE HERE ***"if num_rolls == 0:return free_bacon(opponent_score)else:return roll_dice(num_rolls, dice)# END PROBLEM 3def extra_turn(player_score, opponent_score):"""Return whether the player gets an extra turn."""return (pig_pass(player_score, opponent_score) orswine_align(player_score, opponent_score))def swine_align(player_score, opponent_score):"""Return whether the player gets an extra turn due to Swine Align.player_score: The total score of the current player.opponent_score: The total score of the other player.>>> swine_align(30, 45) # The GCD is 15.True>>> swine_align(35, 45) # The GCD is 5.False"""# BEGIN PROBLEM 4a"*** YOUR CODE HERE ***"if player_score == 0 or opponent_score == 0:return FalseGCD = min(player_score, opponent_score)while GCD >= 10:if player_score % GCD == 0 and opponent_score % GCD == 0:return Trueelse:GCD = GCD - 1return False# END PROBLEM 4adef pig_pass(player_score, opponent_score):"""Return whether the player gets an extra turn due to Pig Pass.player_score: The total score of the current player.opponent_score: The total score of the other player.>>> pig_pass(9, 12)False>>> pig_pass(10, 12)True>>> pig_pass(11, 12)True>>> pig_pass(12, 12)False>>> pig_pass(13, 12)False"""# BEGIN PROBLEM 4b"*** YOUR CODE HERE ***"if opponent_score - player_score < 3 and opponent_score - player_score > 0:return Trueelse:return False# END PROBLEM 4bdef other(who):"""Return the other player, for a player WHO numbered 0 or 1.>>> other(0)1>>> other(1)0"""return 1 - whodef silence(score0, score1):"""Announce nothing (see Phase 2)."""return silencedef play(strategy0, strategy1, score0=0, score1=0, dice=six_sided,goal=GOAL_SCORE, say=silence):"""Simulate a game and return the final scores of both players, with Player0's score first, and Player 1's score second.A strategy is a function that takes two total scores as arguments (thecurrent player's score, and the opponent's score), and returns a number ofdice that the current player will roll this turn.strategy0: The strategy function for Player 0, who plays first.strategy1: The strategy function for Player 1, who plays second.score0: Starting score for Player 0score1: Starting score for Player 1dice: A function of zero arguments that simulates a dice roll.goal: The game ends and someone wins when this score is reached.say: The commentary function to call at the end of the first turn."""who = 0 # Who is about to take a turn, 0 (first) or 1 (second)# BEGIN PROBLEM 5"*** YOUR CODE HERE ***"while True:if who == 0:score_gained = take_turn(strategy0(score0, score1),score1, dice )score0 = score0 + score_gainedsay = say(score0, score1)if score0 >= goal or score1 >= goal:breakif not extra_turn(score0, score1):who = other(who)else:score_gained = take_turn(strategy1(score1, score0),score0, dice )score1 = score1 + score_gainedsay = say(score0, score1)if score0 >= goal or score1 >= goal:breakif not extra_turn(score1, score0):who = other(who)# END PROBLEM 5# (note that the indentation for the problem 6 prompt (***YOUR CODE HERE***) might be misleading)# BEGIN PROBLEM 6"*** YOUR CODE HERE ***"# END PROBLEM 6return score0, score1#######################
# Phase 2: Commentary #
#######################def say_scores(score0, score1):"""A commentary function that announces the score for each player."""print("Player 0 now has", score0, "and Player 1 now has", score1)return say_scoresdef announce_lead_changes(last_leader=None):"""Return a commentary function that announces lead changes.>>> f0 = announce_lead_changes()>>> f1 = f0(5, 0)Player 0 takes the lead by 5>>> f2 = f1(5, 12)Player 1 takes the lead by 7>>> f3 = f2(8, 12)>>> f4 = f3(8, 13)>>> f5 = f4(15, 13)Player 0 takes the lead by 2"""def say(score0, score1):if score0 > score1:leader = 0elif score1 > score0:leader = 1else:leader = Noneif leader != None and leader != last_leader:print('Player', leader, 'takes the lead by', abs(score0 - score1))return announce_lead_changes(leader)return saydef both(f, g):"""Return a commentary function that says what f says, then what g says.NOTE: the following game is not possible under the rules, it's justan example for the sake of the doctest>>> h0 = both(say_scores, announce_lead_changes())>>> h1 = h0(10, 0)Player 0 now has 10 and Player 1 now has 0Player 0 takes the lead by 10>>> h2 = h1(10, 8)Player 0 now has 10 and Player 1 now has 8>>> h3 = h2(10, 17)Player 0 now has 10 and Player 1 now has 17Player 1 takes the lead by 7"""def say(score0, score1):return both(f(score0, score1), g(score0, score1))return saydef announce_highest(who, last_score=0, running_high=0):"""Return a commentary function that announces when WHO's scoreincreases by more than ever before in the game.NOTE: the following game is not possible under the rules, it's justan example for the sake of the doctest>>> f0 = announce_highest(1) # Only announce Player 1 score gains>>> f1 = f0(12, 0)>>> f2 = f1(12, 9)9 point(s)! The most yet for Player 1>>> f3 = f2(20, 9)>>> f4 = f3(20, 30)21 point(s)! The most yet for Player 1>>> f5 = f4(20, 47) # Player 1 gets 17 points; not enough for a new high>>> f6 = f5(21, 47)>>> f7 = f6(21, 77)30 point(s)! The most yet for Player 1"""assert who == 0 or who == 1, 'The who argument should indicate a player.'# BEGIN PROBLEM 7"*** YOUR CODE HERE ***"def say(score0, score1):alt = running_highif who == 0:current_score = score0else:current_score = score1range = current_score - last_scoreif range > alt:alt = rangeprint(range, 'point(s)!', 'The most yet for Player', who)return announce_highest(who, current_score, alt)return say # END PROBLEM 7#######################
# Phase 3: Strategies #
#######################def always_roll(n):"""Return a strategy that always rolls N dice.A strategy is a function that takes two total scores as arguments (thecurrent player's score, and the opponent's score), and returns a number ofdice that the current player will roll this turn.>>> strategy = always_roll(5)>>> strategy(0, 0)5>>> strategy(99, 99)5"""def strategy(score, opponent_score):return nreturn strategydef make_averaged(original_function, trials_count=1000):"""Return a function that returns the average value of ORIGINAL_FUNCTIONwhen called.To implement this function, you will have to use *args syntax, a new Pythonfeature introduced in this project. See the project description.>>> dice = make_test_dice(4, 2, 5, 1)>>> averaged_dice = make_averaged(dice, 1000)>>> averaged_dice()3.0"""# BEGIN PROBLEM 8"*** YOUR CODE HERE ***"def another_one(*args):i = 0sum = 0while i < trials_count:data = original_function(*args)sum += datai += 1return sum/trials_countreturn another_one# END PROBLEM 8def max_scoring_num_rolls(dice=six_sided, trials_count=1000):"""Return the number of dice (1 to 10) that gives the highest average turnscore by calling roll_dice with the provided DICE over TRIALS_COUNT times.Assume that the dice always return positive outcomes.>>> dice = make_test_dice(1, 6)>>> max_scoring_num_rolls(dice)1"""# BEGIN PROBLEM 9"*** YOUR CODE HERE ***"i = 1best_gained_score = 0while i <= 10:estimated_gained_score = make_averaged(roll_dice, trials_count)(i, dice)if estimated_gained_score > best_gained_score:best_gained_score = estimated_gained_scorebest_num_of_rolls = ii = i + 1return best_num_of_rolls# END PROBLEM 9def winner(strategy0, strategy1):"""Return 0 if strategy0 wins against strategy1, and 1 otherwise."""score0, score1 = play(strategy0, strategy1)if score0 > score1:return 0else:return 1def average_win_rate(strategy, baseline=always_roll(6)):"""Return the average win rate of STRATEGY against BASELINE. Averages thewinrate when starting the game as player 0 and as player 1."""win_rate_as_player_0 = 1 - make_averaged(winner)(strategy, baseline)win_rate_as_player_1 = make_averaged(winner)(baseline, strategy)return (win_rate_as_player_0 + win_rate_as_player_1) / 2def run_experiments():"""Run a series of strategy experiments and report results."""if False: # Change to False when done finding max_scoring_num_rollssix_sided_max = max_scoring_num_rolls(six_sided)print('Max scoring num rolls for six-sided dice:', six_sided_max)if True: # Change to True to test always_roll(8)print('always_roll(8) win rate:', average_win_rate(always_roll(8)))if False: # Change to True to test bacon_strategyprint('bacon_strategy win rate:', average_win_rate(bacon_strategy))if False: # Change to True to test extra_turn_strategyprint('extra_turn_strategy win rate:', average_win_rate(extra_turn_strategy))if False: # Change to True to test final_strategyprint('final_strategy win rate:', average_win_rate(final_strategy))"*** You may add additional experiments as you wish ***"def bacon_strategy(score, opponent_score, cutoff=8, num_rolls=6):"""This strategy rolls 0 dice if that gives at least CUTOFF points, androlls NUM_ROLLS otherwise."""# BEGIN PROBLEM 10if free_bacon(opponent_score) >= cutoff:return 0else: return num_rolls# END PROBLEM 10def extra_turn_strategy(score, opponent_score, cutoff=8, num_rolls=6):"""This strategy rolls 0 dice when it triggers an extra turn. It alsorolls 0 dice if it gives at least CUTOFF points and does not give an extra turn.Otherwise, it rolls NUM_ROLLS."""# BEGIN PROBLEM 11if extra_turn(free_bacon(opponent_score) + score, opponent_score):return 0if bacon_strategy(score, opponent_score, cutoff, num_rolls) == 0:return 0return num_rolls# END PROBLEM 11def final_strategy(score, opponent_score):"""Write a brief description of your final strategy.*** YOUR DESCRIPTION HERE ***"""# BEGIN PROBLEM 12return 6 # Replace this statement# END PROBLEM 12##########################
# Command Line Interface #
########################### NOTE: Functions in this section do not need to be changed. They use features
# of Python not yet covered in the course.@main
def run(*args):"""Read in the command-line argument and calls corresponding functions."""import argparseparser = argparse.ArgumentParser(description="Play Hog")parser.add_argument('--run_experiments', '-r', action='store_true',help='Runs strategy experiments')args = parser.parse_args()if args.run_experiments:run_experiments()
Fall 2020 Berkeley cs61a Hog Project相关推荐
- Fall 2020 Berkeley cs61a hw01答案
Fall 2020 Berkeley cs61a hw01答案 from operator import add, subdef a_plus_abs_b(a, b):""&quo ...
- 2020 UCB CS61A FALL -- project1 hog
UCB2020的秋季课,老师是Hany Farid和John DeNero hog是第一个项目,做的时候感觉细节挺多的,主要是熟悉下python的一些语法和高阶函数的使用 代码 "" ...
- CS229 Fall 2020 Python Tutorial
Python Operators print(5 // 2) # integer division output=2 Python doesn't have command like "a+ ...
- 操作系统实验Lab 1:Xv6 and Unix utilities(MIT 6.S081 FALL 2020)
Lab 1 Xv6 and Unix utilities 实验要求链接 Boot xv6 (easy) 实验目的 切换到 xv6-labs-2020 代码的 util 分支,并利用 QEMU 模拟器启 ...
- VMware发布Project Monterey
全球领先的企业软件创新者VMware(NYSE:VMW) 今天在VMworld 2020大会上发布Project Monterey.这一技术预览聚焦于提升数据中心.云和边缘架构,从而满足新一代应用不断 ...
- XV6实验(2020)
XV6实验记录(2020) 环境搭建 参考连接 Lab guidance (mit.edu) 6.S081 / Fall 2020 (mit.edu) xv6 book中文版 Lab1:Xv6 and ...
- 2020留学党:回国后,我要和874万应届生抢机会
看着今年北美应届生就业市场的惨状,留学党表示很心碎.但是望向国内,疫情后的招聘市场也不容乐观,更别说还有几百万人正在虎视眈眈了. 难道花了这么多时间和金钱,换来的就是一个堪堪的工作吗?今年海归留学生的 ...
- 两年前被微软收购的 Bonsai,成为了 Build 2020 的重要杀器
By 超神经 内容提要:昨天,微软 Build 2020 首次在线上召开.大会第一天,发布了多个重磅新品,包括 AI 超级计算机.工业系统 AI 开发平台 Bonsai 项目等,我们从中可一窥微软的 ...
- 计算机视觉领域经典论文源码
计算机视觉领域经典论文源码 转载自:http://blog.csdn.net/ddreaming/article/details/52416643 2016-CVPR论文代码资源: https://t ...
最新文章
- PHP应对洪水般的恶意访问接口 访问冲击
- 前端换行显示,后端返回br
- 【转】关于WaterFall瀑布流式布局的性能优化
- hdu 1251 统计难题 (Trie树)
- 基于DNS实现智能化访问网站
- browserCaps与浏览器功能设置
- python库skimage 图像直方图均衡化、自适应均衡化、对比度拉伸实现
- 用折半查找法查找某一字符在字符串中的位置
- python封装成exe后运行失败_python 在编译成EXE 文件后报错 我实在是找不出原因
- Python Socket模块实现服务端与客户端通信
- 奥克兰大学计算机科学与技术,奥克兰大学计算机科学专业怎么样?成为IT达人就靠它...
- 转帖 分享代码自动生成
- 用 ABAP 调用 OCR 接口实现出租车发票扫描
- Jena TDB的使用简介
- JS实现动态生成表格
- TiDB at ZaloPay Infrastructure Lesson Learned
- 谷歌浏览器chrome安装vuejs devtools 插件
- creator 物理画线
- ArcGIS JSAPI2.0在IIS上的安装
- 【题解】康娜的线段树
热门文章
- 王燕《应用时间序列分析》学习笔记2
- 基于lnmp 一键安装 添加 Nginx 的模块(module)
- 分布式计算机联锁系统,基于MAS的分布式计算机联锁系统研究
- 2022java学习路线总结—纯干货分享
- 【附源码】计算机毕业设计SSM小区物业管理系统
- python----four
- FFmpeg多媒体文件格式探测
- oracle数据库进程pmon,【案例】Oracle进程异常 pmon和LISTENER进程负载均比较高的解决办法...
- Debian11之 RKE2 部署 K8S 集群
- 服务器rd 组件的修复,联想 ThinkServer RD340 服务器不触发之维修篇