PROGRAMAÇÃO EM JOGOS DIGITAIS Frutuoso Silva Linguagem de Programação Python --- www.python.org 1 Python Programming Outras características interessantes do Python. Tipagem dinâmica ! As variáveis e parâmetros não têm tipos declarados, logo podem ser associados a objectos de qualquer tipo em tempo de execução. def dobro(x): “Devolve duas vezes x” return x + x print dobro(2) print dobro (“Dois”) 2 Tipagem dinâmica ! As variáveis e parâmetros não têm tipos declarados, logo podem ser associados a objectos de qualquer tipo em tempo de execução. def dobro(x): “Devolve duas vezes x” return x + x print dobro(2) 4 print dobro (“Dois”) DoisDois Python commands/functions ! Compile and Exec # Compile and exec commands code = compile('a = 1+2', '<string>', 'exec') exec code print a # executar uma expressão contida numa string mycode = 'print "Execute the commands inside a string"' exec mycode 3 Python commands/functions ! Compile and Eval # Compile and exec commands code = compile(‘1+2’, '<string>', ’eval') print eval(code) print eval(‘2*3’) Python commands/functions ! Compile and Exec from a file # Read the contents of file with open('code1.py') as f: data = f.read() # Compile and exec from file code_obj = compile(data, 'code1.py', 'exec') exec(code_obj) 4 Python commands/functions ! Compile and Exec from a file # Read the contents of file with open('code1.py') as f: data = f.read() code1.py print "Print and execute this code!" a=2*5 print "a= ", a # Compile and exec from file code_obj = compile(data, 'code1.py', 'exec') exec(code_obj) Print and execute this code! a= 10 Python commands/functions ! Run the code in a file # Other way to run the code of a file execfile('code1.py') Print and execute this code! a= 10 5 Python commands/functions ! Formatted writing - format(value, format_spec) # Formatação de escrita – ex: tabela headers = ["First name", "Last name"] row1 = ["Jose", "Manuel"] row2 = ["Maria", "João"] row3 = ["Luis", "Silva"] tablerows = [headers, row1, row2, row3] fspec = "<15" # Align left fspec1 = ">15" # Align right fspec2 = "^15" # Align center for first,last in tablerows: print(format(first, fspec) + “|” + format(last, fspec2)) Python commands/functions ! Formatted writing - format(value, format_spec) # Formatação de escrita – ex: tabela headers = ["First name", "Last name"] row1 = ["Jose", "Manuel"] First name row2 = ["Maria", "João"] Jose row3 = ["Luis", "Silva"] Mariarow3] tablerows = [headers, row1, row2, Luis | | | | Last name Manuel Joaquina Silva fspec = "<15" # Align left fspec1 = ">15" # Align right fspec2 = "^15" # Align center for first,last in tablerows: print(format(first, fspec) + “|” + format(last, fspec2)) 6 Python commands/functions ! Formatted writing - format(value, format_spec) headers = ["First name", "Last name"] row1 = ["Jose", "Manuel"] =================== First name | Last name row3 = ["Luis", "Silva"] Jose row3] | Manuel tablerows = [headers, row1, row2, Maria | Joaquina fspec = "<15" # Align left Luis | Silva fspec2 = "^15" # Align center =================== row2 = ["Maria", "João"] print “=”*31 for first,last in tablerows: print(format(first, fspec) + “|” + format(last, fspec2)) print “=”*31 Python commands/functions ! Lambda functions # Example 1 def f (x): return x**2 print f(8) g = lambda x: x**2 print g(8) 7 Python commands/functions ! Lambda functions # Example 1 def f (x): return x**2 print f(8) Vantagem: permite criar funções em runtime. g = lambda x: x**2 print g(8) Python commands/functions ! Lambda functions # Example 2 def make_repeater(n): return lambda s: s * n twice = make_repeater(2) third = make_repeater(3) fourth = make_repeater(4) Vantagem: permite criar funções em runtime. print twice('word') print third([2,3]) print fourth(5) 8 Python commands/functions ! Lambda functions # Example 3 lista = [2, 18, 9, 22, 17, 24, 8, 12, 27] # Multiplos de 3 print filter(lambda x: x % 3 == 0, lista) # Valores modificados print map(lambda x: x * 2 + 10, lista) # Soma valores print reduce(lambda x, y: x + y, lista) print sum(lista) Python commands/functions ! Lambda functions # Example 3 lista = [2, 18, 9, 22, 17, 24, 8, 12, 27] print lista [2, 18, 9, 22, 17, 24, 8, 12, 27] # Multiplos de 3 print filter(lambda x: x % 3 == 0, lista) [18, 9, 24, 12, 27] # Valores modificados 46, 28, 54, 44, 58, 26, 34, 64] print map(lambda x: x * 2 + 10, [14, lista) # Soma valores print reduce(lambda x, y: x + y,139 lista) 139 print sum(lista) 9 Python commands/functions ! Lambda functions # Example 4 sentence = 'It is very cool and powerful' words = sentence.split() print words lengths = map(lambda word: len(word), words) print lengths Python commands/functions ! Lambda functions # Example 4 sentence = 'It is very cool and powerful' words = sentence.split() print words lengths = map(lambda word: len(word), words) print lengths ['It', 'is', 'very', 'cool', 'and', 'powerful'] [2, 2, 4, 4, 3, 8] 10 Python commands/functions ! Lambda functions # Example 5 – prime numbers print "Prime numbers < 70" nums = range(2, 70) for i in range(2, 8): nums = filter(lambda x: x == i or x % i, nums) print nums Prime numbers < 70 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67] Python commands/functions ! Functional Programming map() ! filter() ! reduce() ! ! and recursion they are concepts used in functional programming. 11 Python commands/functions ! Funções de introspecção Python commands/functions ! Inspect import os.path import inspect # módulo de introspecção "amigável” print 'Object: ', inspect.getmodule(os.path) print 'Class? ', inspect.isclass(str) # Lista todas as funções que existem em "os.path” print 'Members: ', for name, struct in inspect.getmembers(os.path): if inspect.isfunction(struct): print name, 12 Python commands/functions ! Inspect import os.path Object: <module 'posixpath' from de '/Library/Frameworks/ import inspect # módulo introspecção "amigável” Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'> print 'Object: ', inspect.getmodule(os.path) Class? True print 'Class? ', inspect.isclass(str) Members: _joinrealpath abspath basename commonprefix dirname exists # Lista todasexpandvars as funções quegetctime existem em getsize "os.path” expanduser getatime getmtime isabs isdir isfile islink ismount join lexists normcase normpath realpath relpath print 'Members: ', samefile sameopenfile samestat split splitdrive splitext walk for name, struct in inspect.getmembers(os.path): if inspect.isfunction(struct): print name, 13