def combat (player, enemy): player_damage = random.range(*WEAPONS[player['weapon']]) enemy_damage = random.range(*enemy['attack']) player_win = player_damage > enemy['health'] enemy_win= enemy_damage > player['health'] return player_damage, player_win , enemy_damage, enemy_win
def road(self): """ Faut qu'il donne la position de toute les cases du chemin gagnant, la position de MacGyver, la position de l'objectif intermeidaire, et la position de l'objectif final """ start = (random.range(15), random.range(15)) actual_position = start road_finish = False goal_middle_placed = False while road_finish != True: """ --- old model --- future_position = random( # random x for this : ( actual_position[0] - 1 , actual_position[1] + 0 ) , # [X] ( actual_position[0] + 1 , actual_position[1] + 0 ) , # [X][O][X] ( actual_position[0] + 0 , actual_position[1] + 1 ) , # [X] ( actual_position[0] + 0 , actual_position[1] - 1 ) ) # (O actual_position) """ direction = random.random( # random x like this : (+1, +0), # [X] (-1, +0), # [X][O][X] (+0, +1), # [X] (+0, -1)) # (O actual_position) future_position = (actual_position[0] + direction[0], actual_position[1] + direction[1]) if check_point_in_grid(future_position): range = random.range(2, 4) future_position = (actual_position[0] + direction[0] * range, actual_position[1] + direction[1] * range) if check_point_in_grid(future_position): actual_position = future_position # fonction qui retien le tracé ( append(actual_postion) jusqu'a future_position) if random.range(6) > 3: if not goal_middle_placed: # case = middle_goal here define = actual position goal_middle_placed = True else: # case = final_goal here define = actual position road_finish = True
def randomHoles(grid,holeCount=30,seed=-1): if seed == -1: random.seed() else: random.seed(seed) for hole in range(holeCount - 1): curTile = grid.nodes[random.range(0,grid.width-1)][random.range(0,grid.height-1)] hole = rand.range(4-1) while len(curTile.neighbors) < hole: hole = rand.range(4-1) curTile.makeHole(hole)
def move( my_history, their_history, my_score, their_score, ): ''' Arguments accepted: my_history, their_history are strings. my_score, their_score are ints. Make my move. Returns 'c' or 'b'. ''' answerChecker(their_history, colludeNumber, betrayNumber) if len(my_history) < 5: return 'c' else: if (colludeNumber + 5 > betrayNumber): return 'c' elif (colludeNumber < betrayNumber + 5): return 'b' else: guesser = random.range(0, 1, 1) if (guesser == 0): return 'c' if (guesser == 1): return 'b' return 'c'
def generaClave(self, alphabet): clave = "" for x in range(0, 4): x = random.range(len(self.alphabet)) clave += alphabet[x] print(clave) return (clave)
def _generateConsommateurs(self): """ exploite population pour remplir le terrain s'assure que obstacles et posObstacles sont conformes """ if (self.obstacles > 0 and self.obstacles != len(self.__posObstacles)): self.__posObstacles = random.sample(range(self.__area), self.obstacles) if self.population == set([]): self.population = [] pf = [1 for _ in range(self.firmes)] if self.clientPreference < 2: flag = True if self.clientPreference == 2: flag = False _c = [] for x, i in self.population: _c.extend([ x, ] * i) random.shuffle(_c) i = 0 while i < self.__area: if i in self.__posObstacles: self.__terrain.append(None) i += 1 continue klass = _c.pop() _0 = klass(self.clientCost, pf[:], bool(random.range(2))\ if self.clientPreference == 3 else flag, self.clientUtility, self.clientPM) self.__terrain.append(_0) i += 1
def new_game(): global secret_number, low, high, guess_remaining secret_number = random.range(low,high) guess_remaining = int(math.ceil(math.log((high-low+1),2))) print " " print "New game. Range is from ", low + "to ", high print " Number of remaining guesses is", guess_remaining
def onUse(self,targetEntity): if self.cooldown > 0: return self.cooldown = speed targetEntity.hp-=random.range(damage,maxdamage) if targetEntity.hp <= 0: targetEntity.onDie()
def buildMaze(grid,seed=-1): if seed == -1: random.seed() else: random.seed(seed) side = random.range(1) cap = random.range(1) if cap == 1: startM = 0 else: startM = grid.height - 1 if side == 1: startN = 0 else: startN = grid.width - 1 curTile = grid.nodes[n][m] stack = [] pathed = [] stack.append(curTile) pathed.append(curTile) while len(stack) != 0: hasUnpathedNeighbor = False for neighbor in curTile.neighbors: if not neighbor in pathed: hasUnpathedNeighbor = True if hasUnpathedNeighbor: nextTile = random.range(len(curTile.neighbors)-1) while nextTile in pathed: nextTile = random.range(len(curTile.neighbors)-1) index = curTile.neighbors.index(nextTile) if index == 0: nextTile.addHole(2) curTile.addHole(0) elif index == 2: curTile.addHole(2) nextTile.addHole(0) elif index == 1: curTile.addHole(1) nextTile.addHole(3) elif index == 3: curTile.addHole(3) nextTile.addHole(3) else: curTile = pathed.pop(len(pathed)-1)
def naive_match(): Game_matcher.lock.acquire() r = len(Game_matcher.waiting_list) if r < 2: return t1 = random.range(r) c1 = Game_matcher.waiting_list.pop(t1) t2 = random.random(len(r - 1)) c2 = Game_matcher.waiting_list.pop(t2) Game_matcher.lock.release() # outside the lock, since queue is already sync by python Game_matcher.matched_players.put([c1, c2])
def restore(self, teamNum:int): if self.strength > 12 and self.strength < 18: randIncrease = random.range(1, 6) self.strength = self.strength + randIncrease if self.strength > 18: self.strength = 18 print("Team %d Fighter: Vampire's strength has been restored to %d after the victory\n" % (teamNum, self.strength)) else: print("Team %d Fighter: Vampire's strength has been restored to %d after the victory\n" % (teamNum, self.strength)) elif self.strength < 13 and self.strength > 6: randIncrease = random.randrange(1, 6) self.strength = self.strength + randIncrease print("Team %d Fighter: Vampire's strength has been restored to %d after the victory\n" % (teamNum, self.strength)) elif self.strength < 7 and self.strength > 0: randIncrease = random.range(1, 9) self.strength = self.strength + randIncrease print("Team %d Fighter: The vampires health was low after victory. After a blood feast his strength has been restored to %d\n" % (teamNum, self.strength))
def game_loop(): global pause pygame.mixer.music.play(-1) x = display_width * 0.45 y = display_height * 0.8 x_change = 0 thing_x = random.range(0,display_width) thing_y = -600 thing_speed = 7 thing_w = 100 thing_h = 100 gameExit = False while not gameExit: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_left: x_change = -5 if event.key == pygame.K_right: x_change = 5 if event.key == py.game.K_p: pause = True paused () if event.type == pygame.KEYUP: if event.key == pygame.K_left or event.key == pygame.K_right: x_change = 0 print (event) pygame.display.update() clock.tick(60) x += x_change gamedisplay.fill(white) things (thing_x, thing_y,thing_w,thing_h, black) thing_y += thing_speed if x > display_width -car_width or x < 0 : crash() if thing_y > display_height: thing_y = 0 - thing_h thing_x = random.randrange(0,display_width) car (x,y)
def getRandomPipe(): """ Generate positions for two pipes (one bottom straight and one top rotated) for blitting in the screen """ pipeHeight = GAME_SPRITES['pipe'][0].get_height() offset = SCREENHEIGHT/3 y2 = offset + random.range(0,int(SCREENHEIGHT - GAME_SPRITES['base'].get_height() - 1.2 * offset)) pipex = SCREENWIDTH + 10 y1 = pipeHeight - y2 + offset pipe = [ {'x': pipex, 'y': -y1}, #Upper Pipe {'x': pipey, 'y': y2} #Lower Pipe ] return pipe
def __init__(self, filas, columnas, territorio): #Es una matriz con i filas y j columnas self.territorio=np.zeros(filas,columnas, dtype=int) """ Defino la distribucion inicial de los animales. Tengo tres opciones, que haya una presa, que haya un predador, o que el espacio este vacio. No voy a definir cantidades iguales de espacio vacio, presas y predadores. El 50% del espacio va a estar vacio. El 30% van a ser presas, y el 20%Predadores. """ for i in range (len(territorio)): for j in range(len(territorio[,:])): categ=random.range(1,10) if categ<=3: self.territorio[i,j]="Presa" elif categ>5: self.territorio[i,j]=0 else: self.territorio[i,j]="Predador"
def generation(population): #this vector will keep track of our fitness ratings scores = [0]*len(population) #every agent will play in up to this many games trialsLeft = 3 matchupsBag = ShuffleBag(range(1,len(population))) while trialsLeft > 0: playerIndices = [matchupsBag.next(), matchupsBag.next(), \ matchupsBag.next()] (scores[playerIndices[0]],scores[playerIndices[1]],\ scores[playerIndices[2]]) = \ playGame(population[playerIndices[0]],\ population[playerIndices[1]],population[playerIndices[2]]) if len(matchupsBag.values) < 3: trialsLeft -= 1 #now create new population based on scores #best individual automatically gets a pass newPopulation = population[scores.index(max(scores))] weightVectorLen = len(population[0]) while len(newPopulation) < len(population): parentA = population[weighted_random(scores)] parentB = population[weighted_random(scores)] crossPoint = random.randrange(weightVectorLen) child = [parentA[0:crossPoint]].\ extend(parentB[crossPoint:weightVectorLen]) while random.randrange(2) == 0: toMutate = random.range(weightVectorLen) child[toMutate] = max(0, child[toMutate] + random.gauss(0, 0.5)) newPopulation.append(child) print("Generation Complete:") for child in newPopulation: print(child) return newPopulation
async def askme(self, ctx): line_count = 0 rownum = random.range(1, len(csv_reader)) for row in csv_reader: if line_count == 0: await ctx.send(f'The quiz will be set up as ' + ''.join(row)) line_count += 1 elif line_count != rownum: line_count += 1 continue else: await ctx.send( f' The question is "{row[0]}" \n Is the answer \n a) {row[1]}, \n b) {row[2]} \n c) {row[3]} \n d) {row[4]}.\n' ) line_count += 1 answer = input("Please enter a letter \n") if (answer.upper() == str(f'{row[5]}').upper()): await ctx.send("Correct answer\n") time.sleep(1) else: await ctx.send( f"Wrong answer.The correct answer is {row[5]} \n")
def __getitem__(self, idx): label = Image.open(self.images_path[idx]).convert('RGB') label = label.rotate(self.random_rotate[random.randrange(0,4)]) # randomly crop patch from training set crop_x = random.randint(0, label.width - self.patch_size) crop_y = random.randint(0, label.height - self.patch_size) label = label.crop((crop_x, crop_y, crop_x + self.patch_size, crop_y + self.patch_size)) # additive jpeg noise buffer = io.BytesIO() label.save(buffer, format='jpeg', quality=random.range(self.jpeg_quality+1)) input = Image.open(buffer).convert('RGB') if self.transforms is not None: input = self.transforms(input) label = self.transforms(label) return input, label
def _gacha(self, size, lucksack=False): if lucksack: rates = [] for rate_tup in self._gacha_rates: if category in ["6", "5sb", "5off"]: rates.append((rate_tup[0], rate_tup[1] * 2)) else: rates.append(rate_tup) else: if random.range(10000) == 0: return [ "Nope, only <:salt:230150323069517824> here for you, kupo!" ] rates = self._gacha_rates result = [] if size == 11: size -= 1 g5 = weighted_choice(self._gacha_rates_g5) result.append(self._gacha_type_map[g5]) for i in range(size): category = weighted_choice(rates) result.append(self._gacha_type_map[category]) return result
def hash(): hset he name "小明" hset he age "年审" hset he name "喵喵" hgetall he hdel he age hget he name if __name__ =="__main__": a= input("输入:") input_data() import time import random a = int(input("请输入百以内数字:")) c= random.range(0,100) while Ture: if a > c: print("你赢了结果是 %s" % a) time.sleep(2) elif a < c: print("我赢了结果是%s" % c) time.sleep(1) else: print('一样大结果是%s' % a)
def NavSystem(): commdist = random.range(10, 100) return
def generateAccountNumber(): return random.range(1111111111,9999999999)
def instance_word(self): self.current_index = random.range(len(self.wordlist) - 1) self.current = self.wordlist[self.current_index] self.jumble_word = self.jumble(self.current)
def makeRandom(): a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for i in range(10): a[i] = random.range(100) return a
if# code:gbk import random total = 0 num = 0 num_1 = num//total while total ==True: a = input() b = random.range(1,100) if a > b: print ’太大了‘ if a < b: print '太小了' total += 0 else: print 'Bingo' num += 0 s = 0 if s > 1: cotinue s = '请问老师是这样提交的吗?' print s s = 0 s += 0
def string_times_x(input_string, printing_number): i = 0 while i < printing_number: input_string = random.range(input_string) sys.stdout.write(input_string) i = i + 1
def makeRandom2(): a = [0] * 10 for i in range(10): a[i] = random.range(100) return a
def d100(): return random.range(100)
def int rollDef(): int valor = random.range(2,12) return valor
import time # A import random x = (random.range(1, 100)) while x < 100: x = x + 20 time.sleep(0.19) print(x) x = x + 12 time.sleep(0.23) print(x) x = x + 4 time.sleep(0.38) print(x) x = x + 70 time.sleep(0.60) print(x) break print("End of code") def winScore(): userName = input("Enter in you: ") print("Great job \n", userName) user_score = x if x < 100: print("\nYour score is :", x) print("\nyou lose!\n") else:
import random class Vivi: def __init__(self, nome): self.nome=nome dano=0 hp=9 def int atackRapdo() int valor = random.range(1,3) return valor def int atackNomrl(): int valor = random.range(1,5) return valor def int atackForte() int valor = random.range(1,9) return valor def int getDano(): return dano def String getPer(): return per def int rollDef(): int valor = random.range(2,12) return valor def levarDano(int dano):
def random_color(random): r = random.range(0, 256) g = random.range(0, 256) b = random.range(0, 256) return Color(r, g, b)
def fn_range(self, pointer, tape, args): return random.range(args[0], args[1])
def int atackNomrl(): int valor = random.range(1,5) return valor
def chooseC(m): while (True): c = random.range(2, m) if (euclide(c, m) == 1): return c