Академический Документы
Профессиональный Документы
Культура Документы
Edumvil
__________________________
__________________________
__________________________
Python: _________________________
__________________________
Mdulo Turtle __________________________
M.C. Gabriel Gernimo Castillo __________________________
Laboratorio Edumvil
Universidad Tecnolgica de la Mixteca __________________________
gcgero@gmail.com
__________________________
__________________________
Introduccin __________________________
__________________________
Turtle es una buena opcin para introducir a la programacin a __________________________
los nios, de una forma visual y sencilla.
_________________________
El mdulo Turtle proporciona primitivas grficas tanto __________________________
orientadas a objeto como orientada a procedimientos.
*(!+,-.!/012&!/10&$33'4!5*(('5&367!8(6!'9/&/1:!$14!('0&$(&/1:!&#'!
__________________________
Para trabajar con Turtle se debe tener instalada una versin de
0#'33!;(*<!&#'!4'0=&*%!/5*17!+;!&#$&!;$/30>!&(6!?0/1:!&#'!@6&#*1!5*1A
__________________________
0*3'!/10&'$4!*;!&#'!0#'33>!$0!;*33*B0C
+1!D/14*B0>!0'3'5&!!"#$"%&&'($)*$#+,>!$14!&#'1!/1!&#'!
__________________________
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
)*+,-&!B#'1!&#'!&'(</1$3!*%'107!
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
$14!'1&'(!)*+,-&7!
>>> t.forward(50)
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
46! ! "#$%&'(!)
www.it-ebooks.info
cabeza de la tortuga.
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
)*+,-&!B#'1!&#'!&'(</1$3!*%'107!
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
$14!'1&'(!)*+,-&7!
__________________________
Moving the Turtle
K*?!0'14!/10&(?5&/*10!&*!&#'!
&?(&3'!I6!?0/1:!;?15&/*10!
Ejemplo:
$L$/3$I3'!*1!&#'!L$(/$I3'!t!
B'!M?0&!5('$&'4>!0/</3$(!&*!
?0/1:!&#'!Pen!;?15&/*1!/1!&#'!
turtle!<*4?3'7!N*(!'9$<%3'>!
&#'!forward!/10&(?5&/*1!&'330!&#'!&?(&3'!&*!<*L'!;*(B$(47!8*!&'33!&#'!
>>> t.forward(50)
*(!+,-.!/012&!/10&$33'4!5*(('5&367!8(6!'9/&/1:!$14!('0&$(&/1:!&#'!
0#'33!;(*<!&#'!4'0=&*%!/5*17!+;!&#$&!;$/30>!&(6!?0/1:!&#'!@6&#*1!5*1A
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C __________________________
>>> turtle.forward (-100)
0*3'!/10&'$4!*;!&#'!0#'33>!$0!;*33*B0C
+1!D/14*B0>!0'3'5&!!"#$"%&&'($)*$#+,>!$14!&#'1!/1!&#'!
(-".)/'012!:(*?%>!53/5=!(-".)/'34)++#/5'&6/787!
+1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
__________________________
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
)*+,-&!B#'1!&#'!&'(</1$3!*%'107!
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
$14!'1&'(!)*+,-&7!
>>> t.forward(50)
__________________________
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
Ejemplo:
>>> turtle.backward(50) __________________________
Laboratorio Edumvil. M.C. Gabriel Gernimo C.
46! ! "#$%&'(!)
www.it-ebooks.info
!1)/L
#=1,)()*.09(B0#'%&.()*#)(?1,D".(/)#&3%&'(%&()*.(;.&)."(14(#(;%";-.9
0#'33!;(*<!&#'!4'0=&*%!/5*17!+;!&#$&!;$/30>!&(6!?0/1:!&#'!@6&#*1!5*1A
0*3'!/10&'$4!*;!&#'!0#'33>!$0!;*33*B0C
+1!D/14*B0>!0'3'5&!!"#$"%&&'($)*$#+,>!$14!&#'1!/1!&#'!
(-".)/'012!:(*?%>!53/5=!(-".)/'34)++#/5'&6/787!
_________________________
derecha un ngulo de unidades. Las unidades estn
+*.(3%".;)%1&(?1,D".(4#;%&'(%/(6(3.'"../9
+1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
__________________________
)*+,-&!B#'1!&#'!&'(</1$3!*%'107!
__________________________
$L$/3$I3'!*1!&#'!L$(/$I3'!t!
B'!M?0&!5('$&'4>!0/</3$(!&*!
?0/1:!&#'!Pen!;?15&/*1!/1!&#'!
turtle!<*4?3'7!N*(!'9$<%3'>!
K1,(;#&(/..()*%/(G6H3.'"..(),"&()1()*.(-.4)(1"("%'*)(*.".I
ngulo de orientacin depende del modo de la &#'!forward!/10&(?5&/*1!&'330!&#'!&?(&3'!&*!<*L'!;*(B$(47!8*!&'33!&#'!
&?(&3'!&*!$4L$15'!OP!%/9'30>!'1&'(!&#'!;*33*B/1:!5*<<$14C
>>> t.forward(50) 0
tortuga.
__________________________
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
90 90
Ejemplo: left right
+*.(),")-.(*#/(012.3(41"$#"3(56(7%8.-/9(:(!"#$%(%/(#(/%&'-.( __________________________
>>> turtle.rigth (90) 71%&)(1&()*.(/;"..&<)*.(/0#--./)(.-.0.&)()*#)(;#&(=.(".7"./.&).39(
__________________________
46! ! "#$%&'(!)
>2."?)*%&'(?1,(/..(1&(?1,"(;107,)."(01&%)1"(%/(0#3.(,7(14(7%8.-/@(
www.it-ebooks.info
$*%;*(#".()%&?@(/A,#".(31)/9(B4(?1,(;1,-3(C110(%&(1&()*.(;#&2#/(
#&3()*.(-%&.(3"#$&(=?()*.(),")-.@(?1,($1,-3(=.(#=-.()1(/..()*#)(
)*.(#""1$(".7"./.&)%&'()*.(),")-.D/(7#)*(%/(E,/)(#(=,&;*(14(7%8.-/9(
+*#)D/(/%07-.(;107,)."('"#7*%;/9 __________________________
!1)/L !"#$%&'($%)*(+,")-./( ( 47
www.it-ebooks.info
#=1,)()*.09(B0#'%&.()*#)(?1,D".(/)#&3%&'(%&()*.(;.&)."(14(#(;%";-.9
0#'33!;(*<!&#'!4'0=&*%!/5*17!+;!&#$&!;$/30>!&(6!?0/1:!&#'!@6&#*1!5*1A
0*3'!/10&'$4!*;!&#'!0#'33>!$0!;*33*B0C
+*.(3%".;)%1&(?1,D".(4#;%&'(%/(6(3.'"../9
+1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
)*+,-&!B#'1!&#'!&'(</1$3!*%'107!
K1,(;#&(/..()*%/(G6H3.'"..(),"&()1()*.(-.4)(1"("%'*)(*.".I
__________________________
B'!M?0&!5('$&'4>!0/</3$(!&*!
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
0
__________________________
Ejemplo: 90
left
90
right
>>> turtle.left (90) __________________________
46! ! "#$%&'(!)
__________________________
www.it-ebooks.info
__________________________
!"#$%&'($%)*(+,")-./( ( 47
www.it-ebooks.info
Ejemplo:
+1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
)*+,-&!B#'1!&#'!&'(</1$3!*%'107!
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
__________________________
$14!'1&'(!)*+,-&7!
>>> pos=turtle.pos()
>>> pos
Moving the Turtle
K*?!0'14!/10&(?5&/*10!&*!&#'!
&?(&3'!I6!?0/1:!;?15&/*10!
__________________________
$L$/3$I3'!*1!&#'!L$(/$I3'!t!
(0.00,0.00) B'!M?0&!5('$&'4>!0/</3$(!&*!
>>> turtle.setpos(80,30)
?0/1:!&#'!Pen!;?15&/*1!/1!&#'!
turtle!<*4?3'7!N*(!'9$<%3'>!
&#'!forward!/10&(?5&/*1!&'330!&#'!&?(&3'!&*!<*L'!;*(B$(47!8*!&'33!&#'!
&?(&3'!&*!$4L$15'!OP!%/9'30>!'1&'(!&#'!;*33*B/1:!5*<<$14C
__________________________
>>> turtle.setpos(pos)
>>> t.forward(50)
>>>
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
__________________________
__________________________
46! ! "#$%&'(!)
www.it-ebooks.info
__________________________
(-".)/'012!:(*?%>!53/5=!(-".)/'34)++#/5'&6/787!
+1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
>>> pos=turtle.pos()
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
)*+,-&!B#'1!&#'!&'(</1$3!*%'107!
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
(0.00,0.00)
Moving the Turtle
K*?!0'14!/10&(?5&/*10!&*!&#'!
&?(&3'!I6!?0/1:!;?15&/*10!
__________________________
>>> turtle.setx(10)
$L$/3$I3'!*1!&#'!L$(/$I3'!t!
B'!M?0&!5('$&'4>!0/</3$(!&*!
__________________________
?0/1:!&#'!Pen!;?15&/*1!/1!&#'!
turtle!<*4?3'7!N*(!'9$<%3'>!
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
46! ! "#$%&'(!)
www.it-ebooks.info
__________________________
(-".)/'012!:(*?%>!53/5=!(-".)/'34)++#/5'&6/787!
+1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
)*+,-&!B#'1!&#'!&'(</1$3!*%'107!
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
$14!'1&'(!)*+,-&7!
__________________________
K*?!0'14!/10&(?5&/*10!&*!&#'!
&?(&3'!I6!?0/1:!;?15&/*10!
$L$/3$I3'!*1!&#'!L$(/$I3'!t!
B'!M?0&!5('$&'4>!0/</3$(!&*!
?0/1:!&#'!Pen!;?15&/*1!/1!&#'!
turtle!<*4?3'7!N*(!'9$<%3'>!
&#'!forward!/10&(?5&/*1!&'330!&#'!&?(&3'!&*!<*L'!;*(B$(47!8*!&'33!&#'!
&?(&3'!&*!$4L$15'!OP!%/9'30>!'1&'(!&#'!;*33*B/1:!5*<<$14C
__________________________
>>> t.forward(50)
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
46! ! "#$%&'(!)
Comandos de movimiento
www.it-ebooks.info
__________________________
__________________________
Mover y Dibujar
__________________________
home(): Mueve la tortuga a la posicin original (0,0), y fija la cabeza en su
orientacin inicial _________________________
Ejemplo: __________________________
>>> turtle.heading()
0.0 __________________________
>>> turtle.setheading(90)
>>> turtle.heading() *(!+,-.!/012&!/10&$33'4!5*(('5&367!8(6!'9/&/1:!$14!('0&$(&/1:!&#'!
0#'33!;(*<!&#'!4'0=&*%!/5*17!+;!&#$&!;$/30>!&(6!?0/1:!&#'!@6&#*1!5*1A
__________________________
0*3'!/10&'$4!*;!&#'!0#'33>!$0!;*33*B0C
90.0
__________________________
+1!D/14*B0>!0'3'5&!!"#$"%&&'($)*$#+,>!$14!&#'1!/1!&#'!
(-".)/'012!:(*?%>!53/5=!(-".)/'34)++#/5'&6/787!
+1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
>>> turtle.home()
)*+,-&!B#'1!&#'!&'(</1$3!*%'107!
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
$14!'1&'(!)*+,-&7!
>>> __________________________
&?(&3'!&*!$4L$15'!OP!%/9'30>!'1&'(!&#'!;*33*B/1:!5*<<$14C
>>> t.forward(50)
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
46! ! "#$%&'(!)
www.it-ebooks.info
+1!D/14*B0>!0'3'5&!!"#$"%&&'($)*$#+,>!$14!&#'1!/1!&#'!
(-".)/'012!:(*?%>!53/5=!(-".)/'34)++#/5'&6/787!
__________________________
+1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
__________________________
)*+,-&!B#'1!&#'!&'(</1$3!*%'107!
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
$14!'1&'(!)*+,-&7!
__________________________
&#'!forward!/10&(?5&/*1!&'330!&#'!&?(&3'!&*!<*L'!;*(B$(47!8*!&'33!&#'!
&?(&3'!&*!$4L$15'!OP!%/9'30>!'1&'(!&#'!;*33*B/1:!5*<<$14C
>>> t.forward(50)
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
46! ! "#$%&'(!)
www.it-ebooks.info
>>>
$L$/3$I3'!*1!&#'!L$(/$I3'!t!
B'!M?0&!5('$&'4>!0/</3$(!&*!
?0/1:!&#'!Pen!;?15&/*1!/1!&#'!
turtle!<*4?3'7!N*(!'9$<%3'>!
&#'!forward!/10&(?5&/*1!&'330!&#'!&?(&3'!&*!<*L'!;*(B$(47!8*!&'33!&#'!
&?(&3'!&*!$4L$15'!OP!%/9'30>!'1&'(!&#'!;*33*B/1:!5*<<$14C
__________________________
>>> t.forward(50)
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
46! ! "#$%&'(!)
www.it-ebooks.info
Ejemplo: __________________________
>>> turtle.dot(150,"blue")
>>> turtle.dot(100,"green")
__________________________
>>> turtle.dot(50,"red")
__________________________
*(!+,-.!/012&!/10&$33'4!5*(('5&367!8(6!'9/&/1:!$14!('0&$(&/1:!&#'!
0#'33!;(*<!&#'!4'0=&*%!/5*17!+;!&#$&!;$/30>!&(6!?0/1:!&#'!@6&#*1!5*1A
0*3'!/10&'$4!*;!&#'!0#'33>!$0!;*33*B0C
+1!D/14*B0>!0'3'5&!!"#$"%&&'($)*$#+,>!$14!&#'1!/1!&#'!
(-".)/'012!:(*?%>!53/5=!(-".)/'34)++#/5'&6/787!
>>> turtle.dot()
+1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
)*+,-&!B#'1!&#'!&'(</1$3!*%'107!
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
$14!'1&'(!)*+,-&7!
__________________________
Moving the Turtle
K*?!0'14!/10&(?5&/*10!&*!&#'!
&?(&3'!I6!?0/1:!;?15&/*10!
$L$/3$I3'!*1!&#'!L$(/$I3'!t!
B'!M?0&!5('$&'4>!0/</3$(!&*!
?0/1:!&#'!Pen!;?15&/*1!/1!&#'!
turtle!<*4?3'7!N*(!'9$<%3'>!
&#'!forward!/10&(?5&/*1!&'330!&#'!&?(&3'!&*!<*L'!;*(B$(47!8*!&'33!&#'!
&?(&3'!&*!$4L$15'!OP!%/9'30>!'1&'(!&#'!;*33*B/1:!5*<<$14C
>>> t.forward(50)
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
__________________________
Laboratorio Edumvil. M.C. Gabriel Gernimo C.
46! ! "#$%&'(!)
www.it-ebooks.info
Estado de la Tortuga
__________________________
shown: True/False
__________________________
pendown: True/False
pencolor: Cadena o tupla
__________________________
fillcolor: Cadena o tupla __________________________
pensize: Nmero positivo
speed: Nmero en el rango de 0 a 10 __________________________
resizemode: auto o user o noresize
stretchfactor: Par de nmeros positivos de la forma (x,y) __________________________
outline: Nmero positivo
tilt: Nmero __________________________
+1!D/14*B0>!0'3'5&!!"#$"%&&'($)*$#+,>!$14!&#'1!/1!&#'!
(-".)/'012!:(*?%>!53/5=!(-".)/'34)++#/5'&6/787!
__________________________
+1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
__________________________
)*+,-&!B#'1!&#'!&'(</1$3!*%'107!
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
$14!'1&'(!)*+,-&7!
>>> t.forward(50)
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
46! ! "#$%&'(!)
__________________________
)*+,-&!B#'1!&#'!&'(</1$3!*%'107!
>>> turtle.home()
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
$14!'1&'(!)*+,-&7!
>>> turtle.end_poly()
$L$/3$I3'!*1!&#'!L$(/$I3'!t!
B'!M?0&!5('$&'4>!0/</3$(!&*!
?0/1:!&#'!Pen!;?15&/*1!/1!&#'!
turtle!<*4?3'7!N*(!'9$<%3'>!
__________________________
&#'!forward!/10&(?5&/*1!&'330!&#'!&?(&3'!&*!<*L'!;*(B$(47!8*!&'33!&#'!
&?(&3'!&*!$4L$15'!OP!%/9'30>!'1&'(!&#'!;*33*B/1:!5*<<$14C
>>> p=turtle.get_poly()
>>> t.forward(50)
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
>>> p
((0.00,0.00), (100.00,0.00), (206.07,106.07), (156.83,97.38), (0.00,0.00)) __________________________
>>>
46! ! "#$%&'(!)
www.it-ebooks.info
1. name es el nombre del archivo gif, y shape ser None o no se coloca, __________________________
as se anexa a la lista de formas la imagen del archivo (Nota: La imagen no
rota).
__________________________
__________________________
Ejemplo:
>>> turtle.addshape("raton.gif") __________________________
>>> turtle.shape("raton.gif")
>>> turtle.fd(100) __________________________
>>>
__________________________
PYTHON - TURTLE&PYGAME
F1$($.D--().--()*.(),")-.()1(),"&(-.4)(G6(3.'"../($%)*()*.(41--1$H
%&'(;100#&3I
>>> t.left(90)
Conceptos __________________________
B4(?1,(*#2.&D)(-.#"&.3(#=1,)(3.'"../(?.)@(*.".D/(*1$()1()*%&J(
#=1,)()*.09(B0#'%&.()*#)(?1,D".(/)#&3%&'(%&()*.(;.&)."(14(#(;%";-.9
+*.(3%".;)%1&(?1,D".(4#;%&'(%/(6(3.'"../9
__________________________
B4(?1,(*1-3(1,)(?1,"(-.4)(#"0@()*#)D/(G6(3.'"../(-.4)9
B4(?1,(*1-3(1,)(?1,"("%'*)(#"0@()*#)D/(G6(3.'"../("%'*)9
315 45
__________________________
180
H#'0!I,&#-0J7!&.(&3'!&.(07!3'+&8!1&!761K'37!$(-.02!&-!+$/'!&#'!
Laboratorio Edumvil. M.C. Gabriel Gernimo C.
0'6!21('/&1-0!LM.7&!$7!1+!,-.!&.(0'2!,-.(!<-2,!&-!+$/'!6#'('!,-.(!
$(5!17!%-10&104!N;!2'4(''7!3'+&OC
D#'!t.left(90)!/-55$02!%-10&7!&#'!$((-6!.%!L710/'!1&!7&$(&'2!
<,!%-10&104!&-!&#'!(14#&OG
,-.JK'!$3('$2,!'0&'('2G
0#'33!;(*<!&#'!4'0=&*%!/5*17!+;!&#$&!;$/30>!&(6!?0/1:!&#'!@6&#*1!5*1A
0*3'!/10&'$4!*;!&#'!0#'33>!$0!;*33*B0C
__________________________
+1!D/14*B0>!0'3'5&!!"#$"%&&'($)*$#+,>!$14!&#'1!/1!&#'!
(-".)/'012!:(*?%>!53/5=!(-".)/'34)++#/5'&6/787!
>>> turtle.forward(100)
+1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
)*+,-&!B#'1!&#'!&'(</1$3!*%'107!
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
$14!'1&'(!)*+,-&7! >>> t.forward(50)
>>> turtle.left(90) Moving the Turtle
K*?!0'14!/10&(?5&/*10!&*!&#'!
>>> t.left(90)
__________________________
&?(&3'!I6!?0/1:!;?15&/*10!
$L$/3$I3'!*1!&#'!L$(/$I3'!t!
B'!M?0&!5('$&'4>!0/</3$(!&*!
>>> turtle.forward(100)
?0/1:!&#'!Pen!;?15&/*1!/1!&#'!
turtle!<*4?3'7!N*(!'9$<%3'>!
&#'!forward!/10&(?5&/*1!&'330!&#'!&?(&3'!&*!<*L'!;*(B$(47!8*!&'33!&#'!
&?(&3'!&*!$4L$15'!OP!%/9'30>!'1&'(!&#'!;*33*B/1:!5*<<$14C
>>> t.forward(50)
48! ! "#$%&'(!)
>>> turtle.left(90)
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
__________________________
www.it-ebooks.info
www.it-ebooks.info
+1!D/14*B0>!0'3'5&!!"#$"%&&'($)*$#+,>!$14!&#'1!/1!&#'!
__________________________
__________________________
(-".)/'012!:(*?%>!53/5=!(-".)/'34)++#/5'&6/787!
+1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
)*+,-&!B#'1!&#'!&'(</1$3!*%'107! *(!+,-.!/012&!/10&$33'4!5*(('5&367!8(6!'9/&/1:!$14!('0&$(&/1:!&#'!
0#'33!;(*<!&#'!4'0=&*%!/5*17!+;!&#$&!;$/30>!&(6!?0/1:!&#'!@6&#*1!5*1A
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
0*3'!/10&'$4!*;!&#'!0#'33>!$0!;*33*B0C
$14!'1&'(!)*+,-&7!
import turtle
+1!D/14*B0>!0'3'5&!!"#$"%&&'($)*$#+,>!$14!&#'1!/1!&#'!
>>>
(-".)/'012!:(*?%>!53/5=!(-".)/'34)++#/5'&6/787!
Moving the Turtle
K*?!0'14!/10&(?5&/*10!&*!&#'!
+1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
&?(&3'!I6!?0/1:!;?15&/*10! )*+,-&!B#'1!&#'!&'(</1$3!*%'107!
$L$/3$I3'!*1!&#'!L$(/$I3'!t!
__________________________
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
t=turtle.Pen()
B'!M?0&!5('$&'4>!0/</3$(!&*!
$14!'1&'(!)*+,-&7!
>>>
?0/1:!&#'!Pen!;?15&/*1!/1!&#'!
turtle!<*4?3'7!N*(!'9$<%3'>!
t
&#'!forward!/10&(?5&/*1!&'330!&#'!&?(&3'!&*!<*L'!;*(B$(47!8*!&'33!&#'!
Moving the Turtle
&?(&3'!&*!$4L$15'!OP!%/9'30>!'1&'(!&#'!;*33*B/1:!5*<<$14C
q
K*?!0'14!/10&(?5&/*10!&*!&#'!
>>> t.forward(50) &?(&3'!I6!?0/1:!;?15&/*10!
q=turtle.Pen()
$L$/3$I3'!*1!&#'!L$(/$I3'!t!
>>>
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C B'!M?0&!5('$&'4>!0/</3$(!&*!
?0/1:!&#'!Pen!;?15&/*1!/1!&#'!
turtle!<*4?3'7!N*(!'9$<%3'>!
&#'!forward!/10&(?5&/*1!&'330!&#'!&?(&3'!&*!<*L'!;*(B$(47!8*!&'33!&#'!
&?(&3'!&*!$4L$15'!OP!%/9'30>!'1&'(!&#'!;*33*B/1:!5*<<$14C
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
>>> q.backward(100)
__________________________
46! ! "#$%&'(!)
>>> t.left(90)
www.it-ebooks.info
>>> q.right(90)
46! ! "#$%&'(!)
www.it-ebooks.info
__________________________
0#'33!;(*<!&#'!4'0=&*%!/5*17!+;!&#$&!;$/30>!&(6!?0/1:!&#'!@6&#*1!5*1A
0*3'!/10&'$4!*;!&#'!0#'33>!$0!;*33*B0C
t.forward(100)
+1!D/14*B0>!0'3'5&!!"#$"%&&'($)*$#+,>!$14!&#'1!/1!&#'!
>>>
(-".)/'012!:(*?%>!53/5=!(-".)/'34)++#/5'&6/787!
+1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
)*+,-&!B#'1!&#'!&'(</1$3!*%'107!
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
q.backward(100)
$14!'1&'(!)*+,-&7!
>>>
turtle
Moving the Turtle
__________________________
K*?!0'14!/10&(?5&/*10!&*!&#'!
&?(&3'!I6!?0/1:!;?15&/*10!
t.left(90)
$L$/3$I3'!*1!&#'!L$(/$I3'!t!
>>>
B'!M?0&!5('$&'4>!0/</3$(!&*!
?0/1:!&#'!Pen!;?15&/*1!/1!&#'!
turtle!<*4?3'7!N*(!'9$<%3'>!
&#'!forward!/10&(?5&/*1!&'330!&#'!&?(&3'!&*!<*L'!;*(B$(47!8*!&'33!&#'!
&?(&3'!&*!$4L$15'!OP!%/9'30>!'1&'(!&#'!;*33*B/1:!5*<<$14C
>>> turtle.right(90)
>>> t.forward(50)
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
46! ! "#$%&'(!)
www.it-ebooks.info
+1!D/14*B0>!0'3'5&!!"#$"%&&'($)*$#+,>!$14!&#'1!/1!&#'!
(-".)/'012!:(*?%>!53/5=!(-".)/'34)++#/5'&6/787!
__________________________
+1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
)*+,-&!B#'1!&#'!&'(</1$3!*%'107!
t
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
$14!'1&'(!)*+,-&7!
>>> t.reset();q.reset();turtle.reset()
&?(&3'!I6!?0/1:!;?15&/*10!
$L$/3$I3'!*1!&#'!L$(/$I3'!t!
B'!M?0&!5('$&'4>!0/</3$(!&*!
_________________________
?0/1:!&#'!Pen!;?15&/*1!/1!&#'!
turtle!<*4?3'7!N*(!'9$<%3'>!
&#'!forward!/10&(?5&/*1!&'330!&#'!&?(&3'!&*!<*L'!;*(B$(47!8*!&'33!&#'!
&?(&3'!&*!$4L$15'!OP!%/9'30>!'1&'(!&#'!;*33*B/1:!5*<<$14C
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
>>> t.left(90);t.forward(200);t.left(90);t.forward(100)
>>> t.left(180);q.backward(200);q.down();t.down() *(!+,-.!/012&!/10&$33'4!5*(('5&367!8(6!'9/&/1:!$14!('0&$(&/1:!&#'!
0#'33!;(*<!&#'!4'0=&*%!/5*17!+;!&#$&!;$/30>!&(6!?0/1:!&#'!@6&#*1!5*1A *(!+,-.!/012&!/10&$33'4!5*(('5&367!8(6!'9/&/1:!$14!('0&$(&/1:!&#'!
__________________________
0*3'!/10&'$4!*;!&#'!0#'33>!$0!;*33*B0C 0#'33!;(*<!&#'!4'0=&*%!/5*17!+;!&#$&!;$/30>!&(6!?0/1:!&#'!@6&#*1!5*1A
__________________________
(-".)/'012!:(*?%>!53/5=!(-".)/'34)++#/5'&6/787!
46! ! "#$%&'(!) +1!D/14*B0>!0'3'5&!!"#$"%&&'($)*$#+,>!$14!&#'1!/1!&#'!
+1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
www.it-ebooks.info
(-".)/'012!:(*?%>!53/5=!(-".)/'34)++#/5'&6/787!
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(! +1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
)*+,-&!B#'1!&#'!&'(</1$3!*%'107! *;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
t.forward(100);t.left(225);q.forward(100)
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?! )*+,-&!B#'1!&#'!&'(</1$3!*%'107!
$14!'1&'(!)*+,-&7! +1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
$14!'1&'(!)*+,-&7!
q
Moving the Turtle
turtle
K*?!0'14!/10&(?5&/*10!&*!&#'! Moving the Turtle
q.left(225);turtle.forward(100);turtle.left(225)
&?(&3'!I6!?0/1:!;?15&/*10! K*?!0'14!/10&(?5&/*10!&*!&#'!
$L$/3$I3'!*1!&#'!L$(/$I3'!t! &?(&3'!I6!?0/1:!;?15&/*10!
__________________________
B'!M?0&!5('$&'4>!0/</3$(!&*! $L$/3$I3'!*1!&#'!L$(/$I3'!t!
?0/1:!&#'!Pen!;?15&/*1!/1!&#'! B'!M?0&!5('$&'4>!0/</3$(!&*!
turtle!<*4?3'7!N*(!'9$<%3'>! ?0/1:!&#'!Pen!;?15&/*1!/1!&#'!
&#'!forward!/10&(?5&/*1!&'330!&#'!&?(&3'!&*!<*L'!;*(B$(47!8*!&'33!&#'! turtle!<*4?3'7!N*(!'9$<%3'>!
...
&?(&3'!&*!$4L$15'!OP!%/9'30>!'1&'(!&#'!;*33*B/1:!5*<<$14C &#'!forward!/10&(?5&/*1!&'330!&#'!&?(&3'!&*!<*L'!;*(B$(47!8*!&'33!&#'!
&?(&3'!&*!$4L$15'!OP!%/9'30>!'1&'(!&#'!;*33*B/1:!5*<<$14C
>>> t.forward(50)
>>> t.forward(50)
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
>>>
__________________________
__________________________
46! ! "#$%&'(!)
46! ! "#$%&'(!)
www.it-ebooks.info
www.it-ebooks.info
Con cdigo similar, solo variando el ngulo y la cantidad de repeticiones puedes crear
diferentes tipos de estrellas
__________________________
+1!D/14*B0>!0'3'5&!!"#$"%&&'($)*$#+,>!$14!&#'1!/1!&#'!
(-".)/'012!:(*?%>!53/5=!(-".)/'34)++#/5'&6/787!
_________________________
+1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
>>> t.reset();q.reset();turtle.reset()
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
)*+,-&!B#'1!&#'!&'(</1$3!*%'107!
t
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
$14!'1&'(!)*+,-&7!
>>> q.up();t.up()
Moving the Turtle
K*?!0'14!/10&(?5&/*10!&*!&#'!
&?(&3'!I6!?0/1:!;?15&/*10!
$L$/3$I3'!*1!&#'!L$(/$I3'!t!
B'!M?0&!5('$&'4>!0/</3$(!&*!
__________________________
?0/1:!&#'!Pen!;?15&/*1!/1!&#'!
>>> t.left(90);t.forward(200);t.left(90);t.forward(100)
turtle!<*4?3'7!N*(!'9$<%3'>!
&#'!forward!/10&(?5&/*1!&'330!&#'!&?(&3'!&*!<*L'!;*(B$(47!8*!&'33!&#'!
&?(&3'!&*!$4L$15'!OP!%/9'30>!'1&'(!&#'!;*33*B/1:!5*<<$14C
>>> t.forward(50)
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
>>> t.left(180);q.backward(200);q.down();t.down()
>>> for i in range (1,76): __________________________
t.forward(100);t.left(175);q.forward(100) *(!+,-.!/012&!/10&$33'4!5*(('5&367!8(6!'9/&/1:!$14!('0&$(&/1:!&#'!
0#'33!;(*<!&#'!4'0=&*%!/5*17!+;!&#$&!;$/30>!&(6!?0/1:!&#'!@6&#*1!5*1A
0*3'!/10&'$4!*;!&#'!0#'33>!$0!;*33*B0C 46! ! "#$%&'(!)
*(!+,-.!/012&!/10&$33'4!5*(('5&367!8(6!'9/&/1:!$14!('0&$(&/1:!&#'!
0#'33!;(*<!&#'!4'0=&*%!/5*17!+;!&#$&!;$/30>!&(6!?0/1:!&#'!@6&#*1!5*1A
0*3'!/10&'$4!*;!&#'!0#'33>!$0!;*33*B0C
+1!D/14*B0>!0'3'5&!!"#$"%&&'($)*$#+,>!$14!&#'1!/1!&#'!
__________________________
+1!D/14*B0>!0'3'5&!!"#$"%&&'($)*$#+,>!$14!&#'1!/1!&#'! (-".)/'012!:(*?%>!53/5=!(-".)/'34)++#/5'&6/787!
q.left(175);turtle.forward(100);turtle.left(175)
www.it-ebooks.info
(-".)/'012!:(*?%>!53/5=!(-".)/'34)++#/5'&6/787! +1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(!
+1!E$5!FG!H>!53/5=!&#'!G%*&3/:#&!/5*1!$&!&#'!&*%A(/:#&!5*(1'(! *;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(!
*;!&#'!05(''1!$14!'1&'(!!"#$%&'(!/1!&#'!/1%?&!I*97!8#'1!'1&'(! )*+,-&!B#'1!&#'!&'(</1$3!*%'107!
)*+,-&!B#'1!&#'!&'(</1$3!*%'107! +1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?!
+1!JI?1&?>!*%'1!&#'!&'(</1$3!;(*<!6*?(!%99&64#"6)/,!<'1?! $14!'1&'(!)*+,-&7!
...
$14!'1&'(!)*+,-&7!
q
Moving the Turtle
turtle
Moving the Turtle K*?!0'14!/10&(?5&/*10!&*!&#'!
K*?!0'14!/10&(?5&/*10!&*!&#'! &?(&3'!I6!?0/1:!;?15&/*10!
&?(&3'!I6!?0/1:!;?15&/*10! $L$/3$I3'!*1!&#'!L$(/$I3'!t!
__________________________
B'!M?0&!5('$&'4>!0/</3$(!&*!
>>>
$L$/3$I3'!*1!&#'!L$(/$I3'!t!
B'!M?0&!5('$&'4>!0/</3$(!&*! ?0/1:!&#'!Pen!;?15&/*1!/1!&#'!
?0/1:!&#'!Pen!;?15&/*1!/1!&#'! turtle!<*4?3'7!N*(!'9$<%3'>!
turtle!<*4?3'7!N*(!'9$<%3'>! &#'!forward!/10&(?5&/*1!&'330!&#'!&?(&3'!&*!<*L'!;*(B$(47!8*!&'33!&#'!
&#'!forward!/10&(?5&/*1!&'330!&#'!&?(&3'!&*!<*L'!;*(B$(47!8*!&'33!&#'! &?(&3'!&*!$4L$15'!OP!%/9'30>!'1&'(!&#'!;*33*B/1:!5*<<$14C
&?(&3'!&*!$4L$15'!OP!%/9'30>!'1&'(!&#'!;*33*B/1:!5*<<$14C
>>> t.forward(50)
>>> t.forward(50)
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
K*?!0#*?34!0''!0*<'&#/1:!3/='!&#/0C
__________________________
__________________________
46! ! "#$%&'(!)
46! ! "#$%&'(!)
www.it-ebooks.info
www.it-ebooks.info
Funciones __________________________
__________________________
Funcin de circulo con color invocando a la funcin circulo __________________________
circulo(0, 1, 0, 10)
def circulo(rojo, verde, azul, radio)
circulo(0.5, 1, 0, 50)
_________________________
t.color (rojo, verde, azul)
t.begin_fill() __________________________
t.circle(radio)
t.end_fill() invocado a la funcin cuadro __________________________
cuadro(50) __________________________
Funcin de cuadro
__________________________
def cuadro(tam)
for i in range (1,5): * Realizar una funcin __________________________
t.forward(tam) para cuadros rellenos de
t.left(90) un color * __________________________
Funciones __________________________
__________________________
Funcin de estrella con
16 http://inventwithpython.com/pygame
Invocando a la funcin estrella __________________________
color
!"#"$%& t.color(0, 0.5, 0) _________________________
There are three primary colors estrella(120,
of light: red, True)
green and blue. (Red, blue, and yellow are the
def estrella(tam, con): __________________________
primary colors for paints and pigments, but the computer monitor uses light, not paint.) By
if con == True:
combining different amounts of these three colors you can form any other color. In Pygame, we
t.begin_fill()
represent colors with tuples of three integers. The first value in the tuple is how much __________________________
red is in the
for x in rangecolor.
(1, 19):
An integer value of ! means there is no red in this color, and a value of "## means there is
the maximum amount of red in the color. The second value is for green and the third__________________________
t.forward(tam) value is for
if x % 2 ==blue.
0: These tuples of three integers used to represent a color are often called R G B values.
t.left(175) __________________________
Because you can use any combination of ! to "## for each of the three primary colors, this
else:
means Pygame can draw 16,777,216 different colors (that is, 256 x 256 x 256 colors). However,
t.left(225) __________________________
if try to use a number larger than "## or a negative number, you will get an error that looks like
if con == True: $%&'()**+*,-./0%&.1-2+&+*-%*3'4(/5
t.end_fill() __________________________
For example, we will create the tuple 6!7-!7-!8 and store
Laboratorio it M.C.
Edumvil. in aGabriel
variable
Gernimonamed
C. 9:;<=. With
no amount of red, green, or blue, the resulting color is completely black. The color black is the
absence of any color. The tuple 6"##7-"##7-"##8 for a maximum amount of red, green, and
blue to result in white. The color white is the full combination of red, green, and blue. The tuple
6"##7-!7-!8 represents the maximum amount of red but no amount of green and blue, so the
You can mix the amount of red, green, and blue to form other colors. Here are the RGB values for
__________________________
__________________________
a few common colors:
Referencias __________________________
__________________________
__________________________
_________________________
1. Turtle graphics for Tk - Python v2.7.6 documentation. http://
docs.python.org/2/library/turtle.html . Consultado: 11/febrero/2014 __________________________
2. Python for Kids. Jason R. Briggs. No Starch Press, Inc. 2013 __________________________
__________________________
__________________________
__________________________
__________________________
__________________________
__________________________
__________________________
_________________________
Python
__________________________
M.C. Gabriel Gernimo Castillo __________________________
Laboratorio Edumvil
Universidad Tecnolgica de la Mixteca __________________________
gcgero@gmail.com __________________________
__________________________
__________________________
Introduccin __________________________
__________________________
__________________________
Python es un lenguaje interpretado, con tipos de _________________________
datos dinmicos, multiplataforma (Unix, Linux,
Windows, MacOS), funcional, y tambin orientado __________________________
a objetos.
__________________________
Su pgina oficial www.python.org
__________________________
Es popular para desarrollo de juegos, pero adems
__________________________
para crear desde aplicaciones hasta sitios web
__________________________
__________________________
Nmeros __________________________
>>> 15%6
3 Table 1-2. Comparison Operators
_________________________
>>> a=100.0; b=2.;p=15. Operator Description
>>> (a*b)*(p/100.) < Less than
__________________________
30.0
>>> c=1
<= Less than or equal to
__________________________
>>> while c<=4: print HOLA;c > Greater than
+=1 >= Greater than or equal to __________________________
....
hola
== Equal to
__________________________
!= Not equal to
hola
hola __________________________
hola
>>> __________________________
Caution Be careful with your loops! If you use a condition that is always true, such as 2>1, Python will
keep going round the loop forever. If you do end up in this pickle, hit Ctrl+Z (Ctrl+C for Linux and Mac OS X)
to stop Python in its tracks. Every programmer has been stuck in an infinite loop at least once!
!"#$%&'"(
Tipos de datos __________________________
Los nmeros complejos son aquellos que tienen parte imaginaria. Si __________________________
no conocas de su existencia, es ms que probable que nunca lo vayas a
Python 2.6.1 (r261:67515, Jun 24 >>> c= "hola mundo"
necesitar, por lo que puedes saltarte este apartado tranquilamente. De __________________________
2010, 21:47:49)
hecho la mayor parte de lenguajes de programacin>>> carecen
type (c)de este
tipo, aunque
[GCC sea muy
4.2.1 (Apple Inc.utilizado
build por ingenieros y cientficos en general. _________________________
5646)] on darwin <type 'str'>
En el caso de que necesitis utilizar nmeros complejos, o simplemen-
>>>complex
e = 5.45 __________________________
te tengis
Type "help",curiosidad, os "credits"
"copyright", dir que este tipo, llamado en Python,
ortambin se for
"license" almacena
more usando coma flotante, debido a que estos nme-
>>> type (e) __________________________
ros son una extensin de los nmeros reales. En concreto se almacena
information.
en una estructura de C, compuesta por dos variables
>>>
<typede'float'>
tipo double,
e = 23una de ellas para almacenar la parte real y la otra para la
__________________________
sirviendo
parte imaginaria. >>> __________________________
>>> type(e)
Los nmeros
<type 'int'> complejos en Python se representan de la siguiente
Python para todos
__________________________
forma:
vierte todos los operandos al tipo ms complejo de entre los tipos de
complejo = 2.1 + 7.8j
__________________________
los operandos.
)$&*+,"*&(
!"#$%&'$#()%)*+,#-)&#).+/
Veamos ahora qu podemos hacer con nuestros nmeros usando los
tarlos,
recurrir
Operadores aritmticos
Si no conocis estos operadores es poco probable que vayis a necesi-
operadores por defecto. Para operaciones ms complejas podemos
por
al lo que podis
mdulo math.
obviar esta parte. Si an as tenis curiosidad __________________________
os dir que estos son operadores que actan sobre las representaciones
en binario de los operandos. __________________________
)$&*+,"*&(-+*./#0/.1"(
Por ejemplo,
Operadorsi veis una operacinEjemplo
Descripcin como 3 & 2, lo que estais viendo es __________________________
un and
+ bit a bit entre
Sumalos nmerosrbinarios
= 3 + 211 y #10r (las
es 5representacio-
nes en binario de 3 y 2).
Tipos bsicos
_________________________
- Resta r = 4 - 7 # r es -3
* Multiplicacin r = 2 * 6 # r es 12
__________________________
El resultado de aplicar and bit a bit
Exponente r =a 11 y 10
6 sera
# r entonces el nmero
**
binario
2 ** es 64
__________________________
/ 10, o lo que es lo mismo, 2r en
Divisin decimal
= 3.5 / 2 (el
# primer dgito es 1
r es 1.75
para ambas
//
cifras, mientras
Divisin que elrsegundo
entera es 1 slo para una de ellas).
= 3.5 // 2 # r es 1.0 __________________________
% Mdulo r = 7 % 2 # r es 1
El operador or (|), del ingls o, devuelve 1 si el primer operando es 1 __________________________
o el segundo operando es 1. Para el resto de casos se devuelve 0.
Puede que tengis dudas sobre cmo funciona el operador de mdulo,
y cul es la diferencia entre divisin y divisin entera. __________________________
El operador xor u or exclusivo (^) devuelve 1 si uno de los operandos
esEl1operador
y el otro de
nomdulo
lo es. no hace otra cosa que devolvernos el resto de
la divisin entre los dos operandos. En el ejemplo, 7/2 sera 3, con 1 de
El operador
resto, notmdulo
luego el (~), delesingls
1. no, sirve para negar uno a uno cada
Operadores a nivel de bit
bit; es decir, si el operando es 0, cambia a 1 y si es 1, cambia a 0.
La diferencia entre divisin y divisin entera no es otra que la que
__________________________
Por ltimo
indica los operadores
su nombre. de desplazamiento
En la divisin (<<seydevuelve
el resultado que >>) sirven
es para
un
desplazar los bits n posiciones
__________________________
nmero real, mientras que en lahacia la izquierda
divisin o la derecha.
entera el resultado que se
devuelve es solo la parte entera. __________________________
Operador Descripcin Ejemplo
No obstante hay que tener en cuenta que si utilizamos dos operandos _________________________
& and r = 3 & 2 # r es 2
enteros, Python determinar que queremos que la variable resultado
tambin
| or
sea un entero, por lo que el resultado
r = 3de,
| por
2 ejemplo,
# r es 33 / 2 y
__________________________
3 //^ 2 sera el mismo:
xor 1. r = 3 ^ 2 # r esTipos 1 bsicos
~ not r = ~3 # r es -4 __________________________
Si quisiramos obtener los decimales necesitaramos que al menos uno
los operandosDesplazamiento
de << fuera un nmero izq.
real, bien
r = indicando
3 << 1 # los decimales
r es 6 20 __________________________
>> Desplazamiento der. r = 3 >> 1 # r es 1
r = 3.0 / 2
__________________________
o bien utilizando la funcin float (no es necesario que sepais lo que
Cadenas
significa el trmino funcin, ni que recordeis esta forma, lo veremos un __________________________
Las cadenas
poco no son ms que texto encerrado entre comillas simples
ms adelante):
(cadena) o dobles (cadena). Dentro de las comillas se pueden __________________________
aadir
r =caracteres
float(3)especiales
/ 2 escapndolos con \, como \n, el carcter de
nueva lnea, o \t, el de tabulacin.
Esto es as porque cuando se mezclan tipos de nmeros, Python con-
Una cadena puede estar precedida por el carcter u o el carcter r, los
NOTAS DEL
cuales CURSO
indican, 19
respectivamente, que se trata de una cadena que utiliza M.C. GABRIEL GERNIMO CASTILLO
codificacin Unicode y una cadena raw (del ingls, cruda). Las cade-
nas raw se distinguen de las normales en que los caracteres escapados
mediante la barra invertida (\) no se sustituyen por sus contrapartidas.
PYTHON - TURTLE&PYGAME
Cadenas __________________________
__________________________
__________________________
>>> print "hola mundo
\n\n" _________________________
hola mundo
__________________________
>>> a = "uno"
>>> b = "dos"
__________________________
>>> c= a + b
>>> print c
__________________________
unodos __________________________
>>> c = a * 3
>>> print c __________________________
unounouno
>>> __________________________
Listas __________________________
__________________________
La lista es un tipo de coleccin ordenada. Sera equivalente a lo
que en otros lenguajes se conoce por arrays, o vectores. __________________________
>>> lista = [11, False]
>>> var = lista [0] _________________________
>>> print var
11 __________________________
>>> var = lista [1]
>>> print var __________________________
False
>>> lista = ["una lista", 2, [2,3]] __________________________
>>> var = lista [2][1]
>>> print var
__________________________
3 __________________________
>>> print lista[-1]
[2, 3] __________________________
Laboratorio Edumvil. M.C. Gabriel Gernimo C.
Lista __________________________
__________________________
>>> print lista[-1] >>> c= "hola
JOHANNA" __________________________
[2, 3]
>>> print c[0] _________________________
>>> print lista[0:2]
h
['una lista', 2] __________________________
>>> print c[5:]
>>> print lista[0:4:2] __________________________
JOHANNA
['una lista', [2, 3]]
>>> print c[::2]
__________________________
>>> print lista[0:3:2]
hl OAN __________________________
['una lista', [2, 3]]
>>> print lista[0:3:1]
__________________________
['una lista', 2, [2, 3]] __________________________
Diccionarios __________________________
__________________________
__________________________
Los diccionarios, tambin llamados matrices asociativas, deben su _________________________
nombre a que son colecciones que relacionan una clave y un valor.
__________________________
>>> d = {"a": "abaco arbol ardilla", "b":"barril barco becerro", "c":
"casa cama", "d": "dado dedo"} __________________________
>>> print d["b"]
__________________________
barril barco becerro
__________________________
__________________________
__________________________
Bucles __________________________
Funciones __________________________
__________________________
Las funciones se declaran de la siguiente forma:
__________________________
_________________________
def mi_funcion(param1, param2):
print param1 __________________________
print param2
__________________________
def mi_funcion(param1, __________________________
param2):
Esta funcion imprime los
__________________________
dos valores
__________________________
pasados como parametros
print param1 __________________________
print param2
Funciones __________________________
__________________________
#!/usr/bin/python def sumar (x, y):
def f(x, y): return x + y __________________________
"""esta es una funcion que
imprime los valores por print sumar (3,2) _________________________
referencia"""
x=x+ 3 def fun (x, y): __________________________
y.append(23) return x * 2, y * 2
print x, y __________________________
x = 22 a, b = fun (1,2)
y = [22] print a , b __________________________
f(x, y)
print x, y __________________________
__________________________
__________________________
Prctica 3.py Laboratorio Edumvil. M.C. Gabriel Gernimo C.
Mdulos __________________________
__________________________
Para facilitar el mantenimiento y la lectura los programas demasiado
__________________________
largos pueden dividirse en mdulos, agrupando elementos
relacionados.
modulo.py programa.py
_________________________
__________________________
def mi_funcion(): #!/usr/bin/python
print Una funcion __________________________
import modulo
class MiClase: __________________________
def __init__(self): modulo.mi_funcin()
print Una clase __________________________
Prctica 4.py
print Un modulo #Gero$./prog.py
Un modulo
__________________________
Una funcion
#Gero$ __________________________
Mdulos __________________________
__________________________
Algunos mdulos por defecto
__________________________
os. Los mdulos de la distribucin por defecto de Python que engloba
funcionalidad relacionada al Sistema Operativo
_________________________
sys. Con funcionalidad relacionada con el mismo interprete de Python
__________________________
time. Se almacenan funciones para manipular fechas y horas.
__________________________
Sin embargo es posible utilizar la construccin from-import para
ahorrar el indicar el nombre del mdulo antes del objeto que interesa. __________________________
De esta forma se importa el objeto o los objetos que indiquemos al
espacio de nombres actual. __________________________
Ejemplo: Ejemplo:
__________________________
import os, sys, time from time import asctime
print time.asctime() print asctime() __________________________
Mdulos __________________________
__________________________
__________________________
A la hora de importar un mdulo Python recorre todos los directorios
indicados en la variable de entorno PYTHONPATH en busca de un _________________________
archivo con el nombre adecuado. El valor de la variable
PYTHONPATH se puede consultar desde Python mediante sys.path __________________________
>>> import sys
>>> sys.path __________________________
De esta forma para que nuestro mdulo estuviera disponible para todos los
__________________________
programas del sistema bastar con copiarlo a uno de los directorios indicados
en PYTHONPATH.
__________________________
__________________________
En el caso de que Python no encontrara ningn mdulo con el nombre
especificado, se lanzara una excepcin de tipo ImportError. __________________________
Archivos __________________________
__________________________
Los archivos en Python son objetos de tipo file creados mediante la funcin
open.
__________________________
Esta funcin toma como parmetros una cadena con la ruta al archivo a
_________________________
abrir, que puede ser relativa o absoluta; una cadena opcional indicando el __________________________
modo de acceso (si no se especifica se accede en modo lectura).
__________________________
__________________________
__________________________
__________________________
__________________________
Archivos __________________________
El modo de acceso puede ser cualquier combinacin lgica de los siguientes
modos: __________________________
r: Modo lectura. El archivo tiene que existir previamente.
__________________________
w: Modo escritura. Si el archivo no existe se crea. Si existe, sobreescribe el
contenido.
_________________________
import __________________________
__________________________
__________________________
Existen varios caminos para importar mdulos al
_________________________
cdigo. Accesando a las clases y funciones que
contiene dicho modulo.
__________________________
import mimodulo
__________________________
o una funcin del modulo ya cargado
mimodulo.funcion()
__________________________
una clase especifica de un modulo
from mimodulo import miclase __________________________
Importa cada una de las cosas del modulo
from mimodulo import *
__________________________
__________________________
import __________________________
__________________________
>>> from datetime import datetime __________________________
>>> the_time = datetime.now()
>>> the_time.ctime() _________________________
'Thu Sep 10 19:01:26 2013'
__________________________
>>> from math import *
8725.book Page 39 Friday, August 24, 2007 5:20 PM
>>> print pi __________________________
3.14159265359
>>> sin (20) __________________________
CHAPTER 2 EXPLORING PYTHON 39
0.91294525072762767
__________________________
>>> import random
Although the numbers that Listing 2-8 produces appear random, they are actually pseudo-
__________________________
>>> print
random, which random.randint
means they are chosen (1,6)
from a large mathematically generated sequence.
4
Occasionally you may need to repeat a sequence of pseudorandom numberswhen playing
__________________________
back a demo, for instance. You can tell the random module to start generating numbers from a
particular point in the sequence by calling the random.seed function. If you call it twice with the
same
8725.book Page value,August
38 Friday, it will24,
cause
2007 the
5:20 random
PM module to reproduce the same sequence of numbers.
Listing 2-9 demonstrates how the seed function can be used to create predictable sequences.
38 import
Listing 2-9. A Better Dice Simulator
CHAPTER 2 EXPLORING PYTHON
import random
__________________________
random.seed(100)
for roll in xrange(10): __________________________
Table 2-6. Some Classes in the datetime Module
print random.randint(1, 6)
print
Class "Re-seeded"
Description __________________________
random.seed(100)
timedelta Stores a difference between two times
for roll in xrange(10): _________________________
dateprint random.randint(1, 6)
Stores a date value
If you runStores
datetime datescript,
this small and time
youvalues __________________________
will see the same sequence of numbers, repeated twice.
Have a look at Table 2-7 for a few of the capabilities of the random module.
time Stores a time value
__________________________
Table 2-7. Some Functions in the random Module
Random Module
Function Description __________________________
You wontSeeds
be surprised to number
the random learn that the random module is used to generate random numbers,
generator
seed
although you maya random
be surprised
__________________________
randint Returns integertobetween
learn that
two the numbers it generates arent truly random.
values
Thats because computers arent actually capable of selecting something at random; they will
choice Selects a random element from a collection
do the same thing again given identical conditions. The numbers that random generates are __________________________
random Return which
pseudorandom, a float between 0 andare
means they 1 pulled from a very long sequence of numbers that
__________________________
appear random but will eventually repeat if you generate enough of them. Fortunately you can
use them in a game because nobody will notice if they repeat after a few billion times!
Summary
Random (or pseudorandom) numbers are very useful in games to stop them from getting
predictable. If a game has no random elements, players will eventually memorize all the
Weve seen that you can use boolean logic to make decisions in Python code. The if statement
sequences of actions, making it less fun (for most people).
takes a boolean expression, such as a > 3, and runs a code block only if that condition results
NOTAS DEL CURSO Lets write a short script to simulate ten throws of a standard six-sided die (Listing
in True. You can append an if statement with one or more else statements, which runM.C.
2-8).
their GABRIEL GERNIMO CASTILLO
code block only if the condition is False. Logic can be combined using the and and or opera-
Listing
tors, 2-8.
and canDice Simulator
be reversed using the not operator.
Functions are stored Python code, created with the def statement. When you define func-
import
tions, random
you specify a list of parameters, which is a list of the information that the function needs
for roll in xrange(10):
PYTHON - TURTLE&PYGAME
__________________________
Referencias
__________________________
__________________________
1.Python para todos. Ral Gonzlez Duque. Licencia Creative Commons.
http://mundogeek.net/tutorial-python/ _________________________
2. Python Programming. Wikibooks.org. 2012.
__________________________
3. Python Algorithms. Magnus Lie Hetland. Apress. 2010.
__________________________
4. Game Programming with Python. Sean Riley. Charles River Media. 2004.
__________________________
5. Invent Your Own Computer Games with Python. Al Sweigart. Licencia
Creative Commons. 2010. __________________________
__________________________
__________________________
__________________________
__________________________
__________________________
Python: _________________________
__________________________
Mdulo Pygame __________________________
M.C. Gabriel Gernimo Castillo __________________________
Laboratorio Edumvil
Universidad Tecnolgica de la Mixteca __________________________
gcgero@gmail.com
__________________________
__________________________
pygame __________________________
__________________________
__________________________
Pgina oficial http://www.pygame.org/
_________________________
Es una librera para la creacin de juegos basada en SDL.
>>> import pygame __________________________
>>> print pygame.ver
1.9.1release __________________________
>>>
__________________________
El paquete pygame contiene un conjunto de mdulos (de
cada dispositivo) que pueden ser usados de forma __________________________
independiente.
__________________________
__________________________
__________________________
possible that the hardware the game is running on does not have certain capabilities, or that
required drivers are not installed. If this is the case, Pygame will set the module to None, which
__________________________
__________________________
>>> import pygame
_________________________
>>> pygame.init() __________________________
(6,0) __________________________
>>> pygame.display.list_modes()
[(1280,800), (1024,768), (832,624), __________________________
(800,600), (720,400), (640,480),
(640,400), (640,350)] __________________________
__________________________
__________________________
pantalla = pygame.display.set_mode
__________________________
((640,480), 0, 32)
pygame.display.set_caption ("IMAGEN") __________________________
fondo = pygame.image.load(imagen).convert
() __________________________
while True:
for evento in pygame.event.get():
__________________________
if evento.type == QUIT:
exit() __________________________
pantalla.blit(fondo, (0,0))
pygame.display.update()
Prctica 5.py __________________________
Laboratorio Edumvil. M.C. Gabriel Gernimo C.
pygame.display __________________________
__________________________
__________________________
pygame.display __________________________
__________________________
__________________________
Sus parmetros
8725ch03.fm son:
Page 47 Friday, September 14, 2007 3:48 PM
_________________________
1. La dupla que contiene el ancho y alto. Este es el requerido, los __________________________
siguientes son opcionales. CHAPTER 3 INTRODUCING PYGAME 47
__________________________
2. Bandera
morequedetailse usaOpening
in the para ela Display
modo section
de despliegue. Se puede
later in this chapter. We wont be enabling any
combinarof las
thesebanderas conPygame
flags for this first el operador ORvalue
script, so the __________________________
(|).we give for flags is just 0, which is also the
default.
3. Profundidad. Especifica la cantidad de bits usados para __________________________
Table 3-2. Flags for pygame.display.set_mode
almacenar los colores en el despliegue.
8725ch03.fm Page 47 Friday, September 14, 2007 3:48 PM
Flag Purpose __________________________
FULLSCREEN Creates a display that fills the entire screen.
DOUBLEBUF Creates a double-buffered display. Recommended for HWSURFACE or OPENGL.
__________________________
CHAPTER 3 INTRODUCING PYGAME 47
HWSURFACE Creates a hardware-accelerated display (must be combined with the
FULLSCREEN flag).
more detail in the Opening a Display section later in this chapter. We wont be enabling any
OPENGL Creates an OpenGL renderable display.
Flag Purpose
__________________________
The next parameter specifies the depth of the display surface, which is the amount of bits
FULLSCREEN Creates a display that fills the entire screen.
used to store colors in the display. A bit, or binary digit, is the most fundamental unit of storage
DOUBLEBUF in aCreates
computer. Bits have exactly
a double-buffered two potential
display. values,
Recommended for 1HWSURFACE
or 0, andorare arranged in memory as
OPENGL.
__________________________
HWSURFACE groups of 8. A group of 8 bits is called a (must
byte. Dont worry with
if this sounds like techno-babble to
Creates a hardware-accelerated
you;FULLSCREEN
Python tends
display be combined the
flag). to hide this kind of thing from the programmer. We will use the value 32 for _________________________
OPENGL ourCreates
bit depth becauserenderable
an OpenGL it gives us display.
the most colors; see Table 3-3 for other potential bit-depth val-
RESIZABLE
ues. If you dont supply a value for the depth or set it to 0, Pygame will use the depth of your
Creates a resizable display.
__________________________
desktop.
NOFRAME Removes the border and title bar from the display.
__________________________
Table 3-3. Bit-Depth Values
NOTAS DEL
15 bits Note colors,
CURSO
32,768 with Pygame
Sometimes is unable to give us the exact display we ask for. It may be that the graphics M.C. GABRIEL
a spare bit GERNIMO CASTILLO
16 bits card doesnt
65,536 support the features we are requesting. Fortunately, Pygame will choose a display that is com-
colors
24 bits patible with thecolors
16.7 million hardware and emulates the display we actually asked for. Thank you, Pygame!
32 bits 16.7 million colors, with a spare 8 bits
* It is possible to have other bit depths, but these are the most
PYTHON - TURTLE&PYGAME
pygame.display.update()
__________________________
Eventos estndares
Table 3-4. Standard Events
__________________________
Event Purpose Parameters
QUIT User has clicked the close button. none __________________________
ACTIVEEVENT Pygame has been activated or hidden. gain, state
KEYDOWN Key has been pressed. unicode, key, mod __________________________
KEYUP Key has been released. key, mod
MOUSEMOTION Mouse has been moved. pos, rel, buttons
_________________________
MOUSEBUTTONDOWN Mouse button was pressed. pos, button
__________________________
MOUSEBUTTONUP Mouse button was released. pos, button
JOYAXISMOTION Joystick or pad was moved. joy, axis, value __________________________
JOYBALLMOTION Joy ball was moved. joy, ball, rel
JOYHATMOTION Joystick hat was moved. joy, hat, value __________________________
JOYBUTTONDOWN Joystick or pad button was pressed. joy, button
JOYBUTTONUP Joystick or pad button was released. joy, button
__________________________
VIDEORESIZE
VIDEOEXPOSE
Pygame window was resized.
Part or all of the Pygame window was exposed.
size, w, h
none
__________________________
USEREVENT A user event has occurred. code
__________________________
Lets write a simple Pygame script to display all the events that are generated. Listing 3-2
uses pygame.event.wait() to wait for a single event. As soon as it gets one, it turns it into a
Lluvia de crculos
string with str and adds it to a list. The rest of the code displays the new event along with as
many previous events as it can fit on the screen. It uses the font module to display text (which
we will discuss later).
#!/usr/bin/python __________________________
import pygame,sys, random
pygame.init()
__________________________
Tip If blanco
negro =(0,0,0); you change the fill color in Listing 3-2 to (0,0,0) and the color of the font to (0, 255, 0), it will look a
= (255,255,255)
pantalla = pygame.display.set_mode ((800,600))
little like Matrix-style code. You may have to use your imagination a little!
pygame.display.set_caption ("Lluvia de circulos"); __________________________
lista=[]
for i in range (20):
x=random.randrange(0,800) _________________________
y=random.randrange(0,800)
r=random.randrange(1,3)
lista.append([x,y,r]) __________________________
while True:
for evento in pygame.event.get():
if evento.type == pygame.QUIT: __________________________
pygame.quit(); sys.exit()
pantalla.fill (negro)
for i in range (len(lista)): __________________________
x,y, radio=lista[i][0],lista[i][1], lista[i][2]
pygame.draw.circle(pantalla,blanco,(x,y),radio)
lista[i][1]+=1 __________________________
if lista[i][1]>590:
y=random.randrange(-50,-10)
lista[i][1] = y __________________________
x=random.randrange(0,800)
lista[i][0] = x
pygame.display.flip() __________________________
pygame.quit ()
pygame.init()
if evento.type == pygame.QUIT:
pygame.quit(); sys.exit() __________________________
pulsada = pygame.key.get_pressed()
negro = (0,0,0); blanco = (255,255,255)
pantalla = pygame.display.set_mode ((800,600))
if pulsada[K_UP]: mario.rect.top -= 0
if pulsada[K_DOWN]: mario.rect.top += 0 _________________________
pygame.display.set_caption ("Mario");
if pulsada[K_LEFT]: mario.rect.left -= 5
imagen = pygame.image.load("mario.png")
x = 100 ;y = 500
if pulsada[K_RIGHT]: mario.rect.left += 5
for rectangulo in listarect: __________________________
pygame.draw.rect(pantalla, (1, 0, 0), rectangulo )
mario = pygame.sprite.Sprite()
mario.image = imagen
if (rectangulo.colliderect(mario)):
mario.rect.left = oldx; mario.rect.top = oldy
__________________________
mario.rect = imagen.get_rect()
c+=1; print ("colision ",c)
oldx = mario.rect.top = y
oldx = mario.rect.left
oldy = mario.rect.top
__________________________
oldy = mario.rect.left = x
reloj.tick(15)
reloj = pygame.time.Clock()
lista=[]; listarect=[]
pantalla.fill (blanco)
__________________________
for i in range (20):
pantalla.blit(mario.image, mario.rect)
x=random.randrange(0,800)
y=random.randrange(0,800)
listarect=[] __________________________
r=random.randrange(1,3)
lista.append([x,y,r])
listarect.append ( pygame.Rect (x-r,y+r,2*r,2*r) ) __________________________
c=0
pygame.mixer.music.load ("mario_main.mp3")
__________________________
pygame.mixer.music.play (-1,0.0)
_________________________
mar="mario.png"
fon="fondo_mario.jpg"
fondo = pygame.image.load(fon).convert() __________________________
imagen = pygame.image.load(mar).convert_alpha()
if evento.type == pygame.QUIT:
__________________________
pygame.mixer.music.stop()
pygame.quit() __________________________
sys.exit()
pygame.init()
__________________________
nave = "nave.jpg"
pantalla = pygame.display.set_mode ((640,480), 0, 32)
pygame.display.set_caption ("Mueve una nave") _________________________
nave1 = pygame.image.load(nave).convert()
x, y = 0, 0; mx, my = 0,0
while True: __________________________
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == KEYDOWN:
__________________________
if event.key == K_LEFT: mx = -1
if event.key == K_RIGHT: mx = +1
if event.key == K_UP: my = -1
__________________________
if event.key == K_DOWN: my = +1
elif event.type == KEYUP:
if event.key == K_LEFT: mx = 0 __________________________
if event.key == K_RIGHT: mx = 0
if event.key == K_UP: my = 0
if event.key == K_DOWN: my = 0 __________________________
x+= mx; y+= my
#!/usr/bin/python
import pygame Mueve dos naves en la pantalla
from pygame.locals import *
from sys import exit
__________________________
pygame.init()
nave = "nave.jpg" __________________________
pantalla = pygame.display.set_mode ((640,480), 0, 32)
pygame.display.set_caption ("Mueve dos naves")
nave1 = pygame.image.load(nave).convert() __________________________
nave2 = pygame.image.load(nave).convert()
x, y = 0, 0; r, s = 450, 10
mx, my , mr, ms = 0,0,0,0
while True:
_________________________
for event in pygame.event.get():
if event.type == QUIT: exit()
if event.type == KEYDOWN:
__________________________
if event.key == K_a: mr = -1
if event.key == K_z: mr = +1
if event.key == K_s: ms = -1 __________________________
if event.key == K_x: ms = +1
if event.key == K_LEFT: mx = -1
if event.key == K_RIGHT: mx = +1 __________________________
if event.key == K_UP: my = -1
if event.key == K_DOWN: my = +1
__________________________
x+= mx; y+= my;r+= mr;s+= ms
elif event.type == KEYUP: pantalla.fill ((0,0,0))
if event.key == K_a: mr = 0 pantalla.blit(nave1, (x,y))
if event.key == K_z: mr = 0 pantalla.blit(nave2, (r,s))
if event.key == K_s: ms = 0
if event.key == K_x: ms = 0
pygame.display.update() __________________________
if event.key == K_LEFT: mx = 0
if event.key == K_RIGHT: mx = 0
if event.key == K_UP: my = 0 Prctica 9.py __________________________
if event.key == K_DOWN: my = 0 Laboratorio Edumvil. M.C. Gabriel Gernimo C.
Referencias __________________________
__________________________
__________________________
1.Making Games with Python & Pygame. Al Sweigart. Licensed under a
Creative Commons.2012. _________________________
2. Begin Game Development with Python and Pygame. Will McGugan. __________________________
Apress. 2007.
__________________________
2. The Art of Computer Game Design. Chris Crawford.
__________________________
__________________________
__________________________
__________________________