mardi 19 novembre 2019

Easy way to compare random results and convert them into "points" on a JSON file in Python

Here is a simplified version of my code:

import json
import random

y = {}
y['red'] = {'name': "red", 'p': 0}
y['blue'] = {'name': "blue", 'p': 0}
y['green'] = {'name': "green", 'p': 0}

with open('y.json', 'w') as f:
    json.dump(y, f)

f = open('y.json')
y = json.load(f)

rr = random.randint(1, 101)
rb = random.randint(1, 101)
rg = random.randint(1, 101)

z = '%s%s%s' % (y['red']['name'], " ", y['red']['p'])
zz = '%s%s%s' % (y['blue']['name'], " ", y['blue']['p'])
zzz = '%s%s%s' % (y['green']['name'], " ", y['green']['p'])


print('\n'.join(sorted([z, zz, zzz], key=lambda x: int(x.split()[-1]), reverse=True)))

with open('y.json', 'w') as f:
    json.dump(y, f)

The 'random'-commands currently have no use, but I want to compare these 3 so that the highest random number adds 3 to 'p', the second-highest 2 to 'p' and the lowest 1 to 'p'.

Example:

if rr = 22; rb = 66; rg = 44

then the output should be:

blue 3
green 2
red 1

So that the values of p in my JASON file are:

y['red'] = {'name': "red", 'p': 1}
y['blue'] = {'name': "blue", 'p': 3}
y['green'] = {'name': "green", 'p': 2}

I know that the JSON file would be overwritten everytime I run the program, but this is just a simplified version.

I also know that I could use if statements for that, but I kinda don't want to because I would have to chain a lot of them and that's just not really pretty and takes a lot of time if I want to add more "colors".

I tried my best to explain my problem, but if there are still any questions please ask me.

Thank you :-)




Aucun commentaire:

Enregistrer un commentaire