2020 Fall Berkeley CS61A Hog


这里是课程链接(可能需要外网)

前言:最近在跟一些美国四大比较有名的课程,在学习的过程中深切感受到了课程的很多精华需要靠实际的项目去巩固~~~


这是UCB CS61A的一个project ,对初学计算机的人可能有一些困难。建议课程的Textbook和Video都要看,学有余力的话Q&A也是一个非常好的巩固环节。

课程截图:


原创不易,希望大家能动动小指头点个赞,你的鼓励是我持续创作的动力!!!


代码如下:

"""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 ***"k, total, flag = 0, 0, 0while k < num_rolls:number = dice()total += numberk += 1if number == 1:flag = 1if flag == 1:return 1elif flag == 0:return total# 注意这里需要用flag来表示如果骰子里某个是1,就返回1。#但不能写if number = 1,return 1。否则没有掷到num_rools这个数字就返回了。#比如这种情况(2,1,4,3),假如取掷两次,每次掷两个。#则使用flag结果为(2,1)(4,3)相应得分为1,7。#若使用后者,则结果为(2,1)->return 得分1,后面那次结果没有了。# 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 ***"number = 100 - scorepi //= pow(10, number)# 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 min(player_score, opponent_score) == 0:return Falsenumber = max(player_score, opponent_score)while number >= 10:if player_score % number == 0 and opponent_score % number == 0:return Truenumber -= 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 Truereturn 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 ***"# problem5想了很久,错误的原因应该是因为每次的strategy都要从上面定义的play函数# (也就是课程里讲的parent函数)里获取,不能在子函数多次调用take_turn(take_turn里面有strategy这个参数),# 否则每次的strategy都是一样的,可实际上即使你获得了另外一次机会,也不一定会采取相同的策略while True:if who == 0:nam_roils = strategy0(score0, score1)score0 += take_turn(nam_roils, score1, dice)say = say(score0, score1)if score0 >= goal or score1 >= goal:break# 之前上面是return,但底下有一个return,只能用break了if not extra_turn(score0, score1):who = other(who)if who == 1:nam_roils = strategy1(score1, score0)score1 += take_turn(nam_roils, score0, dice)say = 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# problem6的代码写到了problem5中,就是say = say(score0, score1)那两句# 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 is not 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 ***"# 这段代码不会,参考网上的往年cs61a hog做的,主要还是高阶函数不够熟悉def commentary(score0, score1, last_score=last_score, running_high=running_high):if who ==0:if score0-last_score>running_high:print("{0} point(s)! The most yet for Player {1}".format(score0-last_score, who))running_high=score0-last_scorereturn announce_highest(who, last_score=score0, running_high=running_high)elif who ==1:if score1-last_score>running_high:print("{0} point(s)! The most yet for Player {1}".format(score1-last_score, who))running_high=score1-last_scorereturn announce_highest(who, last_score=score1, running_high=running_high)return commentary# 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 8def new_func(*args):new, total = 0, 0# while new < trials_count:# 不知道为什么上面的循环超时或者一些莫名其妙的错误,下面这个for循环可以passfor i in range(trials_count):total += original_function(*args)# new += 1return total / trials_countreturn new_func# 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 ***"# make_averaged(original_function, trials_count=1000):# roll_dice(num_rolls, dice=six_sided):# >> > dice = make_test_dice(3, 1, 5, 6)# >> > averaged_roll_dice = make_averaged(roll_dice, 1000)# >> >  # Average of calling roll_dice 1000 times# >> >  # Enter a float (e.g. 1.0) instead of an integer# >> > averaged_roll_dice(2, dice)max_roll = 0num_of_dice = 10max_number_of_dice = 0while num_of_dice > 0:current_rool = make_averaged(roll_dice, trials_count)(num_of_dice, dice)if current_rool > max_roll:max_roll = current_roolmax_number_of_dice = num_of_dicenum_of_dice -= 1return max_number_of_dice# 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 True:  # 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 10# 如果掷0所得的分数比cutoff大就return0,否则return  num_rollsif free_bacon(opponent_score) >= cutoff:return 0else:return num_rolls# return 6  # Replace this statement# 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 11score_add = free_bacon(opponent_score)score_all = score + score_addresult = extra_turn(score_all, opponent_score)if (bacon_strategy(score=score, opponent_score=opponent_score, cutoff=cutoff, num_rolls=num_rolls) == 0) or result:# 上面这个if语句第一项若不写==0会出错return 0else:return num_rolls# return 6  # Replace this statement# END PROBLEM 11def final_strategy(score, opponent_score):"""Write a brief description of your final strategy.*** YOUR DESCRIPTION HERE ***"""# BEGIN PROBLEM 12return 4 # 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()

参考资料:AdaMeta 之前做过的2018年UCB61A–hog Fall

2020 Fall Berkeley CS61A Hog相关推荐

  1. Fall 2020 Berkeley cs61a Hog Project

    ** Fall 2020 Berkeley cs61a Hog Project ** Fall 2020 的Hog和之前project有些变化,Github找不到,所以分享一下- "&quo ...

  2. Fall 2020 Berkeley cs61a hw01答案

    Fall 2020 Berkeley cs61a hw01答案 from operator import add, subdef a_plus_abs_b(a, b):""&quo ...

  3. 【水一波题解】题解 of University of Central Florida 2020 (Fall) “Practice” Local Programming Contest

    题解 of University of Central Florida 2020 (Fall) "Practice" Local Programming Contest [by_0 ...

  4. 【2020 Fall】哥伦比亚大学最新《机器学习》课程

    点击上方,选择星标或置顶,不定期资源大放送! 阅读大概需要3分钟 Follow小博主,每天更新前沿干货 COMS 4771是一个研究生水平的机器学习入门.本课程涵盖监督机器学习的基本统计原理,以及一些 ...

  5. CS 61A 2020 Fall Disc 02: Higher-Order Functions, Self Reference

    1.1 Write a function that takes in a function cond and a number n and prints numbers from 1 to n whe ...

  6. [python][算法][CS61a]python列表,python抽象数据类型使用练习

    提示:本文内容来源于UCB CS61A 2020 Summer课程,详情请点击CS 61A: Structure and Interpretation of Computer Programs 文章目 ...

  7. 论坛报名 | 从捉迷藏、星际争霸到新一代人工智能:多智能体深度强化学习的理论与实践...

    与6位图灵奖得主和100多位专家 共同探讨人工智能的下一个十年 长按图片或点击阅读原文,内行盛会,首次免费注册 2020年6月21-24日,第二届北京智源大会(官网:https://2020.baai ...

  8. 哈佛CS50撕书教授在家录了一套4K网课,你准备好电话簿了吗?

    点击上方"AI遇见机器学习",选择"星标"公众号 重磅干货,第一时间送达 来自:机器之心 哈佛大学 CS50 2020 秋季课程即将面世,在家也可以共享「撕书教 ...

  9. 知乎高赞回答:走上科研之路,需要培养什么能力?怎样培养这些能力?

    点击上方,选择星标或置顶,不定期资源大放送! 阅读大概需要15分钟 Follow小博主,每天更新前沿干货 文章 | QbitAI 来源 | 生物学霸 国内的各种科研人才,他们到底有什么与众不同之处? ...

  10. 哈佛最受学生欢迎的CS50课程来啦!「撕书教授」在家录了一套4K网课

    点击上方,选择星标或置顶,不定期资源大放送! 阅读大概需要5分钟 Follow小博主,每天更新前沿干货 来自:机器之心 哈佛大学 CS50 2020 秋季课程即将面世,在家也可以共享「撕书教授」Dav ...

最新文章

  1. 《包容的智慧》读后感-包容有多少,拥有就有多少
  2. 沐创密码芯片获奖!中国电子学会年度技术发明一等奖,颁给国产集成电路公司...
  3. guid主分区表损坏怎么办_轻钢龙骨隔墙怎么办?轻钢龙骨隔墙的做法
  4. GetModuleHandle(NULL)获取当前DLL模块基址?
  5. IDEA把Springboot打成可执行jar包,内嵌tomcat 这个可以用
  6. C++11 for区间遍历:vector几种遍历方式
  7. C#编写运行在Linux环境下的采用Mediainfo来获取多媒体文件信息的代码
  8. 用.net core实现反向代理中间件
  9. Linux文本编辑器之vim
  10. vue项目没有router文件夹_Vue路由(vue-router)配置实战——动态路由,重定向,工程非根目录...
  11. php提取ip源码,PHP(源码) 如何获取客户端的IP地址
  12. Java并发:Callable、Future和FutureTask
  13. HDU-1584蜘蛛牌
  14. html元素span,[转载]HTML元素 - span标签 使用介绍
  15. 蜀门 - 青城加点完美攻略
  16. git 出现错误fatal: Unable to create ‘project_path/.git/index.lock‘: File exists.
  17. 麻省理工大学线性代数1806(2)消元法及矩阵消元法 矩阵行变换、列变换 置换矩阵 逆矩阵 如沐春风、如饮甘露、醍醐灌顶的线性代数
  18. 语音信号处理-基础(二): 发声生理、听觉生理与听觉心理
  19. Alpha阶段敏捷冲刺①Scrum 冲刺博客
  20. 关于间皮瘤mesothelioma的相关信息

热门文章

  1. 安徽省考计算机专业知识分值分布,安徽省考行测题型分布和分值
  2. 谷歌Chrome浏览器离线安装包
  3. 解决VS 2017/2019社区版无法登陆的方法
  4. IP地址聚合-路由汇聚
  5. Maven 详解及常用命令
  6. 提供2.4G单色、双色、RGB\RGBW\RGBCW调光LED灯方案
  7. PC端如何跟手机端兼容
  8. python编写自动更换ip工具的代码
  9. CentOS7.2 安装L2TP/IPSec 服务端/客户端 和部分心得 ( libreswan+xl2tpd )
  10. python超简单语音识别