ucb秋季入门课程设计题目,偶然机会能够做完了非常简单的第一个项目。
收获还是很多的。
URL:https://cs61a.org/proj/hog/
做了这个小项目后,熟悉了python的一些语法
摇色子加上一点规则。
对于高阶函数部分的理解更加深刻了。
对于高阶函数来说,他的调用过程大致如上图所示,对于上面所写的函数,功能
以示例为例子:
第一次调用:是将函数f和函数g传入然后返回了一个能够对参数score1,score2进行迭代的函数
第二次调用(在第一次返回的基础上):返回一个函数 函数参数列表f g 为空
代码
"""CS 61A Presents The Game of Hog."""
from dice import six_sided, four_sided, make_test_dice
from ucb import main, trace, interact
GOAL_SCORE = 100 # The goal of Hog is to score 100 points.
######################
# Phase 1: Simulator #
######################
def roll_dice(num_rolls, dice=six_sided):
"""Simulate rolling the DICE exactly NUM_ROLLS > 0 times. Return the sum of
the 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
sum = 0
tag=0
while num_rolls:
current_num=dice()
if current_num ==1:
tag=True
sum+=current_num
num_rolls-=1
if tag is True:
return 1
else:
return sum
# END PROBLEM 1
def 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.'
# BEGIN PROBLEM 2
#Free Bacon.
# A player who chooses to roll zero dice scores 2 * tens - ones
# or 1 whichever is higher;
# where tens, ones are the digits of the opponent's score
#给定对手分数来计算分数
#规则大体意思 选择丢0色子 则根据对手分数的两位数进行计算
#2*十位-个位和1中更大者会当前加分
tens,ones=score//10,score%10
current_num=2*tens-ones
if current_num>1:
return current_num
else:
return 1
# END PROBLEM 2
def 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 &