我正在尝试用 PYTHON 编写代码来记录玩骰子游戏'中间'的用户的结果,然后在游戏结束时打印滚动的统计数据,所以基本上我想要打印的是这样的
Game Summary
============
You played 3 Games:
|--> Games won: 0
|--> Games lost: 3
Dice Roll Stats:
Face Frequency
1
2 *
3
4 **
5 *
6 *
7
8 *
9 *
10 **
Thanks for playing!
如果“*”打印的时间是骰子面朝上滚动的话,那么我会继续用这样的东西结束......
Game Summary
============
You played a total of 3 games:
|--> Games won: 1
|--> Games lost: 2
Dice Roll Stats.
Face Frequency
1
2
** 3
4
5
* 6
* 7
**** 8
* 9
10
Thanks for playing!
所以我想做的是垂直排列'*'并与索引值(1,10)相同,而不是总是放在索引值的前面。 这是我的代码:)
die1 = random.randint(1, 10)
dieCount[die1] = dieCount[die1] + 1
die2 = random.randint(1, 10)
dieCount[die2] = dieCount[die2] + 1
die3 = random.randint(1, 10)
dieCount[die3] = dieCount[die3] + 1
dieCount = [0,0,0,0,0,0,0,0,0,0,0]
index = 1
while index < len(dieCount):
print(index)
for n in range(dieCount[index]):
print('*', end='')
index = index + 1
答案 0 :(得分:2)
你可以这样打印,一次整行:
for i, val in enumerate(dieCount[1:], 1):
print('{} {}'.format(i, '*' * val))
答案 1 :(得分:2)
似乎第一个打印(索引)后面会自动添加换行符。试着像打印*的那样:
print(index, end='')
答案 2 :(得分:0)
试试这个:
while index < len(dieCount):
print(index,end ="")
for n in range(dieCount[index]):
print('*', end='')
print()
index = index + 1
答案 3 :(得分:0)
检查my answer to a similar question。
在这里复制:
我创建了一个滚动骰子类,您可以在其中自定义每个滚轴和两侧的骰子数量,以及跟踪滚动。
import random
from collections import defaultdict
class roller():
def __init__(self, number_of_dice=2, dice_sides=6):
self.dice = defaultdict(dict)
for die in range(number_of_dice):
self.dice[die]['sides'] = dice_sides
self.dice[die]['count'] = dict((k,0) for k in range(1, dice_sides+1))
def roll(self, times=1):
print ("Rolling the Dice %d time(s):" % times)
total = 0
for time in range(times):
roll_total = 0
print ("Roll %d" % (time+1))
for die, stats in self.dice.items():
result = random.randint(1, stats['sides'])
roll_total += result
stats['count'][result] += 1
print (" Dice %s, sides: %s, result: %s" % (die, stats['sides'], result))
print ("Roll %d total: %s" % (time+1, roll_total))
total += roll_total
print ("Total result: %s" % total)
def stats(self):
print ("Roll Statistics:")
for die, stats in self.dice.items():
print (" Dice %s, sides: %s" % (die, stats['sides']))
for value, count in stats['count'].items():
print (" %s: %s times" % (value, count))
使用它:
>>> a = roller()
>>> a.roll(4)
Rolling the Dice 4 time(s):
Roll 1
Dice 0, sides: 6, result: 6
Dice 1, sides: 6, result: 3
Roll 1 total: 9
Roll 2
Dice 0, sides: 6, result: 3
Dice 1, sides: 6, result: 3
Roll 2 total: 6
Roll 3
Dice 0, sides: 6, result: 1
Dice 1, sides: 6, result: 6
Roll 3 total: 7
Roll 4
Dice 0, sides: 6, result: 5
Dice 1, sides: 6, result: 4
Roll 4 total: 9
Total result: 31
>>> a.stats()
Roll Statistics:
Dice 0, sides: 6
1: 1 times
2: 0 times
3: 1 times
4: 0 times
5: 1 times
6: 1 times
Dice 1, sides: 6
1: 0 times
2: 0 times
3: 2 times
4: 1 times
5: 0 times
6: 1 times