2022 CS61A Hog 项目代码及注意点

本文介绍了2022年CS61A项目的Hog游戏,重点聚焦在phase 1的problem 5,讨论了docstring的重要性和理解难点。
摘要由CSDN通过智能技术生成

phase 1

"""The Game of Hog."""

from dice import six_sided, make_test_dice
from ucb import main, trace, interact
from math import log2

GOAL = 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
    total=0
    rollone=False 
    #这里必须先定义rollone, 否则后面直接引用会出错误:
    #Error: local variable 'rollone' referenced before assignment
    while num_rolls>0:
        result=dice()
        num_rolls-=1
        if result==1:
            rollone=True
        else:
            total=total+result
    if rollone==True:
        return 1
    else:
        return total
    # END PROBLEM 1

def tail_points(opponent_score):
    """Return the points scored by rolling 0 dice according to Pig Tail.

    opponent_score:   The total score of the other player.

    """
    # BEGIN PROBLEM 2
    ones=opponent_score%10
    opponent_score=opponent_score//10
    tens=opponent_score%10
    return 2*abs(tens-ones)+1
    # END PROBLEM 2
def take_turn(num_rolls, opponent_score, dice=six_sided):
    """Return the points scored on a turn rolling NUM_ROLLS dice when the
    opponent has OPPONENT_SCORE points.

    num_rolls:       The number of dice rolls that will be made.
    opponent_score:  The total score of the other player.
    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.'
    # BEGIN PROBLEM 3
    if num_rolls==0:
        return tail_points(opponent_score)
    else:
        return roll_dice(num_rolls,dice) #注意这里并不能省略dice function
        #若省略,则默认dice=six_sided=make_fair_dice(6),生成随机数
        #在test中我们可以看
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值