为游戏存储一个高分榜

# encoding=UTF-8

"""
    为游戏存储最高分
"""


class GameEntry:
    """Represents one entry of a list of high scores."""
    def __init__(self, name, score):
        self._name = name
        self._score = score

    def get_name(self):
        return self._name

    def get_score(self):
        return self._score

    def __str__(self):
        return '({0}, {1})'.format(self._name, self._score)


class Scoreboard:
    """Fixed-length sequence of high scores in nondecreasing order"""
    def __init__(self, capacity=10):
        """initialize scoreboard with given maximum capacity
            all entries are initially None
        """
        self._board = [None] * capacity     # reserve space for future scores
        self._n = 0                         # number of actual entries

    def __getitem__(self, k):
        """return entry at index k"""
        return self._board[k]

    def __str__(self):
        """return string representation of the high scroe list"""
        return '\n'.join(str(self._board[j]) for j in range(self._n))

    def add(self, entry:GameEntry):
        """consider adding entry to high score"""
        score = entry.get_score()

        # does new entry qualify as a high score?
        # answer is yes if board not full or score is higher than last entry
        good = self._n < len(self._board) or score > self._board[-1].get_score()
        if good:
            if self._n < len(self._board):          # no score drops from list
                self._n += 1                        # so overall number increases

            # shift lower scores rightward to make room for new entry
            j = self._n - 1
            while j > 0 and self._board[j-1].get_score() < score:
                self._board[j] = self._board[j-1]
                j -= 1
            self._board[j] = entry


scoreboard = Scoreboard()
for i in range(11):
    s = GameEntry('a', i)
    scoreboard.add(s)

scoreboard.add(GameEntry('a', 5))
print(scoreboard)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值