def roll_dice(number_of_sides): #define possible value combinations first_roll = randomint(1, number_of_sides) second_roll = randomint(1, number_of_sides) max_val = number_of_sides * 2 #provide user with max value possible print "Maximum possible value rolled is: " + str(max_val) sleep(1) #simulate thinking user_guess = get_user_guess() if user_guess > max_val: #pervent user from entering invalid guess print "No guessing higher than the maximum possible value!" return else: print "Rolling..." sleep(2) #simulate rolling dice print "The first value is: %d" %first_roll sleep(1) print "Rolling again..." sleep(2) print "The second value is: %d" %second_roll sleep(1) total_roll = first_roll + second_roll print total_roll print "Result..." sleep(1) if user_guess > total_roll: print "Congratulations, you've won!" return else: print "Sorry, you've lost." return
def generateField(): validity = False # a,b are equation constances p is the modular constant while validity == False: a = random.randomint(0, 100000) b = random.randomint(0, 100000) p = primes[random.randomint(0, len(primes) - 1)] infinity = (0, 0) if (4 * a**3 + 27 * b**3 != 0 and a != 2 and b != 3): print("Your generated curve has the equation: y2 = x3 + " + str(a) + "x + " + str(b) + ", with a modular constant of " + str(p)) print(" ") validity = True return [a, b, p, infinity]
def status(): if flask_request.method == 'GET': discounts = Discount.query.all() app.logger.info(f"Discounts available: {len(discounts)}") influencer_count = 0 for discount in discounts: if discount.discount_type.influencer: influencer_count += 1 app.logger.info( f"Total of {influencer_count} influencer specific discounts as of this request" ) return jsonify([b.serialize() for b in discounts]) elif flask_request.method == 'POST': # create a new discount with random name and value discounts_count = len(Discount.query.all()) new_discount_type = DiscountType('Random Savings', 'price * .9', None) new_discount = Discount('Discount ' + str(discounts_count + 1), words.get_random(random.randomint(2, 4)), random.randint(10, 500), new_discount_type) app.logger.info(f"Adding discount {new_discount}") db.session.add(new_discount) db.session.commit() discounts = Discount.query.all() return jsonify([b.serialize() for b in discounts]) else: err = jsonify({'error': 'Invalid request method'}) err.status_code = 405 return err
def split_list(lines): global content num = 0 for line in lines: line = line.strip() if not (line.find("@") != -1): continue if MONGO[MONGO_DB][MONGO_USER_COLL].find_one({'_id': line}): continue line_list = line.split("@") username, mailserver = line_list[0], line_list[1] #if mailserver in ["aol.com"]: # continue if username.find(".") != -1: username = username.split(".")[0] #d[mailserver] = d.get(mailserver,0)+1 content = random.choice( [content, content1, content2, content3, content4]) #content = content.format(name=username) #html_content = html_content print("Email send to %s" % line) #html_content = html_content send_mail('kate', 'password123', line, 'Hi ', content) num = num + 1 rtime = random.randomint(240, 400) time.sleep(rtime)
def upload_image_path(instance,filename): # print(instance) # print(filename) new_filename = random.randomint(1,965678743) name, ext = get_filename_ext(filename) final_filename= f'{new_filename}{ext}' return f'products/{new_filename}{final_filename}'
def crossover(agents): offspring = [] for _ in xrange((population - len(agents)) / 2): parent1 = random.choice(agents) parent2 = random.choice(agents) child1 = Agent(in_str_len) child2 = Agent(in_str_len) split = random.randomint(0, in_str_len) child1.string = parent1.string[ 0, split] + parent2.string[split:in_str_len] child2.string = parent2.string[0:split] + parent1.string[ split:in_str_len] offspring.append(child1) offspring.append(child2) agents.extend(offspring) return agents
def test_build_coder(): """Test the build coder method in ps4.py""" shift = random.randomint(1, 27) coder = build_coder(shift) self.assertTrue(isinstance(coder, dict)) random_letter = random.choice(string.letters[:25]) self.assertEqual(coder[random_letter], chr(ord(random_letter) + shift))
def choose_random(self, root, N): # Total number of Nodes # Probability of choosing root = 1/N # Probability of choosing left child = Left_SIZE * 1/N # Probability of choosing right child = RIGHT_SIZE * 1/N # Total probability = 1/N (1 + LEFT_SIZE + RIGHT_SIZE) probability_dict = \ { root.left.size / N : root.left, root.right.size / N : root.right, 1/N : root } probT = (1 + root.left.size + root.right.size) / N # Roll the dice now choice = random.randomint(0,probT) # This is to sort all the probabilities in # increasing order. ordered_p = sorted(probability_dict.keys()) if choice < ordered_p[0]: final = probability_dict[ordered_p[0]] elif choice < ordered_p[1]: final = probability_dict[ordered_p[1]] else: final = probability_dict[ordered_p[-1]] if final == root: return root else: self.choose_random(final, N)
def __init__(cls, *args): """ init Matrix with (m, n) where m - rows, n - columns Matrix(2, 1) [[0, 7]] or with list of rows Matrix([[0, 1], [2 ,3]]) [[0, 1], [2, 3]] """ if len( args ) == 2: # init matrix with (m, n) m rows with n random numbers(0-10) self.rows = [[random.randomint(0, 10) for n in range(args[1])] for m in range(args[0])] self.m = args[0] self.n = args[1] elif len(args) == 1: rows = args[0] if any([len(row) != n for row in rows[1:]]): raise MatrixError("inconsistent row length") self.m = len(rows) self.n = len(rows[0]) self.rows = args[0] else: raise MatrixError( 'Init matrix with (m, n):rows, columns or [[1,2], [2, 4]]')
def pick_a_mac_address(): mac_address_list = './mac_addrs.log' r = open(mac_address_list, 'r') menu_interface_selection(lines, "Select a MAC Address") choice = int(raw_input("Select MAC by number: ")) chosen_mac = stack[counter] print "Randomizing last two digits of MAC" array_letters = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ] array_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] rand_letter = random.choice(string.array_letters) rand_number = random.randomint(integer.array_numbers) chars = chosen_mac.split('.') new_mac = "{}.{}.{}.{}.{}.{}{}".format(str(char[0]), str(char[1]), str(char[2]), str(char[3]), str(char[4]), str(rand_letter), str(rand_number)) print "Your new MAC address to change to is: {}".format(str(new_mac)) time.sleep(1) change_mac_cmd = "macchanger -m {} {}".format(str(new_mac), str(device)) return change_mac_cmd
def mutateColor(rgbTuple = None): """creates a random color based on provided tuple""" if rgbTuple is None: x = [random.randomint(0,255) for x in range(3)] return tuple(x) amounts = [] amount = [0,0,0] rgbList = list(rgbTuple) fullMutate = settings.getValue('COLORS', 'allChange', 1) changeMagnitude = settings.getValue('COLORS', 'magnitude', 1) if changeMagnitude != 0: for value in amount: while value is 0: value = random.randint(-changeMagnitude,changeMagnitude) amounts.append(value) ''' decides whether or not each value changes #0-2: single color change - (0-r, 1-g, 2-b) #3-5: double color change - (3-rg, 4-rb, 5-gb) #6-8: single color change - (6-r, 7-g, 8-b) #9-?: triple color change - (9-? - rgb) ''' mutate = random.randint(0,8+fullMutate) if (mutate >= 0) and (mutate <= 2): rgbList[mutate] += amounts[mutate] elif (mutate >= 6) and (mutate <= 8): rgbList[mutate-6] += amounts[mutate-6] elif (mutate == 3) or (mutate == 4): rgbList[0] += amounts[0] elif (mutate == 3) or (mutate == 5): rgbList[1] += amounts[1] elif (mutate == 4) or (mutate == 5): rgbList[2] += amounts[2] elif (mutate >=9): rgbList = [rgbList[x]+amounts[x] for x in range (3)] rgbList = [0 if value < 0 else 255 if value > 255 else value for value in rgbList] return tuple(rgbList)
def random_msg(): date = random_date() sys.stderr.write('date: %s\n' % date) return met_hydro.MetHydro31( source_mmsi=random.randomint(100000, 999999999), lon=random.randint(-180000, 180000) / 1000., lat=random.randint(-90000, 90000) / 1000., pos_acc=random.choice(0, 1), day=date.day, hour=date.hour, minute=date.minute, wind=random.randint(0, 127), gust=random.randint(0, 127), wind_dir=random.randint(0, 360), gust_dir=random.randint(0, 360), air_temp=random.randint(-600, 60) / 10., humid=random.randint(0, 101), dew=random.randint(-200, 501) / 10., air_pres=random.randint(800, 1201), air_pres_trend=random.choice((0, 1, 2, 3)), vis=random.randint(0, 127) / 10., wl=random.randint(-100, 300) / 10., wl_trend=random.choice((0, 1, 2, 3)), cur_1=random.randint(0, 251) / 10., cur_dir_1=random.randint(0, 360), cur_2=random.randint(0, 251) / 10., cur_dir_2=random.randint(0, 360), cur_level_2=random.randint(0, 31), cur_3=random.randint(0, 251) / 10., cur_dir_3=random.randint(0, 360), cur_level_3=random.randint(0, 31), wave_height=random.randint(0, 251) / 10., wave_period=random.randint(0, 60), wave_dir=random.randint(0, 360), swell_height=random.randint(0, 251) / 10., swell_period=random.randint(0, 60), swell_dir=random.randint(0, 360), sea_state=random.choice(met_hydro.beaufort_scale.keys()), water_temp=random.randint(-100, 501) / 10., precip=random.choice(met_hydro.precip_types.keys()), salinity=50.1, ice=random.choice(0, 1, 3))
def create_activities(mission, instance): #map = PlayerActivityType.objects.get(type='map') #open_ended = PlayerActivityType.objects.get(type='open_ended') #activity_types = (single_res, multi_res, map, open_ended,) def create_player_activity(type): kwargs = dict( creationUser=random.choice(instance.curators.all()), mission=mission, points=random.randint(1, 100), type=type, ) activity = PlayerActivity.objects.create(**kwargs) for l in instance.languages.values_list('code', flat=True): trans = activity.translate(l) trans.name = random_words(l)[:50] trans.question = random_words(l, paragraph=True)[:50] trans.instructions = random_words(l)[:255] trans.addInstructions = random_words(l)[:255] activity.save() return activity multi_res_type = PlayerActivityType.objects.get(type='multi_response') multi_res_activity = create_player_activity(type=multi_res_type) for x in range(10): create_multi_response_activity(multi_res_activity, instance) print "MultiResponse PlayerActivity: %s" % activity.pk multi_res_activity.save() single_res_type = PlayerActivityType.objects.get(type='single_response') single_res_activity = create_player_activity(type=single_res_type) print "Single Response PlayerActivity: %s" % activity.pk for x in range(random.randomint(3, 5)): create_single_response_activity(multi_res_activity, instance) activity.save()
async def chose_random(mess, message): mess.pop(0) if len(mess) == 0: await client.send_message(message.channel, "please add something to chose from") return random.seed() a = random.randomint(0, len(mess) - 1) await client.send_message(message.channel, 'I picked: ' + mess[a])
def shoutout(): chance = random.randomint(1,2) if (chance == 1): print('Your favorite youtuber just \nnoticed one of your comments and decided to shout you out') print('You gain 200 subscribers') youtuber['subscribers'] = youtuber['subscribers']+200 else: return
def what_attacker_type(self, attacker_types): """ Probability distribution over set of attacker types. """ number_of_attacker_types = len(attacker_types) self.attacker_type = random.randomint(1, 0, len(attacker_types)) return self.attacker_type
def weighted_choice(value_list, weight_list): counter = 0 sum_weight = sum(weight_list) random_weight = random.randomint(0, sum_weight) for i, weight in enumerate(weight_list): if random_weight >= counter: counter += weight else: return val_list[i]
def generate_private_key(n=8): w = [ran.randint()] for i in range(n - 1): w.append(ran.randomint(sum(w) + 1, sum(w) * 2)) q = w.pop(-1) w = tuple(w) r = generateCoprime(q) return (w, q, r)
def full_matrix(): Matrix = [] for index in range(DISCHARGE): String = [] for j_ind in range(DISCHARGE): String.append(randomint(MODULE)) Matrix.append(String) return Matrix
def mkdir_list(input): list = [] for count in input: # 0から100の数値をランダムで格納 data = random.randomint(0, 100) list.append(data) # ランダムに格納されたリストの中身を表示する print list
def prims(maze): startNode = [random.randomint(0,SIZE-1),random.randomint(0,SIZE-1), None] maze[startNode[0],startNode[0]] = START neighbors = [] for x in range(-1,1): for y in range(-1,1): if x == 0 and y == 0 or x != 0 and y != 0: continue # in bounds if(startNode[0] + x < SIZE or startNode[1] + y < SIZE): if maze[startNode[0] + x][startNode[1] + y] == '.': continue neighbors.append([startNode[0], startNode[1]]), lastNode = None while(neighbors): randomNode = neighbors.remove(random.randomint(0,len(neighbors)))
def __init__(self, roomnumber=-1): self.number = GenericItem.number GenericItem.number += 1 World.items[self.number] = self if roomnumber == -1: self.roomnumber = random.randomint(0, 2) ###fixme else: self.roomnumber = roomnumber self.farbe = random.choice(["rot", "blau", "gruen"]) self.eigen = random.choice(["gross", "klein", "stinkig"])
def flip_coin(self, n): '''Flip a coin n times''' results = [] for i in range(0, n): flip = random.randomint(0, 1) # Heads is equivalent to 1, tails to 0 if flip == 0: results.append('T') else: results.append('H')
def main(): mininum=raw_input("What is the minimum number?:") maximum=raw_input("What is the maximum number?:") print "I'm thinking of a number from {} to {}.".format(int(minimum),int(maximum)) g=raw_input("What do you think it is?:") n=random.randomint(int(minimum),int(maximum)) print "The target was {}".format(int(n)) print "Your guess was {}".format(int(g)) if g == n print "You guessed right! You must be psychic!"\
def stat_roll(): ######needs sorter and total = 0 rolls = [] for i in range (4): die = random.randomint(1-6) rolls.append(die) print (rolls) sort(rolls) total = sum(die[0,2]) print (rolls) print (total) return total
def crawlDownTree(starterNode): # print "CRAWLING" reachedNewNode = False currNode = starterNode url = '' # For every othe rcase: while True: # Restart crawl down if a site is off topic. if currNode.offTopic: currNode = starterNode else: startOver = False useLinks = True # You must treat search query pages specially if currNode.isQuery: if random.random() < PROBABILITY_RELATED_QUERY: useLinks = False # In both cases, you may draw from traditional links. # This includes traditional links or search results: if useLinks: index = random.randint(0, len(currNode.links) - 1) if currNode.links[index][1] == None: reachedNewNode = True newNode = Node() newNode.isQuery = False currNode.links[index][1] = newNode url = currNode.links[index][0] if startOver: currNode = starterNode else: currNode = currNode.links[index][1] else: index = random.randomint(0, len(currNode.relatedQueries) - 1) if currNode.relatedQueries[index][1] == None: reachedNewNode = True newNode = Node() newNode.isQuery = True currNode.relatedQueries[index][1] = newNode url = currNode.relatedQueries[index][0] startOver = (regexValidation.search(url) is not None) if startOver: currNode = starterNode else: currNode = currNode.relatedQueries[index][1] if reachedNewNode: break currNode.hasNotBeenRead = True return url, currNode
def create_provider_randomly(): brand_list = parameters.CloudParameters.brand region_list = parameters.CloudParameters.region os_list = parameters.CloudParameters.operating_system provider_list = [] for brand in brand_list: provider = Provider() provider.brand = brand for region in region_list: for os in os_list: server = Server() server.os = os server.region = region server.cpu = random.randomint(4, 32) server.ram = random.randomint(32, 256) server.hdd_storage = random.randomint(1024, 10240) server.ssd_storage = random.randomint(1024, 10240) provider.servers.append(server) provider_list.append(provider) return provider_list
def shuffle(self, list): rng = random.randomint() n = list.Count while n > 1: n = n-1 k = rng.Next(n + 1) value = list[k] list[k] = list[n] list[n] = value return list
def takeSnap(): number = random.randomint(1, 100) video_object = cv2.VideoCapture(0) result = True print(result) while (result): ret, frame = video_object.read() img_name = "img" + str(number) + ".png" cv2.imwrite(img_name, frame) start_time = time.time() result = False return img_name print('snapshot taken')
def getNormalMatrixAddress(shape,n): """Throw normal""" limit=4 std=2 address=[] center=[] for axi in shape: center.append(r.randomint(0,axi-1)) address.append(center) c=[] x=0 for axi in shape: if axi<=limit: c.append(np.random.randint(0,axi-1,n-1)) else: c.append(np.random.normal(center[x],std,n-1)) x+=1
def guess_the_num(number): #TODO: use random.randint to get a number between 1 and 20 number = random.randomint(1,20) #TODO: ask user to input their guess response = input("What number do you guess?") #TODO: loop to keep giving the player three guesses until they've guessed correctly tries = 0 while tries == 3: tries += 1 if response >= number: print("Guess lower") elif response <= number: print("Guess higher") else: print("You've got it!") print(tries)
def fuzzer(maxlength=1024,t = str): if t == str: string_length = int(random.random() * maxlength) out = "" for i in range(0, string_length): out += chr(int(random.random() * 96 + 32)) elif t == int: out = random.randomint(0,maxlength) elif t == float: out = random.random() elif t == list: #nesting not supported #random list #recursive length = random.random * maxlength gentypes = [random.choice(str,int,float) for i in range(length)] out = [fuzzer(maxlength,ty) for I,ty in zip(length,gentypes)] return out
def mutate(self): """carries out one mutation""" probN=random.random() if probN < 0.001: pet=Petal(random.randomint(0, 1e9)) pet.mutate() self.petals.append(pet) else: pet=random.choice(self.petals) pet.mutate() if pet.prob < 0.01: self.petals.remove(pet) probSum=0 for pet in self.petals: probSum+= pet.prob probSum=1/probSum for pet in self.petals: pet.prob*=probSum
def walk(self): for node in self.table: node.freq_to_prob() start_index = random.randomint(0, len(self.starts) - 1) starter = self.starts[start_index] go = True final_string = starter + " " hash_val = hash(starter) hash_val = hash_val % self.size while go: prob_index = random.random() prob_sum = 0 for key, value in self.table[hash_val].keys.items(): prob_sum += value if prob_sum >= prob_index: final_string += key + " " next_word = key break hash_val = hash(next_word) hash_val = hash_val % self.size
def AddItem(self, item): ItemEntry = self.Inventory.get(item["name"], None) IsItemUnique = item.get("unique", False) if item["unique"]: if ItemEntry == None: self.Inventory[item["name"]] = item print("Added item to inventory: " + item["name"]) print() return True else: #User already has unique item, so return False to notify this return False else: #The item we're adding is not unique, so append some random numbers to the key in order to prevent KeyErrors #Probably not the best way to tackle the problem, but cheap self.Inventory[item["name"] + string(random.randomint(1000, 9999))] = item print("Added item to inventory: " + item["name"]) print() return True
def mutateColor(rgbTuple=None): """creates a random color based on provided tuple""" if rgbTuple is None: x = [random.randomint(0, 255) for x in range(3)] return tuple(x) amounts = [] amount = [0, 0, 0] rgbList = list(rgbTuple) fullMutate = settings.getValue('COLORS', 'allChange', 1) changeMagnitude = settings.getValue('COLORS', 'magnitude', 1) if changeMagnitude != 0: for value in amount: while value is 0: value = random.randint(-changeMagnitude, changeMagnitude) amounts.append(value) ''' decides whether or not each value changes #0-2: single color change - (0-r, 1-g, 2-b) #3-5: double color change - (3-rg, 4-rb, 5-gb) #6-8: single color change - (6-r, 7-g, 8-b) #9-?: triple color change - (9-? - rgb) ''' mutate = random.randint(0, 8 + fullMutate) if (mutate >= 0) and (mutate <= 2): rgbList[mutate] += amounts[mutate] elif (mutate >= 6) and (mutate <= 8): rgbList[mutate - 6] += amounts[mutate - 6] elif (mutate == 3) or (mutate == 4): rgbList[0] += amounts[0] elif (mutate == 3) or (mutate == 5): rgbList[1] += amounts[1] elif (mutate == 4) or (mutate == 5): rgbList[2] += amounts[2] elif (mutate >= 9): rgbList = [rgbList[x] + amounts[x] for x in range(3)] rgbList = [ 0 if value < 0 else 255 if value > 255 else value for value in rgbList ] return tuple(rgbList)
def setup(self): animals = [ 'bear', 'buffalo', 'chick', 'chicken', 'cow', 'crocodile', 'dog', 'duck', 'elephant', 'frog', 'giraffe', 'goat', 'gorilla', 'hippo', 'horse', 'monkey', 'moose', 'narwhal', 'owl', 'panda', 'parrot', 'penguin', 'pig', 'rabbit', 'rhino', 'sloth', 'snake', 'walrus', 'whale', 'zebra' ] for i in range(NUM_ANIMALS): animal = random.choice(animals) x = random.randint(MARGIN, SCREEN_WIDTH - MARGIN) y = random.randint(MARGIN, SCREEN_HEIGHT - MARGIN) dx = random.uniform(-INITIAL_VELOCITY, INITIAL_VELOCITY) dy = random.uniform(-INITIAL_VELOCITY, INITIAL_VELOCITY) self.animal_sprite = arcade.Sprite( "assets/{animal}.png".format(animal=animal), 0.5) self.animal_sprite.center_x = x self.animal_sprite.center_y = y self.animal_sprite.dx = dx self.animal_sprite.dy = dy self.animal_sprite.mass = random.randomint(0, 200) self.animal_list.append(self.animal_sprite)
def addI_currentfile(inFile): print 'Generating Importance value for %s' % str(inFile) outFile = File('localI.las', mode='w', header=inFile.header) outFile.define_new_dimension(name='gps_time', data_type=10, description='gps_time') for dimension in inFile.point_format: dat = inFile.reader.get_dimension(dimension.name) outFile.writer.set_dimension(dimension.name, dat) outFile.pt_src_id = [random.randint(0, 15) for _ in range(len(outFile))] outFile.gps_time = [] for i in range(len(outFile.X)): outFile.importance_value.append(random.randomint(0, 15)) closeLasFile(outFile) return "localI.las"
def __init_field(self): portion_x, portion_y = (self.height + 1) // 2, (self.width + 1) // 2 for i in range(portion_x): for j in range(portion_y): self.static[i][j] = STATIC_NORTH_WALL | STATIC_EAST_WALL | STATIC_SOUTH_WALL | STATIC_WEST_WALL Pacman.unvisited_count = portion_x * portion_y # generator generator_x, generator_y = random.randint(0, portion_x - 2), random.randint(0, portion_y - 2) self.static[generator_x][generator_y] = STATIC_GENERATOR self.static[generator_x][self.width - 1 - generator_y] = STATIC_GENERATOR self.static[self.height - 1 - generator_x][generator_y] = STATIC_GENERATOR self.static[self.height - 1 - generator_x][self.width - 1 - generator_y] = STATIC_GENERATOR # connect regions Pacman.visited = [[False] * 12 for _ in range(12)] Pacman.border_broken = [False] * 4 self.__ensure_connected(random.randint(0, portion_x - 1), random.randomint(0, portion_y - 1), portion_x, portion_y) if Pacman.border_broken[DIRECTION_LEFT] is False: self.static[random.randint(0, portion_x - 1)][0] &= ~STATIC_WEST_WALL if Pacman.border_broken[DIRECTION_RIGHT] is False: self.static[random.randint(0, portion_x - 1)][portion_y - 1] &= ~STATIC_EAST_WALL if Pacman.border_broken[DIRECTION_UP] is False: self.static[0][random.randint(0, portion_y - 1)] &= ~STATIC_NORTH_WALL if Pacman.border_broken[DIRECTION_DOWN] is False: self.static[portion_x - 1][random.randint(0, portion_y - 1)] &= ~STATIC_SOUTH_WALL # generate symmetric field for r in range(portion_x): for c in range(portion_y): n = bool(self.static[r][c] & STATIC_NORTH_WALL) e = bool(self.static[r][c] & STATIC_EAST_WALL) s = bool(self.static[r][c] & STATIC_SOUTH_WALL) w = bool(self.static[r][c] & STATIC_WEST_WALL) has_generator = bool(self.static[r][c] & STATIC_GENERATOR) if (c == 0 or c == portion_y - 1) and random.randint(0, 3) % 4 == 0: if c == 0: w = False else: e = False if (r == 0 or r == portion_x - 1) and random.randint(0, 3) % 4 == 0: if r == 0: n = False else: s = False if r * 2 + 1 == self.height: s = n if c * 2 + 1 == self.width: e = w self.static[r][c] = has_generator | (STATIC_NORTH_WALL if n else STATIC_EMPTY) | (STATIC_EAST_WALL if e else STATIC_EMPTY) | (STATIC_SOUTH_WALL if s else STATIC_EMPTY) | (STATIC_WEST_WALL if w else STATIC_EMPTY) self.static[r][self.width - 1 - c] = has_generator | (STATIC_NORTH_WALL if n else STATIC_EMPTY) | (STATIC_EAST_WALL if w else STATIC_EMPTY) | (STATIC_SOUTH_WALL if s else STATIC_EMPTY) | (STATIC_WEST_WALL if e else STATIC_EMPTY) self.static[self.height - 1 - r][c] = has_generator | (STATIC_NORTH_WALL if s else STATIC_EMPTY) | (STATIC_EAST_WALL if e else STATIC_EMPTY) | (STATIC_SOUTH_WALL if n else STATIC_EMPTY) | (STATIC_WEST_WALL if w else STATIC_EMPTY) self.static[self.height - 1 - r][self.width - 1 - c] = has_generator | (STATIC_NORTH_WALL if s else STATIC_EMPTY) | (STATIC_EAST_WALL if w else STATIC_EMPTY) | (STATIC_SOUTH_WALL if n else STATIC_EMPTY) | (STATIC_WEST_WALL if e else STATIC_EMPTY) self.content[r][c] = self.content[r][self.width - 1 - c] = self.content[self.height - 1 - r][c] = self.content[self.height - 1 - r][self.width - 1 - c] = CONTENT_EMPTY # wrap all generator for r in range(self.height): for c in range(self.width): if self.static[r][c] & STATIC_GENERATOR: self.static[r][c] |= STATIC_NORTH_WALL | STATIC_EAST_WALL | STATIC_SOUTH_WALL | STATIC_WEST_WALL for direction in (DIRECTION_UP, DIRECTION_RIGHT, DIRECTION_DOWN, DIRECTION_LEFT): temp = self.static[(r + DY[direction] + self.height) % self.height][(c + DX[direction] + self.width) % self.width] if direction == DIRECTION_UP: temp |= STATIC_SOUTH_WALL if direction == DIRECTION_RIGHT: temp |= STATIC_WEST_WALL if direction == DIRECTION_DOWN: temp |= STATIC_NORTH_WALL if direction == DIRECTION_LEFT: temp |= STATIC_EAST_WALL self.static[(r + DY[direction] + self.height) % self.height][(c + DX[direction] + self.width) % self.width] = temp # generate players while True: r, c = random.randint(0, portion_x - 1 - 1), random.randint(0, portion_y - 1 - 1) if self.static[r][c] & STATIC_GENERATOR: continue self.content[r][c] |= CONTENT_PLAYER1 self.content[r][self.width -1 - c] |= CONTENT_PLAYER2 self.content[self.height - 1 - r][c] |= CONTENT_PLAYER3 self.content[self.height - 1 - r][self.width - 1 - c] |= CONTENT_PLAYER4 break # generate large fruit while True: r, c = random.randint(0, portion_x - 1 - 1), random.randint(0, portion_y - 1 - 1) if (self.static[r][c] & STATIC_GENERATOR) or (self.content[r][c] & CONTENT_PLAYER1): continue self.content[r][c] |= CONTENT_LARGE_FRUIT self.content[r][self.width -1 - c] |= CONTENT_LARGE_FRUIT self.content[self.height - 1 - r][c] |= CONTENT_LARGE_FRUIT self.content[self.height - 1 - r][self.width - 1 - c] |= CONTENT_LARGE_FRUIT break # generate small fruit for r in range(portion_x - 1): for c in range(portion_y - 1): if (self.static[r][c] & STATIC_GENERATOR) or (self.content[r][c] & (CONTENT_PLAYER1 | CONTENT_LARGE_FRUIT)) or (random.random.randint(0, 2) % 3 != 0): continue self.content[r][c] = self.content[r][self.width - 1 - c] = self.content[self.height - 1 - r][c] = self.content[self.height - 1 - r][self.width - 1 - c] = CONTENT_SMALL_FRUIT self.small_fruit_count += 1 # collect filed information for r in range(self.height): for c in range(self.width): if self.static[r][c] & STATIC_GENERATOR: self.generators.append((r, c)) self.generator_count += 1 for i in range(4): if self.content[r][c] & PLAYER_ID_MASK[i]: self.players.append(PacmanPlayer(r, c)) self.alive_count += 1
countWave = 0 countDance = 0 initDone = False while not rospy.is_shutdown(): # call function to get sensor value port = 1 # Initialize if not initDone: initRobotPosition() initDone = True # Waves when it senses something in front of it // TEST THIS WITH THE NEW FIRMWARE WRAPPER if somethingInFront(): waveHand() # Dances random dance whichDance = random.randomint(1, 3) if whichDance == 1: danceMotionOne() elif whichDance == 2: danceMotionTwo() elif whichDance == 3; danceMotionThree() # sleep to enforce loop rate r.sleep()
def choose_distant_objects(data_set): import random o_b = random.randomint(0, len(data_set))
raise ZeroDivisionError finally: print("We're done") # Oops # We're done ############# # Importing # ############# # imports are done with the 'import' keyword, if 'from' is used then there is no # need to specify the namespace. import random from time import sleep sleep(random.randomint(1, 100)) ############ # File I/O # ############ # File I/O are very easy in python, but there are two methodes that can be # used. We'll see the two and prefer the later. myfile = open(r"./myfile", "w") # "w" to write, the r"" is the path myfile.write("coucou\n") myfile.writelines(["Ahaha\n", "Ohoho\n"]) myfile.close() myfile = open(r"./myfile") # default is read, "r" to do it explicitely print(myfile.readline()) # coucou
txd=0; tyd=0 tx+=txd; ty+=tyd # This part stops Tux from leaving the edges of screen if tx<0: tx=0 if tx>=540: tx=540 if ty<=0: ty=0 if ty>=330: ty=330 # Make the ball chase Tux if bx>=tx: bx=bx-1 else: bx=bx+1 if by>=ty: by=by-1 else: by=by+1 fx = fx-4 if fx<=-10: fx=600; fy=random.randomint(0,370) # Collision Detection (Tux & Fish, Tux & Ball) if fx<=tx+50 and fx>=tx and fy>=ty-30 and fy<=ty+70: toy.play(); fx=600;fy=random.randint(0,370); score+=1 if bx<=tx+40 and bx>=tx-40 and by>=ty-50 and by<ty+60: burp.play(); bx=600; by=-15; lives -=1; tx=280; ty=180 screen.fill(bkcol); screen.blit(tuxsurf,[tx,ty]) screen.blit(fishsurf,[fx,fy]) screen.blit(ballsurf,[bx,by]) font = pygame.font.Font(None,20) text = font.render("Score: "+str(score), 1, (0,0,0)) screen.blit(text,[5,5]) text = font.render("Lives: "+str(lives), 1, (0,0,0))