def __init__(self): super().__init__("Kobold", rdi(5, 7), 17, 8) if self.lvl == 6: self.hp += rdi(5, 8) self.dmg += 5 elif self.lvl == 7: self.hp += rdi(6, 9) # ( ͡° ͜ʖ ͡°) self.dmg += 7 self.maxHP = self.hp
def __pseudo_aux(len1: int, len4: int, len42: int, len43: int) -> int: # returns a random pointer using a non-linear probability aux = rd() if aux < 0.5: return rdi(0, len4) elif aux < 0.75: return rdi(0, len4) + len4 elif aux < 0.90: return rdi(0, len4) + len42 else: return min(rdi(0, len4) + len43, len1)
def cross_two_point(parent1: list, parent2: list) -> list: # creates 2 new elements splitting the 2 parents in 2 points rd1 = rdi(1, len(parent1) - 1) rd2 = rdi(1, len(parent1) - 1) while rd1 == rd2: rd2 = rdi(1, len(parent1) - 1) point1 = rd1 if rd1 < rd2 else rd2 point2 = rd2 if rd1 < rd2 else rd1 return [ parent1[:point1] + parent2[point1:point2] + parent1[point2:], parent2[:point1] + parent1[point1:point2] + parent2[point2:] ]
def generateBlock(self, nb: int) -> None: for i in range(nb * 2): distance = rdi(50, 200) longueur = rdi(40, 70) lp = self.plateformes[-1] self.plateformes.append( Plateforme(lp.x + lp.width, distance, False)) self.plateformes.append( Plateforme(lp.x + lp.width + distance, longueur, True)) return None
def setCasse(): aa = rdi(4, 16) bb = aa % 2 if bb != 0: return 1 else: return 0
def test__add__(self): """ Testing the addition of 2 Unsigned Ints """ U = UInt(4) U.binaire = '0' * 24 + '1' * 8 # Testing input type V = UInt(4) V.binaire = '0' * 16 + '00000001' + '0' * 8 for elem in (1, -1, '', 2, [], {}, 2.5, Mot(1)): with self.assertRaises(TypeError): U + elem # Testing the return type self.assertIsInstance(U + V, UInt) # First testing if this works with same length UInts for i in range(5): k = rdi(1, 5) U = UInt(k) V = UInt(k) S = U.valeur() + V.valeur() if S > U.Maximum.valeur(): with self.assertRaises(OverflowError): U + V else: W = U + V self.assertEqual(W.valeur(), S) # Testing the OverflowError error U = UInt(4) V = UInt(4) U.binaire = '1' * len(U) V.binaire = '0' * (len(V) - 1) + '1' with self.assertRaises(OverflowError): U + V
def enemyAttack(): moveset = rdi(1, 3) if moveset == 1: pass if moveset == 2: pass if moveset == 3: pass
def fun(arg): count = 0 while 1: count += 1 x = rdi(1, 10) u = rand() if u*arg*0.1 <= prob_arr[x-1] : return x, count
def test_hexadecimal(self): """ Testing the hexadecimal attribute's getter """ for i in range(5): # Tests done using the Python builtins functions U = UInt(rdi(1, 15)) Hex = hex(int(U.binaire, 2))[2:].upper() self.assertEqual(U.hexadecimal, (len(U.hexadecimal) - len(Hex)) * '0' + Hex)
def test_valeur(self): """ Testing the valeur method """ # Testing return type self.assertIsInstance(UInt(4).valeur(), int) # Testing with Python builtins for i in range(15): U = UInt(rdi(1, 15)) self.assertEqual(U.valeur(), int(U.binaire, 2))
def take_turn(self): self.roll = rdi(1, 6) if self.roll == 1: self.last_roll = self.roll self.roll = 0 self.turn = 0 return 0 else: self.turn += self.roll self.last_roll = self.roll self.roll = 0 return self.last_roll
def test__mul__(self): """ Testing the multiplication of 2 unsigned ints """ U = UInt(4) # Testing type of params V = UInt(4) for elem in (1, -1, '', 2, [], {}, 2.5, Mot(1)): with self.assertRaises(TypeError): U * elem # Testing the return type self.assertIsInstance(U * V, UInt) # First testing if this works with same length UInts for i in range(5): k = rdi(1, 5) U = UInt(k) V = UInt(k) W = U * V self.assertEqual(W.valeur(), U.valeur() * V.valeur())
async def on_ready(self): print('Eingeloggt.') channel = self.get_channel(740526658699657306) # der Log-Channel # Uhrzeit für den Log aufbauen timeEdit = str(asctime(localtime(time()))) timeEdit = timeEdit.replace(' ', '') timeList = timeEdit.split(' ') timeEdit = timeList[2] timeEdit += ', ' + timeList[1] + '. ' # set status and log await client.change_presence(status=dc.Status.online, activity=dc.Game('seit ' + timeEdit)) await channel.send(':green_circle: Bot jetzt online. Zeit: ' + timeEdit) # Passwort aktualisieren und ausgeben botPw = rdi(0, 999) print(botPw)
def create_2d_texture_random(width, height, d, scaleB, z=None): y_coords = range(height) x_coords = range(width) texel_final = [] if z is None: z = rdi(-10000, 10000) scaleA = 1 half = 0 for y in y_coords: for x in x_coords: pixel = 150 * pnoise3(x * scaleA - half, y * scaleA - half, z, octaves=10, persistence=0.10) pixel += 40 * pnoise3(x * scaleB - half, y * scaleB - half, z, octaves=5, persistence=0.25) pixel += 120 * pnoise3(x * scaleB * 0.6 - half, y * scaleB * 0.6 - half, z, octaves=5, persistence=0.4) texel_final.append(pixel) # transform to a 0..255 range m = abs(min(texel_final)) texel_final = [p + m for p in texel_final] _max = max(texel_final) if _max == 0: _max = 1 coeff = float(d) / _max texel_final = [int(coeff * p) for p in texel_final] return z, texel_final
def test__lt__(self): """ Testing the comparison of 2 unsigned ints """ U = UInt(4) # Testing type of params for elem in (1, -1, '', 2, [], {}, 2.5, Mot(1)): with self.assertRaises(TypeError): U < elem # Testing the return type V = UInt(4) self.assertIsInstance(U < V, bool) # Testing the comparison of same lengths ints k = rdi(1, 5) ints = [UInt(k) for i in range(5)] for i in range(5): for j in range(5): self.assertEqual(ints[i] < ints[j], ints[i].valeur() < ints[j].valeur()) # Axiome : ! a < b and ! b < a => a == b a = UInt(4) b = a self.assertEqual(a < b, False) self.assertEqual(b < a, False)
""" Módulos Builtins são módulo que fazem parte da linguagem e a acompanham na instalação padrão. OBS: abaixo seguem vários exemplos, execute individualmente comentando so demais. """ #################################################################################### # Utilizando alias (apelidos) no módulo import random as rdm print(rdm.random() ##################################################################################### # Utilizando alias (apelidos) na função from random import randint as rdi print(rdi(10, 100)) ###################################################################################### # Ao utilizar um * no import estaremos importando todas as funções de um módulo import random* print(random()))
def myRendererDrawingFunction(surface): #return dirty rects #surface.fill(Color("black")) return [drawRect(surface, Color("black"), old_rect), drawRect(surface, Color("red"), Rect(rdi(0, 700), rdi(0, 500), 12, 12)), drawRect(surface, Color("yellow"), new_rect)]
def genPwd(self, e): dlg = None finalset = [] setL = self.checkbox_letters.GetValue() setN = self.checkbox_numbers.GetValue() setSC = self.checkbox_specialchars.GetValue() setSP = self.checkbox_setperso.GetValue() def setCasse(): aa = rdi(4, 16) bb = aa % 2 if bb != 0: return 1 else: return 0 i = False if setL == 1: finalset += self.chars['letters'] i = True if setN == 1: finalset += self.chars['numbers'] i = True if setSC == 1: finalset += self.chars['specials'] i = True if setSP == 1: tmp = self.combobox_setperso.GetValue().strip() + " " x = re.search(self.pattern_setperso, tmp) if x is not None: tmp.strip() finalset += tmp.split(' ') i = True else: dlg = wx.MessageDialog(self, "La chaîne de caractère semble mal formée. Tous les caractères doivent être séparés par un espace.\nExemple:\n\na b c = OK\na bb c = Not OK", "Recharger l'application", wx.OK|wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() if i: chars_array_length = len(finalset) array_count = chars_array_length - 1 newpwd = '' y = 0 default_size = 8 spin_size = self.spin_nbchars.GetValue() if spin_size > 0: default_size = spin_size tmpcasse = '' for i in range(default_size): y = rdi(0, array_count) z = self.rbcasse.GetSelection() tmpcasse = finalset[y].encode('utf-8') if z == 0: cc = setCasse() if cc == 1: tmpcasse = tmpcasse.upper() elif z == 2: tmpcasse = tmpcasse.upper() newpwd += tmpcasse self.combobox_newpwd.Append(str(newpwd)) self.combobox_newpwd.SetStringSelection(str(newpwd)) else: dlg = wx.MessageDialog(self, "Aucun jeux de caractère n'a été sélectionné. Vous devez en choisir au moins un", "Erreur", wx.OK|wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy()
""" Built-In -> Módulos integrados já intalados no puthon """ #alias (apelidos) para módulos ou funções import random as rmd print(rmd.random()) #Import de todas as funções de um módulo usando * from random import * print(random()) #Importando todo o modulo import random print(random.random()) from random import randint as rdi print(rdi(5, 56)) #Multiplos immports from random import (random, randint, shuffle, choice) print('random:', random()) print('randint:', randint(3, 8)) lista = ['Geek', 'Uniersity', 'Python'] shuffle(lista) print('shuffle:', lista) print('choice:', choice('Uniersity'))
from math import radians from compas.geometry import Box from compas.datastructures import Mesh from compas.datastructures import mesh_transform_numpy from compas.utilities import rgb_to_hex from compas.geometry import Translation from compas.geometry import Rotation from compas_viewers.objectviewer import ObjectViewer viewer = ObjectViewer(activate_selection=True) # make 10 random meshes # with random position and orientation for i in range(10): T = Translation.from_vector([rdi(0, 10), rdi(0, 10), rdi(0, 5)]) R = Rotation.from_axis_and_angle([0, 0, 1.0], radians(rdi(0, 180))) X = T * R box = Box.from_width_height_depth(rdi(1, 3), rdi(1, 3), rdi(1, 3)) mesh = Mesh.from_shape(box) mesh_transform_numpy(mesh, X) viewer.add(mesh, name="Mesh.%s" % i, settings={ 'color': rgb_to_hex((rdi(0, 255), rdi(0, 255), rdi(0, 255))), 'edges.width': 2, 'opacity': 0.7, 'vertices.size': 10, 'vertices.on': True,
# import random print(random()) # importando todo o módulo # Podemos importar todas as funções de um módulo utilizando o * from random import * print(random()) # import random # print(random.random()) # Utilizando alias (apelidos) from random import randint as rdi, random as rdm print(rdi(5, 89)) print(rdm()) # Costumamos a utilizar tuple para colocar multiplos imports de um mesmo módulo from random import (random, randint, shuffle, choice) print(random()) print(randint(7, 17)) lista = ['liniker', 'oliveira', 'jardel'] shuffle(lista) print(lista) print(choice("123456789"))
import turtle as tt from random import choice as rdc from random import randint as rdi c = ["red","blue","indigo","white","orange"] for i in range(rdi(100,200)): tt.left(89) pass tt.forward(i) tt.pensize(i/2) tt.pencolor(c[i%5])
def calculate_hit_points_hard(dice: int, level: int, iterations: int) -> int: result_pool = 0 for _ in range(iterations): result_pool += dice + sum([rdi(1, dice) for _ in range(level - 1)]) return int(result_pool / iterations)
# prefixes px = [ 'Killer', 'Pro', 'Dead', 'Extreme', 'Fire', 'Ice', 'Xtreme', 'Crazy', 'Ultra', 'Toxic', 'Fearless', 'Elite' ] # suffixes sx = [ 'Dragon', 'Lion', 'Ninja', 'Tiger', 'Spider', 'Wolf', 'Python', 'Gorilla', 'Samurai', 'King', 'Ghost' ] names = 0 while names != 100: # choose randoms myppx = ppx[rdi(0, len(ppx) - 1)] mypx = px[rdi(0, len(px) - 1)] mysx = sx[rdi(0, len(sx) - 1)] r = rdi(0, 30) if r < 10: num = str(rdi(0, 100)) elif r == 30: num = '1337' elif r == 29: num = '69' else:
print(rdm.random()) # Utilizando alias (apelidos) para modulos e funcoes from random import randint as rdi print(rdi(5, 89)) # podemos importar todas as funções de um módulo utilizando o * from random import * print(random()) # Importando todo o modulo import random print(random.random()) """ from random import (random as rdm, randint as rdi, shuffle as sff, choice as cho) print(rdi(4, 6)) print(rdm()) numeros = ['10', '2', '3', '4', '5'] sff(numeros) print(numeros) print(cho('Marcos Luiz')) from math import pi print(pi)
async def on_message(self, message): if message.author == client.user: return if message.content.startswith(cmdPrefix + 'wiki '): # Wiki-Seite laden print(message.content) cmd = message.content cmdEnd = cmd[6:] wikiSearch = wiki.search(cmdEnd) wikiSearch = str(wikiSearch[:5]) # schöner machen wikiSearch = wikiSearch.replace("'", '"') wikiSearch = wikiSearch.replace('[', '') wikiSearch = wikiSearch.replace(']', '') # Überschriften schöner machen wikiSum = wiki.summary(cmdEnd, sentences=10) wikiSum = wikiSum.replace('== ', ':white_medium_small_square: **') wikiSum = wikiSum.replace(' ==', '**') wikiSum = wikiSum.replace(''' ''', ''' ''') # unnötig große Zeilenumbrüche ersetzen # Unterüberschriften schöner machen wikiSum = wikiSum.replace('=:white_medium_small_square: ', ':white_small_square: ') wikiSum = wikiSum.replace('''= ''', '\n') # unnötig große Zeilenumbrüche ersetzen try: searchTopics = ':mag_right: Ähnliche Themen: ' + wikiSearch + ' \n' + '▔' * 50 + '\n' + wikiSum # ähnliche Themen vorschlagen except: outp_Content = ( ':x: Tut mir leid, da ist wohl was schief gelaufen. Versuche es nochmal!' ) try: # Embed erzeugen und absenden embed = dc.Embed(colour=dc.Colour(0x52b0ff), description=f'{outp_Content}') embed.set_thumbnail( url= 'https://upload.wikimedia.org/wikipedia/commons/thumb/8/80/Wikipedia-logo-v2.svg/270px-Wikipedia-logo-v2.svg.png' ) embed.set_author(name='Wikipedia Search') embed.set_footer( text='HeyStyx Bot', icon_url= 'https://betaneostyx.files.wordpress.com/2020/07/dcstyxbot-1.png' ) embedMsg = await message.channel.send(embed=embed) # except: # try: # await message.channel.send(outp_Content[:2000] + '\n _Artikel gekürzt._') except: await message.channel.send( ':x: Der Begriff "' + cmdEnd + '" konnte leider nicht gefunden werden. Möglicherweise ist "' + lang + '" die falsche Sprache?') if message.content.startswith(cmdPrefix + 'wiki.lang'): cmd = message.content lang = cmd[11:] wiki.set_lang( cmdEnd) # leider funktioniert try-except hier nicht richtg :( await message.channel.send( ':white_check_mark: Sprache geändert zu "' + lang + '".') if message.content.startswith(cmdPrefix + 'py'): # Befehl aufbauen cmd = message.content cmdEnd = cmd[4:] try: outpCMD = eval(cmdEnd) if outpCMD == 'None' or outpCMD == '': outpCMD = ':warning: Ausgabe ist leer.' else: pass await message.channel.send('```' + str(outpCMD) + '```' ) # als Code-Block ausgeben except: await message.channel.send( ':x: Ungültiger "eval()"-Befehl. Versuche es noch einmal.') if message.content.startswith(cmdPrefix + 'off ' + str(botPw)): # Uhrzeit für den Log aufbauen timeEdit = str(asctime(localtime(time()))) timeEdit = timeEdit.replace(' ', '') timeList = timeEdit.split(' ') timeEdit = timeList[2] timeEdit += ', ' + timeList[1] + '. ' # set status and lo channel = self.get_channel(740526658699657306) await client.change_presence(status=dc.Status.idle, activity=dc.Game('off seit ' + timeEdit)) await message.channel.send( 'Neues Passwort wurde generiert.\n :warning: **BOT WIRD UMPROGRAMMIERT!**' ) await channel.send(':red_circle: Bot jetzt inaktiv. Zeit: ' + timeEdit) # update password and output botPw = rdi(0, 999) print(botPw) if message.content.startswith(cmdPrefix + 'on ' + str(botPw)): # Uhrzeit für den Log aufbauen timeEdit = str(asctime(localtime(time()))) timeEdit = timeEdit.replace(' ', '') timeList = timeEdit.split(' ') timeEdit = timeList[2] timeEdit += ', ' + timeList[1] + '. ' # set status and log channel = self.get_channel(740526658699657306) await client.change_presence(status=dc.Status.online, activity=dc.Game('wieder seit ' + timeEdit)) await message.channel.send( 'Neues Passwort wurde generiert.\n :green_circle: **BOT WIEDER AKTIV!**' ) await channel.send(':blue_circle: Bot wieder online. Zeit: ' + timeEdit) # update password and output botPw = rdi(0, 999) print(botPw)
def dice_drop_low(dice: int) -> int: first_roll = rdi(1, dice) return first_roll if first_roll > 2 else rdi(1, dice)
def lottery(): for i in range(6): yield rdi(1, 40) yield rdi(1, 15)
def test_kernel_instanciation(): for i in range(n): d = Dungeon(rdi(2, 20), rdi(2, 20)) assert d.map.valid()
def __init__(self): super().__init__("Short Sword", "A short sword suitable for beginner knights.", "KNIGHT", 5, rdi(2, 3)) self.ID = "1x00001"
import random as rdm print(rdm.random()) # 2 from random import randint as rdi, random as rdm print(rdi(5, 89)) print(rdm()) # Podemos importar todas as funções de um módulo utilizando o * from random import * # import random -> diferente, pois quando importa * não é necessário usar o nome do modulo separado por ponto print(random()) """ # Costumamos a utilizar tuple para colocar múltiplos imports de um mesmo módulo from random import (random as rdm, randint as rdi, shuffle as shf, choice as chc) print(rdm()) print(rdi(1, 55)) lista = [1, 2, 3, 4] shf(lista) print(lista) print(chc('Hello World'))
from random import randint as rdi from time import sleep from datetime import date # Exercicio 28 print('=' * 20, 'Primeiro exercicio', '=' * 20) pc = rdi(0, 5) # faz o computador sortear unm número print('-=-' * 25) sleep(.5) print('Vou pensar em um número entre 0 e 5, tente advinhar !') sleep(.5) print('-=-' * 25) sleep(.5) jogador = int(input('Em que número em pensei ? ')) # Jogador tenta advinhar print('Processando...') sleep(2) if jogador == pc: print( 'Parabéns, o número {} foi o que eu realmente pensei'.format(jogador)) else: print( 'Infelizmente você errou, eu pensei no número {} e não no {}.'.format( pc, jogador)) # Exercicio 29 print('=' * 20, 'Segundo exercicio', '=' * 20) vel = float(input('Qual a velocidade atual do seu carro? ')) mult = (vel - 80) * 7 if vel > 80: print('Você foi multado, você excedeu o limite de velocidade de 80Km/h') sleep(.3) print('Você deve pagar uma multa no valor de R${:.2f}'.format(mult))
def dice_drop_low_truncated(dice: int, half: int) -> int: first_roll = rdi(1, dice) return first_roll if first_roll > 2 else min(rdi(1, dice), half)