-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathchapter1.html
178 lines (108 loc) · 15.8 KB
/
chapter1.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-5459430-3");
pageTracker._trackPageview();
} catch(err) {}</script>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>IYOCGwP, Chapter 1 - Installing Python</title>
<link rel="stylesheet" href="inventbook.css" type="text/css" media="all" />
</head>
<body>
<table border='0' width='100%'><tr><td></td><td align='right'><a href='chapter2.html'>Go to Chapter 2 - The Interactive Shell</a></td></tr></table>
<div style='height: 310px;'><a href='http://www.amazon.com/Invent-Your-Computer-Games-Python/dp/0982106017/'><img src='images/buyad.png' align='right'></a></div>
<div style='height: 350px;'><img src='images/chap1.png'></div>
<div class='inthischapter'><h3 id="TopicsCoveredInThisChapter">Tópicos cobertos neste capítulo:</h3>
<ul>
<li>Baixando e instalando o interpretador Python.</li>
<li>Usando o console iterativo para rodar instruções.</li>
<li>Como usar este livro.</li>
<li>O <i>website</i> do livro em <a href='http://inventwithpython.com'>http://inventwithpython.com</a> (em inglês)</li>
</ul></div>
<p>Olá! Este livro irá lhe ensinar como programar, mostrando a você como criar jogos de computador. Uma vez que você aprenda como os jogos neste livro funcionam, será capaz de criar os seus próprios <i>games</i>. Tudo o que você precisa é um computador, um programa chamado interpretador Python e este livro. O programa que você precisará é livre e pode ser baixado da internet.</p.
<p>Quando eu era uma criança, achei um livro como este que me ensinou como escrever meus primeiros programas e jogos. Aquilo foi divertido e fácil. Agora, como um adulto, eu ainda me divirto programando computadores e sou pago para fazer isso. Mas mesmo que você não venha a se tornar um programador quando crescer, a capacidade de programar um computador é uma habilidade muito útil.</p>
<p>Computadores são máquinas muito úteis. A boa notícia é que aprender como programá-los é facil. Se você pode ler este livro, você pode programar um computador. Um <span class='term'>programa</span> é apenas um punhado de instruções executadas pelo computador, da mesma forma que um livro de histórias é apenas um punhado de sentenças lidas pelo leitor.</b>
<p>Essas instruções são como um passa-a-passo que você pode seguir para ir até a casa de um amigo. (Virar a esquerda no semaforo, andar dois quarteirões, continuar andando até você encontrar a primeira casa azul a direita.) O computador segue cada instrução que você fornece na ordem em que você a fornece. Vídeo games são apenas programas de computador. (E programas muito divertidos!)
<p>Neste livro, qualquer palavra que você precisar saber vai aparecer <span class='term'>assim</span>. Por exemplo, como a palavra "programa" é definida no parágrafo anterior.</p>
<p>Para dizer ao computador o que você quer fazer, você escreve um programa em uma linguagem que o computador entenda. A linguagem de programação ensinada neste livro chama-se Python. Há muitas linguagens de programação diferentes, incluindo BASIC, Java, Pascal, Haskell e C++ (pronuncia-se "c mais mais").</p>
<p>Quando eu era criança, a maior parte das pessoas aprendiam a BASIC como a sua primeira linguagem. Mas novas linguagens de programação foram inventadas desde então, incluindo Python. Python é mais facil de aprender do que BASIC e é uma linguagem de programação séria usada por programadores de computador profissionais. Muitos adultos usam Python em seu trabalho (e quando estão programando apenas por diversão).</p>
<p>Os primeiros jogos que nós vamos criar neste livro vão provavelmente parecer simples se comparados aos que você joga no Xbox, Playstation ou Wii. Eles não têm graficos bonitos ou música mas isto por que eles têm a intenção de ensinar o básico. São propositalmente simples para que possamos focar em aprender a programar. Jogos não precisam ser complicados para ser divertidos. Forca, Jogo-da-Velha e jogos de códigos secretos são simples de programar, mas também são divertidos.</p>
<p>Nós também vamos aprender como fazer o computador resolver problemas matemáticos no console do Python. (Não se preocupe se você não sabe muita matemática. Se sabe somar e multiplicar, você sabe o suficiente para programar. Programar é mais sobre resolução de problemas e traçar planos do que problemas matemáticos.)</p>
<h2 id="DownloadingandInstallingPython">Baixando e Instalando o Python</h2>
<p>Antes de começar a programar você vai precisar instalar um programa chamado interpretador Python. (Talvez você precise da ajuda de um adulto aqui.) O <span class='term'>interpretador</span> é um programa que entende as instruções que você escreverá na linguagem Python. Sem o interpretador, seu computador não entenderá essas instruções e seus programas não funcionarão. (Vamos nos referir ao "interpretador Python" apenas como "Python" a partir de agora.)</p>
<p>Como escreveremos nossos jogos na linguagem Python, será necessário primeiro baixar o Python do <i>website</i> oficial da linguagem Python, <a href='http://www.python.org'>http://www.python.org</a></p>
<p>Eu vou dar instruções de como instalar o Python no Microsoft Windows, não por que é meu sistema operacional favorito, mas por que é o provável sistema operacional que o seu computador está utililizando. Você pode precisar da ajuda de alguém para baixar e instalar o Python no seu computador.</p>
<p>Ao acessar o python.org, você deve ver uma lista de links na esquerda (Sobre, Noticias, Documentação, Download e por aí vai.) Clique no link <span class='menuname'>Download</span> para ir à página de download, então procure por um arquivo chamado <b>Python 3.1 Windows Installer</b> (Um binario Windows -- não inclue os fontes) e então clique neste link para baixar o Python para windows.</p>
<p class='centeredImageP'><img src='images/1-1.png' alt='' class='centeredImage' /><br />
Figure 1-1: Click the Windows installer link to download Python for Windows from <a href='http://www.python.org'>http://www.python.org</a></p>
<p>Dê dois cliques no arquivo <span class='filename'>python-3.1.msi</span> que você acabou de baixar. (Se a instalação não iniciar, tente clicar com o botão direito do mouse e escolher a opção "Instalar"). Quando o instalador iniciar, clique no botão <span class='menuname'>Next</span> e aceite as opções de instalação (não é necessário fazer nenhuma mudança). Quando a instalação finalizar, clique <span class='menuname'>Finalizar</span>.</p>
<p><b>Importante!</b> Tenha certeza de ter instalado o Python 3 e não o Python 2. Os programas deste livro usam Python 3, você obterá alguns erros se tentar executá-los com Python 2.</p>
<p>A instalaçaão para Mac OS é similar. Em vez de baixar o arquivo python-3.1.msi do site, baixe o arquivo python-3-1-1.dmg. O link para este arquivo vai parecer algo como "Mac Instaler disk image (3.1.1)" na página de download ("Dowload Python Software").</p>
<p>Se o seu sistema operacional for o Ubuntu, você pode instalar o Python abrindo uma janela do termina (clique em Aplicações > Acessórios > Terminal) e digite <span class='m'>sudo apt-get install python3</span> e tecle <i>enter</i>. Será necessário digitar a senha do usuário ou a senha de root para instalar o Python, portanto pergunte para o dono do computador para digitar sua senha.</p>
<p>Pode haver uma versão mais nova do que a versão 3.1 do Python. Se isso ocorrer, baixe a versão mais atual. Os programas deste livro funcionarão igualmente. Se você tiver qualquer problema, pode sempre procurar no Google por "instalar python 3 no <seu sistema operacional>". Python é uma linguagem muito popular, logo não deve ser dificil encontrar ajuda.</p>
<!-- TODO video não está traduzido
<p>A video tutorial of how to install Python is available from this book's website at <a href='http://inventwithpython.com/videos/'>http://inventwithpython.com/videos/</a>.</p>
-->
<!-- TODO traduzir o resto
<h2 class='pagebreaker' id="StartingPython">Iniciando o Python</h2>
<p>If your operating system is Windows XP, you should be able to run Python by choosing <span class='menuname'>Start</span>, <span class='menuname'>Programs</span>, <span class='menuname'>Python 3.1</span>, <span class='menuname'>IDLE (Python GUI)</span>. When it's running it should looking something like Figure 1-2. (But different operating systems will look slightly different.)</p>
<p class='centeredImageP'><img src='images/1-2.png' alt='' class='centeredImage' /><br />
Figure 1-2: The IDLE program's interactive shell on Windows.</p>
<p>IDLE stands for <b>I</b>nteractive <b>D</b>eve<b>L</b>opment <b>E</b>nvironment. The development environment is software that makes it easy to write Python programs. We will be using IDLE to type in our programs and run them.</p>
<p>The window that appears when you first run IDLE is called the interactive shell. A shell is a program that lets you type instructions into the computer. The Python shell lets you type Python instructions, and the shell sends these instructions to software called the Python interpreter to perform. We can type Python instructions into the shell and, because the shell is interactive, the computer will read our instructions and respond in some way. (Ideally in a way that we expect but that will depend on whether we write the correct instructions.)</p>
<h2 id="HowtoUseThisBook">How to Use This Book</h2>
<p>There are a few things you should understand about this book before you get started. "Invent with Python" is different from other programming books because it focuses on the complete source code for different games. Instead of teaching you programming concepts and leaving it up to you to figure out how to make fun games with those concepts, this book shows you fun games and then explains how they are put together.</p>
<h2 id="TheFeaturedPrograms">The Featured Programs</h2>
<p>Most chapters begin with a sample run of the featured program. This sample run shows you what the program's output looks like, with what the user types in shown as <b>bold</b> print. This will give you an idea of what the complete game will look like when you have entered the code and run it.</p>
<p>Some chapters also show the complete source code of the game, but remember: you don't have to enter every line of code right now. Instead, you can read the chapter first to understand what each line of code does and then try entering it later.</p>
<p>You can also download the source code file from this book's website. Go to the URL <a href='http://inventwithpython.com/source'>http://inventwithpython.com/source</a> and follow the instructions to download the source code file.</p>
<h2 id="LineNumbersandSpaces">Line Numbers and Spaces</h2>
<p>When entering the source code yourself, do <b>not</b> type the line numbers that appear at the beginning of each line. For example, if you see this in the book:</p>
<div class='sourceblurb'>
<ol start='9'>
<li>number = random.randint(1, 20)</li>
</ol>
</div>
<p>You do not need to type the "9." on the left side, or the space that immediately follows it. Just type it like this:</p>
<div class='sourceblurb'>
number = random.randint(1, 20)
</div>
<p>Those numbers are only used so that this book can refer to specific lines in the code. They are not a part of the actual program.</p>
<p>Aside from the line numbers, be sure to enter the code exactly as it appears. Notice that some of the lines don't begin at the leftmost edge of the page, but are indented by four or eight spaces. Be sure to put in the correct number of spaces at the start of each line. (Since each character in IDLE is the same width, you can count the number of spaces by counting the number of characters above or below the line you're looking at.)</p>
<p>For example, you can see that the second line is indented by four spaces because the four characters ("<span class='m'>whil</span>") on the line above are over the indented space. The third line is indented by another four spaces (the four characters, "<span class='m'>if n</span>" are above the third line's indented space):</p>
<div class='sourceblurb'>
while guesses < 10:<br />
if number == 42:<br />
print('Hello')<br />
</div>
<h3 id="TextWrappinginThisBook">Text Wrapping in This Book</h3>
<p>Some lines of code are too long to fit on one line on the page, and the text of the code will wrap around to the next line. When you type these lines into the file editor, enter the code all on one line without pressing Enter. </p>
<p>You can tell when a new line starts by looking at the line numbers on the left side of the code. For example, the code below has only two lines of code, even though the first line wraps around:</p>
<div class='sourceblurb'>
<ol>
<li>print('This is the first line! xxxxxxxxxxxxxxx<br />
xxxxxxxxxxxx')</li>
<li>print('This is the second line! ')</li>
</ol>
</div>
<h3 id="TracingtheProgramOnline">Tracing the Program Online</h3>
<p>You can visit <a href='http://inventwithpython.com/traces'>http://inventwithpython.com/traces</a> to see a trace through each of the programs in this book. Tracing a program means to step through the code one line at a time, in the same way that a computer would execute it. The traces web page has notes and helpful reminders at each step of the trace to explain what the program is doing, so it can help you better understand why these programs work the way they do.</p>
<h3 id="CheckingYourCodeOnline">Checking Your Code Online</h3>
<p>Some of the games in this book are a little long. Although it is very helpful to learn Python by typing out the source code for these games, you may accidentally make typos that cause your game programs to crash. It may not be obvious where the typo is.</p>
<p>You can copy and paste the text of your source code to the online diff tool on the book's website. The diff tool will show any differences between the source code in the book and the source code you've typed. This is an easy way of finding any typos in your program.</p>
<p>Copying and pasting text is a very useful computer skill, especially for computer programming. There is a video tutorial on copying and pasting at this book's website at <a href='http://inventwithpython.com/videos/'>http://inventwithpython.com/videos/</a>.
<p>The online diff tool is at this web page: <a href='http://inventwithpython.com/diff'>http://inventwithpython.com/diff</a>. A video tutorial of how to use the diff tool is available from this book's website at <a href='http://inventwithpython.com/videos/'>http://inventwithpython.com/videos/</a>.</p>
<h2 id="Summary">Summary</h2>
<p>This chapter has helped you get started with the Python software by showing you the python.org website where you can download it for free. After installing and starting the Python IDLE software, we will be ready to learn programming starting in the next chapter.</p>
<p>This book's website at <a href='http://inventwithpython.com'>http://inventwithpython.com</a> has more information on each of the chapters, including an online tracing website that can help you understand what exactly each line of the programs do.</p>
-->
<table border='0' width='100%'><tr><td></td><td align='right'><a href='chapter2.html'>Go to Chapter 2 - The Interactive Shell</a></td></tr></table>
<div style='height: 310px;'><a href='http://www.amazon.com/Invent-Your-Computer-Games-Python/dp/0982106017/'><img src='images/buyad.png' align='right'></a></div>
</body>
</html>