Bien, en la primer lección acerca de los bucles. Mencione que pospondría la enseñanza del Ciclo For
, hasta que revisaramos las listas. ¡El momento ha llegado!
for
¶Basicamente, el ciclo for
hace algo para cada valor en una lista. La forma en que se realiza es un poco confusa, por lo demás es básica. El siguiente ejemplo de código:
# Ejemplo del ciclo 'for'
# Primero, crea una lista para que itere a tráves de ella:
newList = [45, 'eat me', 90210.07, "The day has come, the walrus said, \
to speak of many things", -67]
# Crea el ciclo:
# Va a tráves de la lista newList, y secuencialmente coloca cada información
# dentro de una variable, y corre el ciclo
for value in newList:
print(value)
type(newList[1])
45 eat me 90210.07 The day has come, the walrus said, to speak of many things -67
str
Como puedes ver, cuando el ciclo se ejecuta, este corre a tráves de todos los valores en la lista mencionada después de in
. Después coloca los calores dentro de value
y se ejecuta a través del ciclo, cada ocasión con el valor cambia a algo distinto. Veamos otra vez, en un programa clásico cheerleading que todos conocemos:
# cheerleading program
word = input("Who do you go for? ")
for letter in word:
call = "Gimme a " + letter + "!"
print(call)
print(letter + "!")
print("What does that spell?")
print(word + "!")
Gimme a p! p! Gimme a e! e! Gimme a r! r! Gimme a r! r! Gimme a o! o! What does that spell? perro!
Acabas de aprender dos cosas:
Y eso es todo lo que hay para el Ciclo For.
Ahora pasemos a la parte práctica de la lección. Iniciemos la escritura de programas. Hasta ahora hemos aprendido de variables, listas, bucles y funciones. Con ello es suficiente para programar un poco. Así que dejaremos una tarea.
# THE MENU FUNCTION
# El programa pregunta por una cadena con todas las opciones del menú
# y la cadena de texto pregunta por una pregunta.
# asegurate que cada entrada es unica.
def menu(list, question):
for entry in list:
print(1 + list.index(entry),end=""))
print (") " + entry)
return eval(input(question)) - 1
# def menu(list, question): le indica a la función a
# solicitar dos datos:
# Una lista de todas las entradas del menú,
# y la pregunta que se realizará cuando se hayan desplegado todas las opciones
# para las entradas en la lista: es más o menos decir;
#'para cada entrada de la lista, haz lo siguiente:'
# print list.index(entry) + 1 usa la función .index() para encontrar
# donde se encuentra la entrada de lista. la función print despliega este
# añade 1 para hacer que los números sean más inteligibles.
# print ") " + imprime un corchete y el nombre de las entradas
# después del ciclo for termina, eval(input(question) - 1) pregunta,
# y regresa el valor al programa principal (menos 1, y regresa el
# número que la computadora entenderá).
No ha sido muy díficl , verdad? El programa actual abarca cinco líneas - esto es una maravilla de lo mucho que hemos aprendido hasta el momento! Todos mis comentarios tienen 16 líneas - mayor de tres veces el tamaño del programa. Es una buena idea ampliar tus programas. Recuerda que si deseas publicar tu código abierto, habrá muchas personas revisando tu código que hayas escrito. Revisemos la función que acabamos de escribir en el primer programa de ejemplo.
¿Cuál será nuestro primer programa de ejemplo? ¿Qué tal un (muy) sencillo juego de aventura de texto? Suena divertido! Sólo abarcará un habitación de la casa, y será extremadamente simple. Habrá cinco cosas y una puerta. En una de esas cinco cosas, es una llave de la puerta. Requieres encontrar la llave, que abre la puerta. Primero una versión en inglés-plano, después en Python:
#Versión plana de nuestro juego 'game'
Informar a la computadora acerca de nuestro menú
Imprime un mensaje de bienvenida, mostrando la descripción de una habitación
Vamos a dar al jugador, seis cosas para que las mire: una maceta, un cuadro\
un jarrón, una lampara, un zapato y la puerta.
Dile a la computadora que la puerta esta cerrada
Dile a la computadora donde se encuentra la llave
Presenta un menu, diciendo que cosas pueden 'operate':
El menú te proporcionará seis opciones
El menú te preguntará "Qué deseas buscar?
Si el usuario desea buscar:
pot plant:
Si la llave se encuentra aquí , proporciona al jugador la llave
de forma indicarle que no esta aquí
painting:
Lo mismo de arriba
etc.
door:
Si el jugador tiene la llave, permitelé abrir la puerta
De otra forma, indiquenle que busque más
Mencionen al jugador un mensaje de que lo hizo bien, para completar el juego.
# TEXT ADVENTURE GAME
#the menu function:
def menu(list, question):
for entry in list:
print(1 + list.index(entry),end="")
print (") " + entry)
return eval(input(question)) - 1
#Give the computer some basic information about the room:
items = ["pot plant","painting","vase","lampshade","shoe","door"]
#The key is in the vase (or entry number 2 in the list above):
keylocation = 2
#You haven't found the key:
keyfound = 0
loop = 1
#Give some introductary text:
print("Last night you went to sleep in the comfort of your own home.")
print("Now, you find yourself locked in a room. You don't know how")
print("you got there, or what time it is. In the room you can see")
print(len(items), "things:")
for x in items:
print(x)
print("")
print("The door is locked. Could there be a key somewhere?")
#Get your menu working, and the program running until you find the key:
while loop == 1:
choice = menu(items,"What do you want to inspect? ")
if choice == 0:
if choice == keylocation:
print("You found a small key in the pot plant.")
print("")
keyfound = 1
else:
print("You found nothing in the pot plant.")
print("")
elif choice == 1:
if choice == keylocation:
print("You found a small key behind the painting.")
print("")
keyfound = 1
else:
print("You found nothing behind the painting.")
print("")
elif choice == 2:
if choice == keylocation:
print("You found a small key in the vase.")
print("")
keyfound = 1
else:
print("You found nothing in the vase.")
print("")
elif choice == 3:
if choice == keylocation:
print("You found a small key in the lampshade.")
print("")
keyfound = 1
else:
print("You found nothing in the lampshade.")
print("")
elif choice == 4:
if choice == keylocation:
print("You found a small key in the shoe.")
print("")
keyfound = 1
else:
print("You found nothing in the shoe.")
print("")
elif choice == 5:
if keyfound == 1:
loop = 0
print("You put in the key, turn it, and hear a click")
print("")
else:
print("The door is locked, you need to find a key.")
print("")
# Remember that a backslash continues
# the code on the next line
print("Light floods into the room as \
you open the door to your freedom.")
Last night you went to sleep in the comfort of your own home. Now, you find yourself locked in a room. You don't know how you got there, or what time it is. In the room you can see 6 things: pot plant painting vase lampshade shoe door The door is locked. Could there be a key somewhere? 1) pot plant 2) painting 3) vase 4) lampshade 5) shoe 6) door You found nothing in the shoe. 1) pot plant 2) painting 3) vase 4) lampshade 5) shoe 6) door The door is locked, you need to find a key. 1) pot plant 2) painting 3) vase 4) lampshade 5) shoe 6) door
Traceback (most recent call last): File "/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py", line 3331, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-18-bf35cea435da>", line 34, in <module> choice = menu(items,"What do you want to inspect? ") File "<ipython-input-18-bf35cea435da>", line 9, in menu return eval(input(question)) - 1 File "<string>", line unknown ^ SyntaxError: unexpected EOF while parsing
Bueno, un juego simple, pero divertido. No te asustes por la cantidad de códgio, 53 de las líneas son sólo sentencias condicionales if
, que es lo más fácil de leer (Una vez que hayas comprendido toda la sangría o indentación. Pronto, realizarás tu propio juego, y puedes hacerlo más simple (o más compleja) como gustes. Lo publicaré un poco después.
La primera pregunta que debería hacerse es "¿Este programa funciona?". La respuesta es sí. Luego la siguiente pregunta es "¿Este programa trabaja bien?" - no del todo. La función del menu()
es genial - reduce un poco del tecleo. El ciclo while
que tenemos, sin embargo es un poco más desordenado - cuatro niveles de indentación, para un programa simple. Podemos hacerlo mejor!
Ahora, será más sencillo cuando introduzcamos las clases. Pero eso tendrá que esperar. Hagamos una función que reduzca nuestro desorden. Le pasaremos dos cosas - el menú de las opciones, y la ubicación de las llaves. Y devolverá una cosa, si la llave ha sido encontrada o no, veasmoslo:
def inspect(choice,location):
if choice == location:
print("")
print("You found a key!")
print("")
return 1
else:
print("")
print("Nothing of interest here.")
print("")
return 0
Now the main program can be a little simpler.
In the field below:
inspect
functionwhile
loop with:while loop == 1:
keyfound = inspect(menu(items,"What do you want to inspect? "),keylocation)
if keyfound == 1:
print("You put the key in the lock of the door, and turn it. It opens!")
loop = 0
# TEXT ADVENTURE GAME
#the menu function:
def menu(list, question):
for entry in list:
print(1 + list.index(entry),end="")
print (") " + entry)
return eval(input(question)) - 1
#Give the computer some basic information about the room:
items = ["pot plant","painting","vase","lampshade","shoe","door"]
#The key is in the vase (or entry number 2 in the list above):
keylocation = 2
#You haven't found the key:
keyfound = 0
loop = 1
#Give some introductary text:
print("Last night you went to sleep in the comfort of your own home.")
print("Now, you find yourself locked in a room. You don't know how")
print("you got there, or what time it is. In the room you can see")
print(len(items), "things:")
for x in items:
print(x)
print("")
print("The door is locked. Could there be a key somewhere?")
#Get your menu working, and the program running until you find the key:
while loop == 1:
choice = menu(items,"What do you want to inspect? ")
if choice == 0:
if choice == keylocation:
print("You found a small key in the pot plant.")
print("")
keyfound = 1
else:
print("You found nothing in the pot plant.")
print("")
elif choice == 1:
if choice == keylocation:
print("You found a small key behind the painting.")
print("")
keyfound = 1
else:
print("You found nothing behind the painting.")
print("")
elif choice == 2:
if choice == keylocation:
print("You found a small key in the vase.")
print("")
keyfound = 1
else:
print("You found nothing in the vase.")
print("")
elif choice == 3:
if choice == keylocation:
print("You found a small key in the lampshade.")
print("")
keyfound = 1
else:
print("You found nothing in the lampshade.")
print("")
elif choice == 4:
if choice == keylocation:
print("You found a small key in the shoe.")
print("")
keyfound = 1
else:
print("You found nothing in the shoe.")
print("")
elif choice == 5:
if keyfound == 1:
loop = 0
print("You put in the key, turn it, and hear a click")
print("")
else:
print("The door is locked, you need to find a key.")
print("")
# Remember that a backslash continues
# the code on the next line
print("Light floods into the room as \
you open the door to your freedom.")
Last night you went to sleep in the comfort of your own home. Now, you find yourself locked in a room. You don't know how you got there, or what time it is. In the room you can see 6 things: pot plant painting vase lampshade shoe door The door is locked. Could there be a key somewhere? 1) pot plant 2) painting 3) vase 4) lampshade 5) shoe 6) door You found nothing in the shoe. 1) pot plant 2) painting 3) vase 4) lampshade 5) shoe 6) door You found nothing behind the painting. 1) pot plant 2) painting 3) vase 4) lampshade 5) shoe 6) door
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-20-bf35cea435da> in <module> 32 #Get your menu working, and the program running until you find the key: 33 while loop == 1: ---> 34 choice = menu(items,"What do you want to inspect? ") 35 if choice == 0: 36 if choice == keylocation: <ipython-input-20-bf35cea435da> in menu(list, question) 7 print (") " + entry) 8 ----> 9 return eval(input(question)) - 1 10 11 #Give the computer some basic information about the room: <string> in <module> NameError: name 'vase' is not defined
Ahora el programa se reduce masivamente - de 83 líneas engorrosas- a unas muy bien formadas 50 líneas! Por supuesto, se pierde bastante versatilidad: todos los elementos de la habitación hacen lo mismo. La puerta se abre automáticamente cuando encuentra la llave. El juego se vuelve un poco menos interesante. Y se vuelve más díficil de cambiar.
Ahora dije que escribirías unos programas. Esta es tu oportunidad! Tu tarea, si aceptas esta, es postear un mejor juego de aventuras con texto, puedes utilizar cualquier sección de código que he utilizado aquí. Recuerda repasar las lecciones previas - son herramientas invaluables. Haz una búsqueda para algunos textos simples de juegos de aventuras - si encuentras alguno juegos de aventura divertidos y agradables, échales un vistazo.