Python Random Conditions -
i working on first python game before started, working through tutorials , trying modify them. found great "bejeweled" style game trying make changes to, running 1 problem.
the game used 7 different images. when game start, place gems in random order checked make sure wasn't putting ton of same gems next each other.
what wanting increase number of images seventeen. images load correctly, of images want limit number of times appear. example, want gem1 through gem3 more common gem, while others not appear often. thinking of doing using random. have pick number between 1-5. if 1-4 picked, either gem1, gem2, or gem3 picked. if 5 picked, of other gems appear needs follow possiblegems code make sure bunch of same images not appearing next each other. ideas on how make work?
i have included of tutorial code in places important gems. can full source code searching gemgem.py in google.
possiblegems = list(range(len(gemimages))) offsetx, offsety in ((0, -1), (1, 0), (0, 1), (-1, 0)): # narrow down possible gems should put in # blank space don't end putting 2 of # same gems next each other when drop. neighborgem = getgemat(boardcopy, x + offsetx, y + offsety) if neighborgem != none , neighborgem in possiblegems: possiblegems.remove(neighborgem) newgem = random.choice(possiblegems) boardcopy[x][y] = newgem dropslots[x].append(newgem)
code load images
# load images gemimages = [] in range(1, numgemimages+1): gemimage = pygame.image.load('gem%s.png' % i) if gemimage.get_size() != (gemimagesize, gemimagesize): gemimage = pygame.transform.smoothscale(gemimage, (gemimagesize, gemimagesize)) gemimages.append(gemimage)
the simpler way this. basically, instead of creating list [0,1,2]
, repeat each element many times want relative probability.
gem_frequency = [10, 8, 7, 3, 1, 1, 1, 1, 1] gem_lists = [] index, gf in enumerate(gem_frequency): gem_lists.append([index] * gf) gem_prob = chain(*gem_lists) gem_prob [0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,3,3,3,4,5,6,7,8] len(gem_prob) 33 random.choice(gem_prob) 0 1 0 3 1 3 8 0 2 4
so, entry 2 listed frequency 10. should appear 10 times entry 8 (which has frequency of 1). total weights these 33, , 0 chosen approximately 10/33 of time.
if list gets long, might consume lot of memory, sufficient.
or use weighted choice this:
Comments
Post a Comment