- 帖子
- 52
- 精华
- 0
- 积分
- 207
- 阅读权限
- 30
- 注册时间
- 2016-1-15
- 最后登录
- 2016-12-17
|
本帖最后由 manhong2112 于 2016-1-16 22:21 编辑
- def ex1(text):
- i = {}
- for j in text:
- if j in i: i[j] += 1
- else: i[j] = 1
- return sorted(i.items(),key=lambda i: i[1],reverse=True)
- print(ex1("History is his story."))
复制代码 這是練習一- def ex2():
- from random import randint
- from sys import exit
- class Game:
- thrownNumber = 0
- gameRound = 0
- def startNewGame(self):
- self.gameRound += 1
- print("New Game start, Round",self.gameRound)
- self.thrownNumber = randint(3,18)
- def endGame(self,*players):
- for i in players:
- playerScore = 0
- playerScore += i.bet.get("big",0) * 2 if self.thrownNumber >= 11 else 0
- playerScore += i.bet.get("small",0) * 2 if self.thrownNumber < 11 else 0
- playerScore += i.bet.get(str(self.thrownNumber),0) * 10
- i.score += playerScore
- i.bet = {}
- class Player():
- score = 0
- bet = {}
- id = ""
- def __init__(self,id,score = 100):
- self.id = id
- self.score = score
- self.bet = {}
- def addBet(self,type,betScore):
- if self.score - betScore < 0: raise ValueError()
- self.bet[type] = self.bet.get(type,0) + betScore
- self.score -= betScore
- class Computer(Player):
- def addBet(self):
- for i in range(randint(1,5)):
- try:
- betScore = randint(1,int(self.score/randint(1,5)) + 1)
- if randint(0,1):
- super().addBet("big" if randint(0,1) else "small",betScore)
- else:
- super().addBet(str(randint(3,18)),betScore)
- pass
- except ValueError: break
- comp = Computer("Computer")
- player = Player(input("Input Your Name: \n> "))
- game = Game()
- # game main body
- while True:
- game.startNewGame()
- # print(game.thrownNumber)
- # read input
- print("Input 'quit' to end game, input 'end' or leave blank to end input, input as '<type/number> <bet>' to bet")
- while True:
- tmp = input("> ")
- if tmp == "end" or tmp == "": break
- if tmp == "quit": exit(0)
- tmp = tmp.split(" ")
- try: player.addBet(tmp[0],int(tmp[1]))
- except ValueError: print("Over your existing score")
- except IndexError: print("Wrong input, try again")
- comp.addBet()
- print(comp.id," bet ",comp.bet,sep="")
- print(player.id," bet ",player.bet,sep="")
- game.endGame(player,comp)
- print("Number is", game.thrownNumber)
- print(comp.id,"'s score: ",comp.score,sep="")
- print(player.id,"'s score: ",player.score,sep="")
- print("="*24,sep="")
- ex2()
复制代码 不知道為甚麼有時候player的分數會動,而且只出現在一開始
Edit: 似乎在一開始有不知名原因讓電腦的下注寫入到玩家的下注了
Edit: 似乎沒這麼簡單,第一回兩者的下注合在一起了? ! 而且只限於第一回?!!!
Edit: 將繼承去掉後就能正常運作,然而我依然不懂繼承的哪裡弄錯了,都快崩潰啦TAT
Edit: 雖然不太清楚為甚麼,但兩個對象的dict都指向了同一個位址,是因為繼承直接把列表的位址也複製了嗎?也就是說,繼承時子類的東西是直接指向父類?
Edit: 在 __init__ 把dict初始化了, 也沒太大問題了,美化就懶的弄了,就醬子吧!
Edit: 插一句不相關的,能否加個折疊之類的把代碼折起來,免得一大串代碼放在那邊佔空間 |
|