Python
Programming
for the Absolute Beginner
rd Edition
Australia Brazil Japan Korea Mexico Slngapore Spaln United lngdom United States
r.
~n
Mocua -
-- 6
~.
2014
.
Python. - .: , 2014. - 416 .: .
- r Pytho. ,
,
.
Python , .
r m.
n ,
, r . m 1)'
, Python,
, .
r Python !
: Couse Technology .
r
.
, , , :
. , ,
! 1
, .
.............................................. 2s
.................................................. 26
.................................................. 27
............................................. 29
n 1. . Game Over. . . . . . . . . . . . . . . 30
n 2. , -.
r ................... 43
n . , while .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
n 4. for, .
................................ 104
n s. . ................. 134
n 6. . - .................. 165
n 7. . r ............. 194
n 8. r.
........................ 219
n 9. r- .
-: ................................ 245
6
10.
.
.............. .211
11. . ................308
12. , , .
..........................343
. - ..............................387
. livewires .................... 388
...................................... 400
.............................................. 25
.................................................. 26
.................................................. 27
............................................. 29
2. , -.
.................... 43
................... 43
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
. . . . . . . . . . . . . . . . . . . 55
.............................................. 56
....................... 56
.................................. 56
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
............................ 58
............ 59
input() ............................. 59
................................ 61
........... 61
. . . . . . . . . . 62
.................................... 63
9
( ) ........ 64
............... 65
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
( ) ....... 66
...................... 67
. . . . . . . . . . . . . . . . . . . . . . . 68
. . . . . . . . . . . . . . . . . . . . . 68
................................ 69
. . . . . . . . . . . . . . . . . . . . . . . 69
m . . . . . . . . . . . 69
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
. , while .
.............................. 72
............................... 72
. . . . . . . . . . . . . . . . . . . . . . . . 73
random ................................. 74
randint() . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
randrange() . . . . . . . . . . . . . . . . . . . . . . . . . 75
if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
....................... 75
, if ................... 77
..................................... 77
.................................. 77
. . . . . . . . . . . . . . . . . . 78
................ 79
if else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
/ . . . . . . . . . . . . . . . 79
else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
elif . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
......................................... 80
elif . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
10
while. . . . . . . . . . . . . . . . . . . . . . . . . 84
. . . . 84
while ......................... 85
.................. 85
. . . . . . . . . . . . . . . 86
. . . . . . . . . . . . . . 86
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
. . . . . . . . . . 87
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
, . . . . . . . . . . . . . . . 88
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
. . . . . . . . . . . . . . . . . . . . 90
............................ 91
....................... 91
. . . . . . . . . 92
break . . . . . . . . . . . . . . . . . 93
continue .................. 93
break continue . . . . . . . . . . . . . . . 93
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
. . . . . . . . . . . . . . 94
not . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
and . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
..................................... 98
.............................. 98
.......................... 99
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
. . . . . . . . . . . . . . . . . . . . . . . . . 101
random . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
.................................. 101
. . . . . . . . . . . . . . . . . . . . . . . . . . 101
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
11
4. for, .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
............................. 104
for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
. . . . . . . . . . . . . . . 105
for ......................... 106
for. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
.................... 107
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
, . . . . . . . . . . . . . . . . . . . . . . . . . . 109
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
:
. . .. . . . . . . .. . . . . . .. . . . . . .. . .. .. . . 109
.............. 110
len() . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
in ............................. 111
........................................ 111
.............. 111
. . . . . . . . . . . . . . . . . . . . 112
. . . . . . . . . . . . . . . . . . . . . 113
............................. 114
.............................. 115
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
. . . . . . . . . . . . . 116
.................................. 117
. . . . . . . . . . . . . . . . . . 118
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
. . . . . . . . . . . . . . . 119
None .................................. 121
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
. . . . . . . . . . . . . . . . . . . . . . . . . . 122
................................... 123
. . . . . . . . . . . . . . . . . 123
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
12
.......................... 125
...................... 125
. . . . . . . . . . . . . . . . . . . . . . . . . 126
................................. 126
2.0 .............. 126
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
len() . . . . . . . . . . . . . . . . . . . 127
in . . . . . . . . . . . . . . . . . 128
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
................................. 129
............................... 1
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . l
......................... 11
. . . . . . . . . . . . . . . . . . . 131
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
....................... 132
jume. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
. . . . . . . . . . . . . . . . . . . . . . . . . 132
. . . . . . . . . . . . . . . . . . . . . . 132
. . . . . . . . . . . . . . 13
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
................................................. 13
5. . ................. 134
. .............................. 134
..................................... 135
3.0 . . . . . . . . . . . . . . 136
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
len() . . . . . . . . . . . . . . . . . . . . 137
in . . . . . . . . . . . . . . . . . . . . . . 137
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
..................................... 138
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
13
,
............................... 139
. . . . .. . . .. ... . .. 139
............................. 140
................................ 140
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
..................... 140
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
. . . . . . . . . . . . . . . . . . . . . . . . . . 142
.................................. 142
................................. 143
.......................... 143
. . . . . . . . . . . . . . . . . . . . . . . . . 144
.............................. 144
, - . . . . . . . . . . . . . . . . . . 144
.............................. 145
2.0 .................. 145
. . . . . . . . . . . . . . . . . . 146
......................... 147
......................... 147
............................... 148
, .... 148
............ 149
. . . . . . . . . . . . . . . . . . . . . . . . 149
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
. . . 152
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
.......................... 153
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
- . . . . . . . . . . . . . . . . . . . . 156
- ........................ 157
- ..................... 157
14
. . . . . .. . . . . . . . . . . . . .. . . 158
............................... 158
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
................................... 159
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
..................... 163
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
................................................. 164
6. . - . . . . . . . . . . . . . . . . . . 165
- . . . . . . .. . . . .. . . . . . . 165
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
................... 167
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
. . . . . . . . . . . . . . . . . . . . . . . . . . 168
. . . . . . . . . . . . . . . . . . . . . . . . 169
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
. . . . . . . . . . . . . . . . . . . . . . . 169
- ......... 170
. . . . . . . . . . . . . . . . . . 170
.......................... 171
............................ 172
, . . . . . . . 172
. . . . . . . . . . . . . 173
....... 174
. . . . . . . . . . . . . . . . 174
. . . . . . . . . . 175
.......... 175
. . . . . . . . . . . . . . . . . . . . . . 176
............... 177
. . . . . . . . . . . . . . . . . . . . . . . 177
. . . . . . . . . . . . . . . 179
.......... 180
. . . . . . . . 180
15
. ......... 181
. ..... 181
- . . . . . . . . . . . . . . . . . . . . . . 182
- ...................... 182
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
display_instruct() .............................. 185
ask_yes_no() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
ask_numer() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
pieces(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
new_oard() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
display_oard() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
legal_moves() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
winer() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
human_move() . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
computer_move() .............................. 188
next_turn() .................................. 191
congrat_winner() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
mai() ................................ 192
.................................. 192
............................................... 192
7. . ............ 194
.............................. 194
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
.................. 195
.......................... 197
. . . . . . . . . . . . . . . . . . . . . . . . . . . 198
. . . . . . . . . . . . . . . . . . . . . . . 199
. . . . . . . . . . . . . . . . . . . . . . . 200
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
3 ..................... 201
.............................. 201
. . . . . . . . . . . . . . . . . . . . . . . . . . . 202
. . . . . . . . . . . . . . . . . . . 203
3 . . . . . . . . . . . . . 203
. . . . . . . . . . . . . . . . . . . . 204
16
................. 205
. . . . . . . . . . . . . 206
................................ 207
..................................... 208
.................. 208
try/except . . . . . . . . . . . . . . . . . . . . . . 208
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
.................. 211
................................. 212
else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
. . . . . . . . . . . . . . . 213
open_file() .................................. 214
next_line() ................................... 215
next_lock() ................................. 215
welcome() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
..................................... 216
..................................... 216
.................................... 216
..................................... 217
......................... 217
.................................. 217
main() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
................................................. 217
8. .
.................................. 219
...................... 219
- ..................... 221
, . . . . . . . . . . . . . . . . . . . . . . . . . 221
. . . . . . . . . . . . . . 221
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
. . . . . . . 224
17
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
. . . . . . . . . . . . . . . . . . . . . . . . 225
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
. . . . . . . . . . 226
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
............................... 228
. . . . . . . . . . . . . . 229
. . . . . . . 229
............................. 231
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
. . . . . . . . . . . . . . . . . . . . . . . . . . 232
. . . . . . . . . . . . . . . . . . . . . . 232
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
. . . . . . . . . . . . . . . . . . . . . 233
............. 233
. . . . . . . . . . . . . . . . . . . . . . . . . . 234
. . . . . . . . . . . . . . . . . . . . . . . . . . . 234
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
. . . . . . . . . 237
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
. . . . . . . . . 237
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
. . . . . . . . . . . . . . . . . . . . . . . . 240
Critter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
................................................. 244
9. - .
- ................................. 245
- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
18
...... 247
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
. . . . . . . . . . . . . . . . . . . . . . . . . . . 249
.................................... 249
. . . . . . . . . . . . . . . . . . 249
card . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
Hand ................... 250
- ..................... 251
- Hand . . . . . . . . . . . . . . . . 251
. . . . . . . . . . 252
. . . . . . . . . . . . . . . . 253
2.0 . . . . . . . . . . . . . . . . . . 253
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
. . . . . . . . . . . . . . . . . . 255
. . . . . . . . . . . . . . . . . . . . . . . 255
. . . . . . . . . . . . . . . . . . . . . . . 256
. . . . . . . . . . . . . . . . . . . . . . 258
3.0 . . . . . . . . . . . . . . . . 258
. . . . . . . . . . . . . . . . . . . . . . . . . . . 258
............ 259
. . . . . . . . . . . . . . . . . . . . . . . . . 260
. . . . . . . . . . . . . . . . . . 261
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
. . . . . . . . . . . . . . . . . . 263
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
. . . . . . . . . . . 265
- .............................. 266
cards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
............................ 267
. . . . . . . . . . . . . . 268
cards games . . . . . . . . . . . . . . . . . . . . . . . . . . 269
BJ_card. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
J_Deck. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
BJ_Hand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
BJ_Player. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
19
J_Dealer
..................................... 272
.....................................
J_Game 273
main() .................................. 275
............................................ 276
10. .
.............. 211
. .. . . .. . . . .. 277
GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
- . . . . . . . . . . 280
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
GUI .................... 281
tkinter ................................. 282
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
. . . . . . . . . . . . . . . . . . . . . . . . . . 283
. . . . . . . . . . . . . . . . . . 283
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
, . . . . . . . . . . . . . . . . . 284
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
. . . . . . . . . . . . . . . . 285
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
........... 286
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
. . . . . . . . . . . . . . . . . . 287
GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
- 2. . . . . . . . . 288
tkiter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
Application . . . . . . . . . . . . . . . . . . . . . . . . . . 288
- ..................... 288
, . . . . . . . 289
Applicatio . . . . . . . . . . . . . . . . . . 289
. . . . . . . . 290
............... 290
. . . . . . . . . . . . . . . . . . . . . 290
. . . . . . . . . . . . . . 291
20
.......................... 291
.................................. 291
. Grid ............ 291
. . . . . . . . . . . . . . . . . . 292
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
Grid . . . . . . . . . . . . . . . . . . . . . . . . . . 293
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
. . . . . . . . . . . . . . . . . . . . . . . . . 295
: ........ 295
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
..................... 297
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
. . 297
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
-2 .................... 300
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
............................ 301
. . . . . . . . . . . . . . . . . . . . . 303
................................ 303
. . . . . . . . . . . . . . . . . 303
tkinter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
- Application . . . . . . . . . . . . . . . . . . . . 304
create_widgets() Application . . . . . . . . . . . . . . . . 304
tell_story() Application. . . . . . . . . . . . . . . . . . . . . . . 305
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
.............................................. 307
............. 312
......................... 312
............................... 313
.............. 313
........................... 313
.................................. 315
......................... 315
.................................... 315
- ................. 317
....................... 318
................................ 318
........................... 319
...................................... 320
! .......... 320
color .................................. 321
Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
Text . . . . . . . . . . . . . . . . . . . . . . 322
..................................... 323
...................... 323
color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
Message . . . . . . . . . . . . . . . . . . . . . . . . 324
. . . . . . . . . . . . . . . 325
Message . . . . . . . . . . . . . . . . . . . . 325
....................................... 325
. . . . . . . . . . . . . . . 326
. . . . . . . . . . . . . . . . . . . . 327
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
. . . . . . . . . . . . . . . . . . . . . 327
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
Sprite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
update() . . . . . . . . . . . . . . . . . . . . . . . 329
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
........................ 330
........... 330
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
............................ 331
. . . . . . . . . . . . . . . . . . . . . . . . 332
22
12. , , .
. . . . . . . . . . . . . . . . . . . . . . . . . 343
. ....................... 343
....................................... 345
. . . . . . . 345
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
.......................... 347
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
............. 347
angle ........... , . . . . 349
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
.................. , . . . . 349
. . . . . . . . . . . . . . . . . . . . . . . . . . 350
............................. 350
.......................... 351
. . . . . . . . . . . . . . . . . . . . . 352
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
. . . . . . . . . . . . . . . . . 352
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
23
.......................... 357
.. .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
. . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
. . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . 358
. . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
- 1 . . . . . . . . . . . . . . . . . . . . . 359
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
Asteroid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
main() ...................................... 361
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
- 2 . . . . . . . . . . . . . . . . . . . . 361
Ship . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
Ship . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
- 3 . . . . . . . . . . . . . . . . . . . 363
math .................................. 364
Ship . . . . . . . . . . 364
upclate() Ship. . . . . . . . . . . . . . 364
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
- 4 . . . . . . . . . . . . . . . . . . 366
upclate() Ship. . . . . . . . . . . . . . . . . . . 366
Missile ....................................... 367
. . . . . . . . . . . . . . . . . . . . . . . . . 369
- 5 . . . . . . . . . . . . . . . . . . . . . 369
Ship . . . . . . . . . . . . . . . . . . . . . . 370
- Ship . . . . . . . . . . . . . . 370
update() Ship. . . . . . . . . . . . . . . . . . . 370
................................... 371
- 6 .................... 371
upclate() Missile ................. 371
die() Missile . . . . . . . . . . . . . . . . . . 371
update() Ship. . . . . . . . . . . . . . . . . . . 372
die() Ship. . . . . . . . . . . . . . . . . . 373
Asteroid. . . . . . . . . . . . . . . . . . 373
die() Asteroid . . . . . . . . . . . . . . . . . 373
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
- 7 . . . . . . . . . . . . . . . . . . 374
Wrapper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
24
Collider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
Asteroid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
Ship . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
Missile. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
Explosion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
, , . . . . . . . . . . . . . . . . . . . . . . . 378
- 8 . . . . . . . . . . . . . . . . . . . . . 378
color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
Asteroid. . . . . . . . . 383
- Asteroid ............ 383
die() Asteroid. . . . . . . . . . . . . . . . . . . 383
Ship . . . . . . . . . . . . . . . . . . . . . . 384
- Ship . . . . . . . . . . . . . 384
update() Ship. . . . . . . . . . . . . . . . . . . 384
die() Ship. . . . . . . . . . . . . . . . . . . . 385
main() ...................................... 385
................................................. 385
. - .............................. 387
. livewires.................... 388
livewires . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
games ...................................... 388
Screen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
Sprite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
Text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
Animation . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . 393
Mouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
Keyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
Music. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
games . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
games. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
,
, - .
, r - , .
. ,
.
Uenny Davidson) ,
: .
.
(Mic\1ael Dawson) :
, . -
, .
-.
,
U CLA . ,
, : <k ++
(Beginning ++ through Game Programming), <k
Python (Guide to Programming with Python) <kC++:
(++ Projects: Programming lR1ith Text-Based Games).
(www.programgames.com)
.
: - .
.
, , -
, . ,
, :
?~
, , . ,
,
~.
, ,
. ... ,
.
. ,
, ,
, ,
.
- Python
, . ,
, - .
,
.
,
, . ,
,
, .
Python - . ,
. ,
Python
.
, . Python
,
- . Python,
. ,
, Python
~.
28
, .
Python
Windo\vs. , ,
. .
, , ,
: , , ,
- , GUI .
,
. ,
, .
,
. ,
, .
, ,
- www.courseptr.com/downloads.
(),
. ,
, .
.
------------------------
, .
-------------------------
. .
-------------------------~
,
.
,. Q ~ '
- . ,
.
,
, .
, j:i
vinitski@minsk.piter.com ( ~>, ).
!
http://www.piter.com
.
.
1 Game Over
- , , - .
, . Python,
: -
(GUI).
, , .
,
. Python.
:
Python ;
Python ;
;
Python ,
, .
Game Over
Game Over, , ,
: Game Over. . 1.1
, .
. 1.1 - ,
. ,
(GUI), ,
.
G Over < ; ,
, Python.
.
, ,
Python. ,
.
, .
, .
Python 31
. 1.1. , ,
Python
Python - ,
(Guido van Rossum).
1991 . Python ,
,
, .
Python 42, .
(Monty Python), .
Python -,
( , , ,
,
).
.
Python? .
Python
-
. , , ,
32 1. . Game Over
, Python -
: Python
, .
Python -
Python ,
. ,
GUI .
Python .
: Google, I, Industrial Light + Magic,
Microsoft, NASA, Red Hat, Verizon, Xerox Yahoo!.
Python. Electronic Arts, 2 Games Disney Interactive
Media Group - Python.
Python - r-
- () -
.
, ,
. , ,
, , , .
C#,java Python - - . Python
. # java -
. ;
- ,
. Python : -
. - ,
, .
? .
? . Python
.
Python -
Python , , ++ jv.
, Python ,
,
(, /++), -
Python.
Python Windows 33
Python
thn- : Palm
Cray. ,
Python Windows, Macintosh,
Linux - .
Python , ,
:
Python. ,
, , - , ,
- -
Macintosh.
Python, .
r r Python
.
Python Python Tutor,
.
: http://mail.python.org/mailman/listinfo/tutor.
Tutor (~), : ,
.
,
Python. , ,
. ,
.
Python - r
Python . ,
. , Python,
. Python,
. , Python ( -
!).
- , Python
.
r Python Windows
Python,
. :
Python Windows
.
34 1. . Game Over
Python Windows .
1. Python Windows - (www.co-
urseptr.com/downloads). Python Software
python-3. 1 . ms i.
2. python-3 . 1.msi - Python Windows.
. 1.2.
3. .
, Python 3.1 .
~~~~~~~~~~~~~~~~~~~~~~~~
www.courseptr.com/downloads - -, n
. , , ,
, .
. .
CJ Pythonl
python
for
l:\Python31\
windows
1 < Back ![ Next > 1 Cancel
. 1.2. Python
Python
Python .
, Windows,
Python http://www.python.org
. Python
. 1.3.
IDLE 35
FOUNDJON
productlvltf and lower malntenance costs.
t-
Help
Pack11g1 lnde
osi.pproved open source ltcense ~~i~M!iiili
Qulcltllnks~.7.2)
DocumvntaHon
Wlnd~ /rstaller
New ro P'ython or choosing etwEen Python 2 and Python
~on 2 or ptthon 3
? Read
[
Soun:1D1'itribution The F\tf1on So~re Foundatlon holds the intellectual property rights jl:nlng users uch
Q11lck llnb .2 .1) behlnd Pyttion, underwrites the Pyeon co[lference, and funds other RtkSpte, /ndustnal L!ght nd
. 1.3. Python,
~~~~~~~~~~~~~~~~~~~~~~~~~~
, Python. ,
, , Python .
IDLE
Python
IDLE. ,
. -
. ,
. IDLE : .
, -
Python. Python ,
, , .
. ~
Python 3.1 ~ IDLE (Python GUI). , ,
. 1.4.
36 1. . Game Over
l,ol@~
' '
Python 3.1.1
(r311:7448, J.ug 17 2009,
"copyright", "credit3" or
17:02:12)
"lice~e()" for
[JIISC v . 1500 32
nre information.
it (Intel)] on t1in32
-
> 1
.1.4. Python.
Game Over
, Python!
. , - ,
.
print
, : pri nt( "Game Over" ).
, . (
), , .
Python. - ,
-
pri nt ( ) , ,
, . ,
.
~~~~~~~~~~~~~~~~~~~~~~~~~~
Python . ,
. n print( Game Over) , Print(Game Over)
PRINT(Game Over)- .
IDLE 37
, , ,
. , -
, , .
pri nt () - .
, , ,
. , pri nt ( "Game Over").
, .
, , .
pri nt () "Game Over". ,
Game Over.
~~~~~~~~~~~~~~~~~~~~~~~~
Python r ,
. .
2.
,
"Game Over", print( ), .
, . ,
~ ~ ~
, ,
() . .
"Game Over" - : , .
, , .
- , Python -
, - .
.
, , ,
Python. ~. ,
-. ~
. , , :
.
.
, ,
. , ,
primt( "Game Over" ), :
( : 'primt' ).
, pri mt. ,
, . . ,
, , :
.
, , , ( ,
, ) .
,
. , .
, Python, - pri nt -
. , , "Game Over"
.
. ,
:
.
, : . ,
, ,
. , IDLE
. , , .
,
, , , , .
w r
,
. File () New Window ( ).
, . 1.5.
() pri nt ( "Game Over")
Enter. ! ,
, .
, .
r
File Save As (
). game_over. ,
, .
~~~~~~~~~~~~~~~~~~~~~~~~
..
, IDLE, Python.
IDLE 39
7~ Untltied 1<;ol@l;...n...1
l J;.dl: Furmat "'-"' Qptfon '!'l)ndows IJ.elp
1
-
~~
. 1.5. . Pytho
Pyt.hcn .1.1 (r11:74'l, .lug 17 2009, 17:02:12) [JISC v.1500 2 bit (Intel)] on 1n2
"copyriqht", "cre:dit~" or "licee()" for more informe.tion.
>>> print. ( nGame Over")
~ OVer
>>> .,." RE3TART """",,.".,,."." ..... " " "" "."
>
Game OVer
> 1
11
, 1> . , ,
pri nt ( "Game Over" ),
, - Game Over.
(RESTART), -
: Game Over. :
IDLE, .
,
- , .
- , . , ,
, .
,
. ,
- , .
.
r Game Over
, Game Over IDLE.
, IDLE - .
, ,
,
.
Game Over ,
, , .
, , , . -
, .
, Game Over
. , , ,
Gamc Over -
. ,
. Game Over, :
Enter. .. Enter,
.
.
(www.courseptr.com/clownloads ), game_over.
Chapter 1, 1
~~~~~~~~~~~~~~~~~~~~~~~~~~
, \Vindows+ R cmd,
. Python,
. - u.4t. . .
Game Over 41
# Game Over
# print
- , .
, .
.
. , -
, .
, ,
.
#. (
# ) .
. , IDLE
.
, .
.
, -
.
: ~ ?
, , , - ?~>
,
, , ,
. ,
,
.
r, .
. ,
.
, - ;
, - .
.
, - .
, :
, . , ,
.
. ,
pri nt.
42 1. . Game Over
print("Game Over")
- pri nt.
, Game Over.
Enter. . ,
Enter. Enter .
,
.
, ,
. ,
, , , i nput ) .
. ,
Python .
- .
Python ,
, ,
. , ,
. ,
Python .
'
t
, , ' i
' A/J,AUU
"'Jfl
' "
' "l,.
. ,,, !
-.,'r
: .
n ,
.
, ,
Enter . , .
, . ,
.
2 ,
-.
<< >> 1
,
. .
,
, (, , ) .'\f.
.
, :
s-, -
;
Python;
;
,
;
r r
&
,
1>,
. 2.1.
(
, ) . Python 2.,
Python 3.1 ,
# coding: 1251 # coding: utf-8. - . .
44 2. , -.
. 2.1. , 28-
!
,
.
,
: , .
, , , , >.>
. .
, ,
. -
- .
: "Game Over".
. , ,
.
.
. 2.2. .. .
# Game Over - 2
#
pri nt( " 'Game Over' 2. ")
print( " " . "". "")
print( "".
"-".
"")
print("Bo". end=" " )
pri nt ( " ...")
print(
1 _I / 1 1 11 1 1 _I
1 1 / / 1 1 1 11 11 1 1 I_
1 1 _ / _ I 1 / 1_1 1 1 1 _I
1 l_I 1 / / 1 1 11 1 1 1 I_
' / / 1 l_I / / l_I 1__ 1
/ _ \ l l // 1 _11 - \
111111 / / 1 I_ 1 l_I 1
1 1 1 1 1 1/ / 1 _I 1 _ /
1 l_I 1 1 1/ / 1I_1 1 ' '
, _ _1 1_1 1_11_1 \_\
:
, ( ' ' ),
46 2. , -.
,
. ,
. , , "
'. '
" - . , " ". "
" - .
, , ,
" ''.
- . ,
, , , .
pri nt ( ).
, .
:
pri nt "".
"-".
"")
, .
47
pri nt )
. , pri nt ()
. , -, ,
. , ,
print( ). ,
pri nt ()
. :
-------------------------
, , .
6, .
, , , Game Over
. :
/ _J / 1 1 11-11 _I
11 / /11 1 11 11 1 1 I_
11 !_ J 1 1 1_1 1 1 1 _J
1 l_J 1 / / 1 1 11 1 1 1 I_
' 1 1 1 J_I 1 1 l_I l __ I
/ \ 1 1 / / 1 _11 \
1 1 1 1 1 1 / / 1 I_ 1 J_I 1
1 1 1 1 1 1 / / 1 _I 1 1
1 l_I 1 1 1/ / 1J_1 1 \ \
\ _ _ ! I_/ 1_11_1 ,_,
. ,
. , ,
48 2. , - .
; ,
.
,
, .
s-
s- ( )
.
.
s- : (\)
. ,
s-, ,
.
, , ,
~;. - , .
~;. - , s
,
. . 2.3.
. 2.3. ...
s-nn 49
,
. - (courseptr.com/downloads)
Chapter 2; fancy_credits.py.
#
# s-
printC"\t\t\tBoopaaee ")
printC"\t\t\t \\ \\ \\ \\ \\ \\ \\")
print("\t\t\tpapaoa ")
print("\t\t\tMaa ")
print("\t\t\t \\ \\ \\ \\ \\ \\ \\")
rint"\n :")
printC"oey \'\'.
\"\".")
#
printC"\a")
inputC"\n\nHae Enter. .")
~~ ,
.
, s-
\ t. \t :
s-
, , , ,
.
.
, ,
.
, , , ,
,
s-. :
.
( ,
\ \ ), :
printC"\t\t\t \\ \\ \\ \\ \\ \\ \\")
printC"\t\t\t \\ \\ \\ \\ \\ \\ \\")
s-
\ n.
50 2. , -.
, , . \n ,
, .
:
print("\nOreoe :")
\ n,
:.
, ( ,
) .
s- \', \".
.
, :
rit(" \'\'.
\"\".")
.
, .
1. \ '\ ' ''.
2. \' .
3. \"\" "".
4. \" .
:
! pri nt ("\")
. s- \ -
. pri nt()
. ~ , ,
.
- \.
s-
, , IDLE.
, , . , ,
print( "\"). IDLE,
, .
Windows, ,
, .
, s-, , :
. . 2.1
s-.
51
n 2.1. s-
n
\\ . : \
\' , . : '
\" . : "
\ .
\ .
\t - .
, , .
,
- .
r r
~ .
. 2.4. ,
.
- (www.courseptr.com/downloads)
Chapter 2. si l ly _stri gs. .
. 2.4. ,
#
#
rit(" + " '+' . ")
52 2. , -.
, , - ,
. -
pri nt:
print("e " + " '+'. ")
+ " " "
'+' . , .
: ,
, .
~ - -
. , , , ""
"", "", " ".
;
.
,
, :
,
, 22 .
.
. .
\ (
), .
n 53
, ( ,
);
.
, , -
. , -
,
.
r
, ,
:
rint("" * 10)
:
"
" - ".
*, , .
- , ;
.
,
* .
.
, , .
.
- .
. , -
, -
. , Python
; ,
.
r r r
- . -, ,
, .
, . - ,
- .
~ - ( )
. . 2.5,
.
54 2. , -.
. 2.5. Python , , ,
- (www.courseptr.com/
downloads) Chapter 2. word_problems. .
#
#
print("Ec 800 40 .")
print("o 20 . ?")
inut(" . Enter.")
print("800 - 40 + 20 =". 800 - 40 + 20)
print("\nEc . . ")
rint(" 6 3 .
?")
inut(" . Enter .")
print(" * 3 =". 6 * 3)
print("\nEc 19 (
).")
print(" . ?")
inut(" . Enter . ")
print( "19 / 4 =". 19 / 4)
print("\nEc . 107 . ")
print("pea . ?")
inut(" . Enter ." )
print("l07 // 4 =" . 107 // 4)
print("\nEc 107
.")
print("o ?")
inut( " . Enter. ")
print( "107% 4 =" . 107% 4)
input("\n\nHae Enter. . ")
55
, .
, , , . Python
;
, , - . (int)
( fl oat) . . ,
1, 27, -100 - , 2,376, -99,11,0 - .
. , ,
. , 800 - 40 + 20 40
800 20, 780. ,
800 - 40 + 20 , 780.
-
, ;
, . 6* 6 3 18; ,
19 / 4 19 4 - 4. 75.
, , .
: 107 / / 4. //
, , . // ( )
, ,
( ).
1, ;
. 107 / / 4 26.
, 107 % 4, , ,
. %
. 107 % 4 3.
. 2.2 .
6n 2.2.
+ 7+3 10
- 7-3 4
* 7*3 21
1 () 7/3 2.3 33333 33333 33335
11 ( ) 7 // 3 2
/ 7%31 1
-------------------------
8 n. 2.2 , . , 7
3 2.3333333333333335. n, . n
, ,
- .
decimal. Python.
56 2. , -.
.
. Python -
.
. 2.6,
<.:.
. 2.6.
. 2.6,
. ,
. -
(www.courseptr.com/downloads) Chapter 2. greeter. .
#
#
name = ""
print(name)
rint(".". name)
input("\n\nHae Enter. . ")
-
. ,
- ,
. -
57
. , ,
: - .
, , , ,
:
name = ""
. name,
- "".
, .
, name , ,
~~~~~~~~~~~~~~~~~~~~~~~~~~
, ( ) -
, , -
. Python ,
. ,
, , - .
, , ,
:~> 5.
- .
, .
, , :
printCname)
"", print("Bac").
, :
,
. - name,
person, guy alpha7345690876:
.
; Python
, . , :
.
. ( ) scope
, . - . . .
58 2. , -.
, ;
.
,
. ,
, 4 4
( : alpha7345690876 -
, , ). , .
. ,
, , , .
, , score , s. ( -
,
, . ,
, , , .)
. ,
, .
, , hi gh _score hi ghScore?
. , ,
,
.
. -
. , ~, ,
Python, .
,
( Python
).
.
, . ,
, , : persona 1_checki ng_account _
1ance'? , . ,
, , . , ,
.
15 .
~~~~~~~~~~~~~~~~~~~~~~~~~
, ,
. -
.
4, , ,
. ,
, 4. ,
, ,
59
, .
, - .
,
: .
, ,
, . . 2.7.
. 2.7. m
. , ,
.
- ( www.courseptr.com/
downloads) Chapter 2. persona l _greeter. .
#
#
name = inut(". ? ")
print(name)
rint(".". name)
input("\n\nHae Enter. .")
input()
:
i nput ( ) .
i nput () , .
, .
input() ". ? ". . 2.7
, i nput ( ) .
, - . Enter
input() , .
, , name.
, , ,
i nput ( ) , .
, ,
,
.
,
, : i nput ( )
. i nput ( ) - .
, ; ,
. -
, . ,
i nput ), - ". ? ".
, .
i nput ( ) ,
.
,
. ,
name . :
print(name)
name, :
rint(".". name)
".", name.
, ,
. - ,
Enter:
input("\n\nHae Enter. .")
i nput () .
, ( )
Enter, , ,
. - - ,
, . -
, . ,
Enter, i nput ( ) ,
. .
61
Python .
- .
. :
.
, , ~.
, ,
- ~ .
: ,
~. 1943 IBM (Thomas Watson).
~
-. (
, 3 . .)
. 2.8.
. 2.8. ,
- (www.courseptr.com/
downloads) Chapter 2. quotati on_manipul at i on. .
#
#
# . 1943 . IBM
quote =". ."
rint(" : ")
62 2. , -.
print(quote)
print("\nOa :")
print(quote.upper())
print("\nB :")
print(quote.lower())
print("\nKa :")
pr;nt(quote.title())
print("\nC -- :")
print(quote.replace("y ". " "))
print("\nA :")
print(quote)
input("\n\nHae Enter. .")
r r
, -
. , , :
print(quote.upper())
, ,
quote, .
upper( ). - 4
, . , quote upper ()
, .
, , , :
print("YMAIO. .")
, ,
, .
, , , .
. , .
, , , i nput ( ) ,
,
. , , :
pri nt (upper())
, ", , ,
, , , ,
. . ,
. , upper( ) ,
replace( ).
:
print(quote.title())
quote, ,
, , - .
, titl ( ).
:
, quote
" " " ".
rep 1() 1-: ,
, . .
- :
, .
.
:
print("\nA :")
print(quote)
. 2.8 , quote . :
. .
, ,
. 2.3.
2.3.
u() ,
lower() ,
swapcase() , :
capitalize(} , , -
title(} , ,
-
strip(} , (, ,
)
l(old, , old new.
new [,max]) max -
: ,
.
, . ,
.
64 2. , -.
( )
,
.
,
- . , ,
, ,
. ,
, .
. 2.9.
. 2.9. , ! ?
, . ,
. ,
, , .
, , ,
, .
(www.courseptr.com/downloads) Chapter 2.
trust_fund_bad . py.
# ( )
#
pri nt (
. .
.
. . -
. . .
65
, .
: . 2.9. -
, .
, . ? ,
.
.
,
, , , , .
.
- , .
, , - ,
. , ,
. ?
, i nput ( ) .
, ,
. : ,
.
, !
, , ? , -
,
. ? , ,
!
I:
+ , .
, .
, , , . nnoxo, ()
? , . .
66 2. , -.
, ~. -
, i nput ( ), .
,
.
( w)
~ ,
.
. 2.1 .
. 2.1.61 300 -
.
- Chapter 2 t rus t _fund _good. .
# ( )
# type conversion
print(
. .
.
. . -
. . .
r= i nt ()
ent = i nt ( i nput (" '1 : "))
jet = int(input("Apea : "))
gifts = i nt ( i nput (": "))
food = int(input("Oe : "))
staff = int(input("aoae <. . . ): "))
guu = int(input("aa : "))
games = int(input( " : ))
total = + ent + jet + gifts + food + staff + guu + games
int("\n :". total)
input("\n\nHae Ente. .")
. ,
:
()
.
: i nt () , r,
.
car.
:
ent = i nt( i nput (" : "))
jet = int(input("Apea : "))
gifts = int(input("oap: "))
food = int(input("Oe : "))
staff = int(input("aoae (. . . ): "))
guru = int(input("aa : "))
games = i nt ( i nput (" : ))
, . ,
input() int() - .
, , . ,
, ~ , r
~ . i nput () ,
i nt ( ) .
, rent, i nput ()
, .
- ; i nput () ,
int() .
, i nt () .
ent.
.
68 2. , -.
.
. 2.4.
n 2.4. ,
float(x) float("lO.O") 10.
int(x) int("lO"} 10
str(x) str(lO) '10'
,
. , , ,
.
food, :
food = food * 52
food, 52 ,
food. , :
food *= 52
*= - .
food 52 food,
.
, ,
- .
. 2.5.
2.5.
*= *= 5 x=x*S
/= /= 5 = / 5
%= %= 5 = % 5
+= += 5 x=x+S
-= -= 5 =-5
, ,
~ - .
- , .
- (www.courseptr.com/
downloads) Chapter 2. usel ess_trivia ..
01 69
,
. , ,
:
#
#
# /
# / . . .
-------------------------
8 ,
. . (:1-j
.
i nput () ,
:
------------------------
: ,
. ,
.
name r
name - :
print("\nEc . : "
name. l ower ())
print("A . : ". name.upper())
- , , -,
. ,
, , .
, , , ,
4~ .
70 2. , -.
called = name * 5
print{"\nEc ".)
print("o :")
print(called)
11 ed
name. -
called.
365 , 24 , 60 , 60
,
moon_weight sun_weight
,
1 :
moon_weight = weight / 6
print("\naee . ". moon_weight. "?")
sun weight = weight * 27.1
print( " . ", sun_weight. ". (. .
".)")
, ,
. moon_wei ght , 1/6
weight. 27,1
, sun_weight , weight * 27 .1.
Enter,
:
, , - .
, , ,
. - . .
71
, ,
. s
. , .
: ,
. , ,
.
, .
, , , ,
.
: . ,
. - 11
- .
, .
.
r ,
. : 15 20 % .
,
. : , ,
, .
, .
.
,
3 while
.
<< >>
-
- :
. ,
, , .
,
- . :
ra nd i nt ) ra nd ra nge );
if ;
l se -
;
l i f,
;
whi l :;
. ,
, :
1 100,
. ,
: ,
. ,
. . 3.1.
. -
:
73
, , , . .
, ( ) , Python
.
. 3.1. - !
~~~~~~~~~~~~~~~~~~~~~~~~~~
Python ,
, , , . (
) . , , http://
www.fourmilab.ch/hotblts/.
.
- . ,
, , .
: , , .
, .
. 3.2.
- (www.courseptr.com/
downloads) Chapter ; craps_rol 1er . .
#
#
import random
# 1 - 6
diel = random.randint(l. 6)
die2 = random.randrange() + 1
total = diel + die2
print("p " . diel. "". die2. ". ". total)
input("\n\nHae Enter. . ")
74 . , while .
. 3.2. ! 7 :
random
import. ,
random:
import random
- , ,
. ,
. , random ,
.
, -
,
, . ,
random.
randint()
random randi nt( ),
. randint() :
random.randint(l. 6)
, randi nt() ,
random.
: _. _ .
. ,
. : ,
if 75
, . random. randi nt )
, randi nt ) random.
.1
.
randi nt() r
, . , ,
r 1 6, 1, 2, 3, 4, 5 6.
.
randrange()
random randrange( ),
. randrange( ),
-
. :
() ( ). random. n -
drange() , 1, 2, 3, 4 5. 6? , randrange()
, .
, di 2 ,
1 :
: randlt() randrange(),
.
, .
n if
.
. i f
,
, , .
r
~ i f ,
.
, .
. 3.3 3.4.
- (www.courseptr.com/downloads)
Chapter ; password. .
76 3. , while .
. 3.3. -, !
. 3.4. , , secret? ..
#
# if
print('opo " ". ')
print('-- - \n')
password = inut(" : ")
i f password == "secret":
print( " ocy ")
input(" \ n \ nHae Enter . . ")
---.------~ ; : : .1 : ---
,
. , , secret.
. -
, . , ,
. -
. .
if 77
, if
>.> :
if password == "secret":
print("ocyn ")
. , ,
. password "secret ",
. "secret",
, , i f, .
n
i f , ,
. , , ,
: ,
. , : >.>,
, , .
Python -: True - ,
F l se, , - .
. , >.> ,
i f, - password == "secret ". ,
password - "secret ". password "secret ",
- True, - Fa l se.
,
t .
>.>: >.>, ==.
~~~~~~~~~~~~~~~~~~~~~~~~~~
. ,
,
. password =
secret - ,
password secret. password ==
secret - ,
True False. ,
-.
>.>, .
. 3.1.
3.1.
-- 5 == 5 True
!= 8 != 5 True
,
78 . , while .
3.1 ()
r
> 3 > 10 False
< 5<8 True
>= 5 >= 10 False
<= 5 <= 5 True
~~~~~~~~~~~~~~~~~~~~~~~~~
,
, . , ;
fr -~ . , , <
True, ( ).
Pytho . ,
, r <,<=,> >=.
, . 10 > .
, , - l.!J- .
, i f, ,.
pri nt (" ") - .
. ,
. ,
: - .
, i f.
( ), ,
. ~:~.
pri nt( " ").
,
,
. :
if password == "secret":
print("ocy ")
print("opo ! . . .")
,
! . . "
,
.
~~~~~~~~~~~~~~~~~~~~~~~~
Python , .JI
( , ). ,
. . -, :
, . -,
. , n
.
- .
if else 79
r r
.
,
. - i f,
, , , .
, .
, ,
.
if else
, , :
- , - - .
1se i f.
r /
, , ,
, .
/ el se.
, , ( . . 3.4 ).
. 3.5.
. 3.5.
n>
- Chapter ;
granted_or_denied. .
80 3. , while .
# /
# else
pri nt (' " ". ')
print('-- - \n')
password = input( " : ")
if password == "secret":
pri nt ( " ")
else:
print("ocy ")
input("\n\nHae Enter. .")
else
: i f
l se:
if password == "secret":
pri nt ( " " )
else:
print("ocy ")
password "secret",
, . (
else) .
i f l se
: - ,
, - 1se.
l se i f : l se,
. l se ,
if , if l se
. .
elif
,
l i
f. ,
.
1970- - -, ! -
, (Mood Ring). ,
. .
- :
, .
. 3.6 , , .
elif 81
. 3.6. ,
, . ,
,
.
, i f
l i f , r . (
, .
,
. )
- (www.courseptr.com/downloads)
Chapter ; mood_computer . .
#
# elif
import random
print(" . .")
print("a. ...")
mood = random.randint(l. 3)
if mood == 1:
#
pri nt( \
1
1
1 <
1
1.
1
'
... '
""")
82 . , while .
elif mood == 2:
#
print( \
<
11 "tl)
elif mood == 3:
#
print( \
1
1
1 <
1
1
1 '
11 11)
else:
print("He ! ( . .)")
pri nt (" ... . ")
input("\n\nPress the enter key to exit.")
elif
, 1i f,
, .
:
if mood == :
elif mood == 1:
elif mood == 2:
, i f,
1i f ( else if). 1i f
.
, :
mood . ,
mood . . ,
, ,
n elif 83
mood . , , ,
, , , mood .
.
~~~~~~~~~~~~~~~~~~~~~~~~~
, if elif
,
. , ,
. , mood
, .
,
.
.
mood ,
l se :
! ( . .).
mood 1, 2 3, .
. : ls-
.
~~~~~~~~~~~~~~~~~~~~~~~~~
, else
: ,
. , - ,
else ,
.
, ,
.
. 3.2.
.& 3.2. -
n
if <>: . <> ,
<> <> , -
while
.
: ,
. , :
- , - , ,
, .
, , -:
, .
- .
, .
whi l .
r
,
. , ,
, , ,
,
. ,
. whi l
. , . 3. 7.
. 3.7. - ,
, : ? -
.
- (courseptr.com/downloads) Chapter 3.
three_year-old.py.
01 while 85
#
# while
print("\topo ' '\n")
rint(" .")
rint(" .\n")
response = ""
while response !=" .":
response = input("oey?\n")
print("A. .")
input("\n\nHae Enter. .")
while
:
whi l , .
- i f.
, if whi l ,
. ( , -
) , , whi l
, ,
. .
: response =
i nput ("?\ n" ). ,
" .", - .
response ! = " ." ,
: print( ". .").
whi l .
, :
. ,
, .
- response. ,
, " . " ,
.
. ,
. :
response = ""
~~~~~~~~~~~~~~~~~~~~~~~~~~
,
, .
86 . , while .
- . , response "".
response , "",
, .
, whi l .
. , ,
, :
,
, ,
. , - .
( ) , ,
. !
, -
..
counter =
while counter <= 10
print(counter)
, ,
1. , , .
,
counter . :
( ) .
.
, . .
, - : .
, ?
87
!> -
.
. , ~.:
, . .
. ?
- Chapter ;
losing_battle-bad.py.
#
#
print("Baeo .")
rint(" .")
rint(" .
.\n")
health = 10
trolls =
damage = 3
while health != :
trolls += 1
health -= damage
rint(" . . "\
" ". damage. " . \n")
print( " " . trol l s. ".")
print("Ho ! . ")
input("\n\nHae Enter . . ")
, . 3.8. ,
Qrl+C.
. 3.8. , .
?
88 . , while .
r
, . ,
.
, , :
.
, ,
, .
- .
, .
:
whi 1
:
,
, , whi l
, , .
. ,
89
~ ~ .
:
- Chapter 3;
l os i ng_batt l e-good. . , hea l th
, .
, :
. 3.9. , . ,
, ,
35 + 2,
: 37. , 37 ? Python
. ,
. 2749, 8. 6, "",
, "" (True) (Fa l se ).
, :
True Fa l se . ,
.
90 3. , while .
,
. ~.>
, .
,
. - ,
. . 3.10 3.11 .
. 3.1 . ,
. 3.11. -
!
, , , : -
. ,
. -
91
( - ).
- (www.courseptr.com/downloads)
Chapter ; ma i t re_d. .
#
#
print("opo --!")
print("Kaec. .\n")
money = int(input("Coo ? "))
if money:
pri nt (" . . .
. .")
el se:
rint(". . .")
input("\n\nHae Enter. .")
i f money:
, money :
money . ,
, - . ,
:
if money != :
, .
. 4 - .
, - ,
. : ,
- . , ,
, - . "" ,
- . ,
/ - . ,
- ,
.
, , ,
. :
, , , - .
4
, .
, ?
92 . , while .
. ~.> ,
, - , ,
. , >.> .
.
r
~.> 1 1
~.> . ,
5 . ,
. 3.12.
. 3.12. 5 cotinue,
break
- Chapter ;
fi ni cky _counter . .
#
# break continue
count =
while True:
count += 1
# . count 10
if count > 10 :
break
# 5
if count == 5:
continue
pri nt (count)
input("\n \ nHae Enter. .")
93
break
:
while True:
, ,
- .
:
# . count 10
if count > 10:
break
count
1, 11. -
break ( " ) .
continue
count :
# 5
if count == 5:
continue
cont i nue , .
, , ,
. , count
5, , pri nt ( count),
. .
break continue
break continue -
. . ,
, ,
break continue; ,
. break conti nue, -, :
, , .
Python
. ,
, ~>
.
.1 ,
. ~~ .
94 . , while .
,
. ~m61-l .
,
.
.
~ - ,
.
( , ?).
,
() .
, - ~.
, .
, ,
. , ,
.
. 3.13-3.15.
. 3.13. ,
. 3.14. ,
95
. 3.15. ,
- Chapter ;
1 us i ve_network . .
#
#
rint("\t ")
print("\too !\n")
securi ty =
username = ""
while not username :
username = inut(" : ")
password = ""
while not password :
password = input("apo: ")
if username == "M .Dawson" and password == "secret" :
rint(". . ")
security = 5
elif username == "S.Meier" and password == "civilization":
rint(". .")
security = 3
elif username == "S.Miyamoto" and password == "mariobros" :
print("oporo . .")
security = 3
elif username == "W.Wright" and password == "thesims":
print("Ka . ?")
security = 3
l if username == "guest" or password == "guest":
print("opo .")
security = 1
else:
pri nt( " . . -
. \n")
input("\n\nHae Enter. .")
96 3. , while .
n , n r .
n n -n (). -
n , .
, nn n - n.
r not
, -
, Enter ( )
. ,
, - :
username = ""
while not username:
username = i nput (": ")
, whi 1, not.
, not (~).
not,
. Python not -
,
. , not username
, username , not username , username
. :
r and
,
, ,
. , , , S. Mei er
ci vi 1i zat i on . , . -
97
and.
, -
.
or
, .
, guest
. , :
.
~> - ,
. , ,
, ( )
.
.
- , !
, 12
. ,
.
. ,
;
, .
. .
.
r
1 ,
, - . -
, ,
.
99
. ,
. , , ~ -
, , , .
~. :
$100
10000
:
, .
,
. -
( ) . ,
, .
Python: i f 1se,
.
, , ,
. ~,
. ,
, .
- .
,
.
, ,
~ .
~ ~:
. .?
,
. :
, .
100 . , while . r
- , .
, ,
.
40 ~ ,
. , , Python,
, /
.
, :
- ,
. -, ,
: . -,
, ,
------------------------
n r - r.
, r ,
.
1 100
1
. .
1
.
r n 101
. ,
, Python.
- Chapter ;
guess_my_number.py.
, :
#
#
# 1 100
# . .
# /. . .
#
random
.
random:
import random
,
:
#
the_number = random.randint(l. 100)
guess = int(input("Bae : "))
tries = 1
the_number , .
1." 100,
random. randi nt( ). i nput()
, i nt ( )
. gL.ess. ,
tri es, .
1.
102 . , while . ~
. ,
, . ( guess)
(the_number).
, , - .
#
while guess != the_number:
if guess > the_number:
pri nt( "".")
else:
print( "."")
guess = i nt ( i nput (" : "))
tries += 1
, guess the_number,
guess != the_number, , ,
. :
, Enter:
inut("\\n Enter. .")
, . ,
,
.
if ( if-el se if-el if-el se),
. whi 1 -
.
, , ,
. ,
,
.
103
. - - . - -:
- , -
, .
, 100 ,
, - .
,
. n ( ),
.
. , 1 100
, . , ,
. ,
Pytho.
4
.
<<>>
for,
, , .
,
, .
- ,
.
, - .
,
.
, :
for ;
range() ;
;
;
;
.
~, . 4.1,
, .
- ,
, (
, , ).
,
. -
.
for 105
. 4.1. . ,
for
-
whi l . ,
- . for
, . for -
. , ,
, , .
for
, .
.
. for,
. , .
. . 4.2.
for.
- (courseptr.com/downloads) Chapter 4.
loopy_string.py.
#
# for
word = inut(" : ")
print("\nBo :")
for letter in word :
pri nt ( l etter)
input("\n\nHae Enter. . ")
106 4. f, .
. 4.2. for , ,
for
- for,
:
, ,
, .
, , . , ,
1etter ,
" ". pri nt L .
,
1etter - "". ,
, "".
f 107
for.
, , . -
. .
, Pytho for ,
.
for
for, ,
. for, ,
, i n,
, , , . .
for
. for range( )
.
~>.> .
, , range()
for ,
. , . 4.3.
- (courseptr.com/
downloads) Chapter 4. counter. .
#
# range(J
pri nt( ":")
for i in rangeOOJ:
pri t ( i . end=" " )
rint("\n\n :")
for i in range(O. 50. 5):
print(i. end=" ")
print("\n\nocae :")
for i in range(lO. . -1):
print(i. end=" ")
input("\n\nHae Enter. .\n")
,
- r t i, j, k.
, . ,
, , , i, j k- .
:
for i 'n rangeOO):
pr'nt(i. end=" ")
for , 4'
. , ,
. , ,
range( ). , range()
. range()
, (
). , , range( 10) [0. 1.
2. 3. 4. 5. 6. 7. 8. 9].,.
i , ; i
1, , . . ,
i 9, .
~~~~~~~~~~~~~--~-~--~-~-~--
range() ,
r . ,
, , . ,
.
range(), http://www.python.org.
-----------------------
, , .
.
. , , 5.
n: n 109
,
, :
n for .
, n, n - ,
for, n-. n,
!. , :
for _ in rangeClOJ:
rint("! ")
nr:
r
, - :
.
, , Python
. ,
, , , ,
.
110 4. for, .
,
. ,
- <;>.
.
. 4.4.
. 4.4. len() in -
- ( courseptr.com/
downloads) Chapter 4. message_ana lyzer. .
#
# len() in
message = inut(" : ")
pri nt ( "\n :". l en(message))
pri nt( "\n . ' . ")
if "" in message:
rint(" .")
else :
print("e .")
input("\n\nHae Enter. .")
len()
,
. :
. !, , (
), 1.
in
.
,
:
if "" in rnessage:
rint(" .")
el se:
print("e .")
if : "" in message. ,
mes sage, " ", , -
. . ! , , Ti.>.
, " i n message
"... ". , ,
!, ,
... ".
. i n , ,
- .
, , i n -
. - ,
, , .
for .
.
. , ,
, ,
, , , -
. ,
, ?
.
.
( ), .
.
r
~.>
, .
112 4. for, .
- "",
, .
.
. 4.5.
. 4.5.
- (courseptr.com/
downloads) Chapter 4. random_access. .
#
#
import random
word = ""
pri nt (" word : " word . "\n")
high = len(word)
low = - len(word)
for i i n range(lO):
position = random.randrange(low . high)
pri nt ( "word[". posi ti on. "J\ t". word[posit i on])
input("\n\nHae Enter. .")
word = ""
. ,
( , ),
. - >.> -
( -
r 113
). - ~" - 1; - ~" -
2 . .
. ,
word , word[ ].
: .
:
>>> print(word[lJ)
>>> print(word[2])
>>> print(word[J)
>>> print(word[4])
>>> print(word[5J)
~~~~~~~~~~~~~~~~~~~~~~~~~-
, , n -
- . . ,
. 5,
. :
, ,
.
:
. - ,
. , , , - .
, ,
. , , -
"":
>>> print(word[-2])
>>> print(word[-3])
> pri nt (word[ -4])
>>> print(word[-5])
>>> print(word[-6])
.
. 4.6 ,
"".
2 4 5
-6 -5 -4 -3 -2 -1
. 4.6.
r
~.>. ""
- , .
random:
import random
,
, .
: -6 5
( , word). ,
random. randrange()
. ,
:
high = len(word)
low = -len(word)
high 6, ~~.>
. l ow ~~.>, -6.
, .
r 115
, -6 5.
random. randrange() . ,
( )
( ). , , :
posi ti on = random. randrange( 1ow. hi gh)
position -6, -5, -4, -3, -2, -1, , 1, 2, 3, 4 5.
, ,
"".
, , .
,
:
for i i n range(lO):
position = random.randrange(low. high)
print("word[". position. "J\t". word[position])
, :
. ,
- , - .
- . , ,
, "Game Over ! " ,
. .
, , , . ,
- :
. ,
"", "".
, , ,
. ""
name. - "",
, , name. -
, , , . ,
, . 4.7.
r. ,
, , ,
.
116 4. for, .
oame )( G
. 4.7. name ,
- .
, .
. , ,
, . , ,
:
> word="rpa"
> word[l]=""
Traceback (most recent call last):
File "<pyshell#l>". line l. in <module>
word[l]=""
TypeError: 'str' object does not support item assignment
, , "" "" (
, ).
~ ~. ""
- word[l]. :
. ,
(
). ,
, .
+, .
, .
, , , ,
.
~
.
, . 4.8.
117
. 4.8. for ,
. - ,
. ,
, , - .
- (courseptr.com/downloads)
Chapter 4. no_vowe l s. .
#
#. for
message = i nput (" : ")
new_message = '"'
VOWELS = "iu"
print()
for letter in message:
if letter.lower() not in VOWELS :
new_message += letter
pri nt (" : ". new_message)
print("\nBo :". new_message)
input("\n\nHae Enter. .")
r
new_message , :
VOWELS = "iu"
VOWELS . , ,
,
, .
, .
.
118 4. for, .
, (
).
. -,
. , ,
, "aei u", VOWELS.
, , ,
, , , -
. -,
- , .
,
, .
,
~~~~~~~~~~~~~~~-----------------------
, , .
( r )
, Python, , .
. , ,
, .
'
. r. Python, ,
.
---- - - .. - .. --- -- ----- - - - -- ----- -- - -- ----- ---------------- - - --------------- - - - - --- ------ -. - ------- ..]
.
, .
. , -.
, . ,
.
: , ,
,
. , ~~ :
, i n
. letter. lowerC ).
~~~~~~~~~~~~~~~~~~~~~~~~~~
, , ,
. , , , () ,
. n ,
- (, ),
.
. , :
winner, , ; .
:
name.lower() == winner.lower()
, name wi nner
, . ,
"" "" . "" "",
"" "".
-, , , ,
+= - . ,
. :
new_message += letter
, :
r
, ,
.
.
. , ,
, - .
- .
,
- .
~ "" .
. ,
, .
. 4.9.
120 4. for, .
. 4 .9.
, ,
, .
- (courseptr.com/
downloads) Chapter 4. pizza_sl icer . .
#
#
word = ""
print(
1 2 3 4 5
+---+-- - +---+---+ - --+
1 1 1 1 1 1
+---+---+- - -+ -- - + - --+
-5 -4 -3 -2 -1
rint(" ''.
.")
print(" Enter. . ")
start = None
while start !=
121
None
,
, , :
start = None
sta rt None.
Python , .
None (False).
. start
whi l .
,
- , :
. ,
. . 4.10 ,
"". ,
, . 4.6.
2 4 5
-5 -4 -3 -2 -1
. 4.10. .
/
,
. , ,
:
>>> print(word[l:J)
122 4. f, .
> print(word[-4:-2])
>>> print(word[-4:3])
word[O: 5) ,
. word[ 1: 3)
" ", .
, . ,
word[-4: -2) "", word[l :3),
. .
, , .
, word[-4:3) "".
~~~~~~~~~~~~~~~~~~~~~~~~~
, ,
, - word[2:1], Python ,
. ,
. , , , , .
4 ~
, ,
:
- .
, . ,
;
. , , word "",
word[ :4] , word[0:4J. ,
, .
word [2: ] - , word[2: 5].
, ,
. word [ : J - , word [: 5].
:
>>>print(word[0:5J)
>>> print(word[:J)
------------------------
, [:] -
. , ,
. -
.
, , .
, ,
. 1 1, , 11
.
.
, ,
. , .
- ,
:r ( , ).
, , ,
.
<<
-
RPG. ,
. , ,
( , ?). ,
, .
.
- , .
, - .
. 4.11.
- ( courseptr.com/dow
loads) Chapter 4. hero's_inventory. .
#
#
#
124 4. for, .
i nventory = ()
#
i f not i nventory:
pri nt ( " . " )
input("\nHae Enter. .")
#
i nventory = ("" .
"".
"" .
" ")
#
pri nt ( "\ n : ")
pri nt (i nventory)
#
print("\na. :")
for item in inventory:
pri nt ( i tem)
input( "\ n\nHae Enter . . ")
. 4.11. , ,
,
r
,
, .
- , .
, ,
:
i nventory = ()
: i nventory
.
r 125
, , , Python
. .
~ :
if not inventory:
pri nt ( " . ")
(F l se }, ,
, - (True).
i nventory , Fal se;
, not i nventory . ,
" . ".
enycroro
.
-,
. i nventory:
i nventory = ("" .
"".
"".
" ")
. , -
"", - "", - "", , , -
"u ". - .
, , .
, ( );
.
Python ,
.
~~~~~~~~~~~~~~~~~~~~~~~~~~~
, , .
, , : .
, - ,
.
. ,
,
- - .
n
,
, -
, . :
126 4. for, .
printC"\nCoepoe :")
pri nt i nventory)
, .
for, , i nventory,
:
print("\na. :")
for item in inventory:
print(item)
i nventory .
; ,
.
,
(),
. , , ,
.
~~~~~~~~~~~~~~~~~~~~~~~~~
, .
. ,
. , ,
. , , ,
, Python.
- . ,
, .
, for,
, i n, -
. , , .
2.0
.
;
. ,
.
. . 4.12.
,
, .
- (courseptr.com/downloads) Chapter 4.
hero's_inventory2.py.
127
. 4.12. - , , ,
,
r
,
~. ,
:
# 2.0
#
# for
i nventory = ("" .
"" .
"".
" ")
print("\na . : ")
for item in inventory:
pri nt ( i tem)
i nput("\nHae Enter. .")
len()
1en ( ) , :
, .
. , ,
. 1en () :
#
print("Ceac " . len(inventory) . "/-.")
i nput( "\ nHae Enter. .")
128 4. for, r .
~~~~~~~~~~~~~~~~~~~~~~~~~~
, r inventory ,
, .
in
( ),
i . , . ,
, :
# in
if " " in inventory:
pri ntC " .")
.
- , .
(),
:
#
index = int(input("\nBee : "))
print( " ". index. " ". inventory[index])
. 4.13.
-4 -3 -2 -1
. 4.13. -
.
. , , - ,
.
129
~ , ,
. :
#
start = int(input{"\nBee : "))
finish = int(input("Bee : "))
print("Cpe inventory[", start. ":". finish. "] - ". end=" ")
print(inventory[start:finishJ)
input("\nHae Enter. .")
. 4.14 ,
.
2 3 4
-4 -3 -2 -1
. 4.14. , ,
r
, .
:
, .
+:
#
chest = ("". " ")
print("B . :")
print(chest)
130 4. for, .
, , -
chest,
: "" " ". chest ,
. +=
i nventory chest, - -
inventory. ,
inventory, , , ,
. ,
inventory chest i nventory.
r r
, ,
~~. ,
. - ( oourseptr.oom/downloads)
Chapter 4. word_jumb 1. .
r
random:
# r CWord Jumle)
#
# -
# r -
import random
, . ,
WORDS :
.
# .
WORDS =("". "". "". "", "", "")
, WORDS ,
random.choice( ):
#
word = random.choiceCWORDS)
, .
- .
, word.
, . , word
correct. , ,
:
131
# .
correct = word
r
-
, .
, .
,
(, ,
). ,
:
,
. , ,
, . , .
-r~1,
, (
) .
r r
:
# ~ .
jume ='"'
j umb l .
,
.
r
wh i l . , ,
:
while word:
,
, word .
:
- -
word. word
.
132 4. for, .
n
,
:
position = random.randrange(len(word))
word[pos i t i on] , ~ word
~ j umb 1.
jume
jume.
word[position].
Jume += word[position]
word
:
,
, ,
:
#
pri nt
''!
. .
( Enter. .)
.
, Enter:
133
n
, . :
i f guess == correct:
print("a. ! !\n")
:
print("Cnaco .")
input("\n\nHae Enter. .")
. ,
range( ), ,
. ,
,
.
for, ,
- .
. , ,
, ,
. ,
, ~~.
' .
r, .
, .
r,
.
, r .
, .
, r, , , .
, - , .
, , t t, t - ,
t Her. .
.
5 <<>>
-
. - , ,
. , ,
, , , -
, . ,
. .
-
. , -
. ,
, - .
, :
, ;
;
,
;
,
;
;
.
- , ~..
- ,
, . ,
, .
,
. .5.1-5.3 .
. ,
, .
, ,
.
135
. 5.1. . .. . ?
. 5.2. !
, , - . .
.
, , - . ,
, , ,
.
136 5. .
. 5.3. ,
n
3.0
2.0:,
4.
, . 3.0 ,
. ;
, . . 5.4
.
. . 5.5.
. 5.4. .
, 2.0,
137
. 5.5. - , ,
,
i nventory; .
2.0 ,
, , , .
- (courseptr.com/downloads)
Chapter 5. hero' s _i nventory. .
# 3.0
#
# for
inventory = ["". "". "". " "]
print("\na. :")
for item in inventory:
pri nt ( item)
i nput ( "\n Enter. .")
len()
2.0.
l en() , .
#
pri nt (" ". l en( i nventory). "/ -. ")
i nput ( "\n Enter. .")
in
. i n
.
138 5. .
# in
if " " i n i nventory:
print("B .")
2.0. ,
, ,
.
#
index = int(input("\nBee : "))
pri nt (" ". i ndex. " ". i nventory[indexJ)
, ,
?
:
#
start = int(input("\nBee : "))
finish = int(inputC"Bee : "))
print("Cpe inventory['', start. ":". finish. "] - ", end=" ")
print(inventory[start:finishJ)
input("\nHae Enter. .")
.
, chest , .
, ,
.
#
chest = ["". " "]
printC"B . :")
printCchest)
printC"B .")
inventory += chest
pri nt " : ")
pri nt ( i nventory)
input("\n\nHae Enter. .")
, ,
, , . ,
,
139
. , :. :
. ,
, .
,
,
:
#
print("B .")
inventory[OJ = ""
print("Teep :")
pri nt ( i nventory)
input("\nHae Enter. .")
i nventory, ,
1 "":
inventory[OJ = ""
("").
, pri nt,
i nventory.
~~~~~~~~~~~~~~~~~~~~~~~~~
, ,
n . - ,
r, .
,
. i nventory [4: 6J [ " -
" J:
#
print("a V: .
.")
inventory[4:6] = [" "]
print("Teep :")
pri nt ( i nventory)
input("\nHae Enter. .")
- inventory[4] inventory[5] -
" ".
, i nventory
.
140 5. n.
de l,
:
#
print("B v.")
del inventory[2J
print("Bo :")
print(inventory)
input("\nHae Enter. .")
, 2,
"'', inventory. -
: ,
r, . , m
2 - : 3.
#
printC"Bop .")
del i nventory[: 2]
printC"B :")
print(inventory)
inut("\\ Enter. .")
, .
. ,
, .
r
.."d
-
. - . -
~ 141
: ,
, .
. 5.6.
. 5.6.
.
. ,
, . - scores -
, . -
. choi , .
None. -
(courseptr.com/downloads) Chapter 5. high_scores. .
#
#
scores = []
choice = None
- whi 1. ,
.
:
142 5. .
)
choice = input("Ba : ")
pri nt ()
, . ,
: .
#
if choice == :
pri nt .)
, whi l
. ,
.
1, el i f, :
#
1i f choi == 1 :
print("Peop")
for score in scores:
print(score)
2, ,
, score.
append( ),
score scores.
.
#
elif choice == "2":
score = int(input("Bne : "))
scores.append(score)
143
3, ,
. ,
, , . ,
.
#
elif choice == "3":
score = i nt ( i nput( " ?: "))
if score in scores:
scores.remove(score)
else:
rint("". score. " .")
, score
scores. , remove( ).
, ,
( score). ,
score, .
, . ,
score. remove()
, .
~~~~~~~~~~~~~~~~~~~~~~~~~~
remove().
, , . - ,
:
if score in scores:
scores.remove(score)
,
. 4:
#
elif choice == "4":
scores.sort(reverse=True)
sort() . ,
,
. , ,
. , sort ()
.
reverse True. . ,
.
144 5. .
~~~~~~~~~~~~~~~~~~~~~~~~~
, ,
. , , umers,
:
numbers.sort()
, , ,
el se. ,
.
#
else:
rint(". ". choice)
, , ,
, , ,
, .
. 5.1.
n 5.1.
nd()
sort() . reverse
. True,
reverse()
unt() ,
id() ,
isert(i, ) i
pop([i]) i .
i . , -
01
rmv()
,
-
, : ?*>
, , ,
145
.
. Python ,
, .
. , .
,
, .
, ,
, .
,
. , ,
.
, Python
.
, , , .
, 4' ~.
,
, , , .
, .
n
, .
, /,
/. -
. ,
. -
.
.
,
. , ,
. ,
.
:
r 2.0
4:~
. , ,
. ,
: ,
.
. 5.7.
146 5. .
. 5.7. ,
:
, ,
. ,
- . :
, nested .
- " " , - " ". ""), - [ " ".
"". ""].
,
.
. :
scores . - ,
, , : .
( !).
147
, 1 , - 1500,
3000.
~~~~~~~~~~~~~~~~~~~~~~~~~
nr , .
, n , :
. r
. n
r, scores.
1
, ,
:
- . ,
. ,
? ,
, , :
"" scores :
>>> print(scores[2][0])
scores[2J[OJ ,
scores 2 ( (" " . 3000) ), ,
, ( "").
,
.
, ,
, :
148 5. . 8
4~,
whi 1. ,
. - (courseptr.com/
downloads) Chapter 5. high_scores2.py.
# 2.0
#
scores = []
choice = None
whi le choice '= "":
pri nt(
2.
-
1 -
2 -
1, scores
score name,
.
# 1
elif choice == "1":
print("Peop\n")
pri nt ("\ t ")
for entry in scores:
149
2,
. entry.
( score ),
, ( name ).
,
, .
scores , 1, .
# add score
el if choice == "2":
name = inut(" : ")
score = int(input("Bne : "))
entry = (score. name)
scores.append(entry)
scores.sort(reverse=True)
scores = scores[:5J # 5
w
, , 1 2,
l se. ,
.
#
else:
rint(". ". choice)
, , , :
2 , .
, , ,
,
. , l anguage = "Python" ,
"Python" - ,
language, .
. 5.8, .
150 5. . ~
language
, "Python" , -
, - , , .
, Python .
: ,
. ,
~ . ,
; , .
? ,
(, , ), , .
, , .
,
. , .
,
, .
. ,
. ( .
-~ - 9.
?) -,
. -
,
, , ,
- (
- ?), -
<'/:~. ,
.
. , ,
:
mike------.
ho~ey _____.
. 5.9. mike, mr_dawson honey
, , ,
, . ,
(!)
, . ( !)
, , .
:
> honey[2J = " "
>>> printChoney)
[' '. ' '. ' ' J
, . 2 , 1<0
honey, "", " ".
.
,
, . Python .
2 honey,
, , .
:
> printCmike)
[' ' , ' ' . ' ' J
>>> printCmr_dawson)
[' ' . ' ' . ' ' J
2 , mi ke mr_dawson,
" ". ,
.
: ,
. ,
, .
, () , :
, - . ,
: ,
, r ! :
, .
,
. , ,
.
, , ,
. , , ,
. .
,
. ,
: . - ,
; Python,
4 - .
. .
, , ,
.
, -
- , , .
( )
.
, ,
, . . 5.10.
,
. , - . ~
- ( courseptr.com/downloads) u
Chapter 5. geek_translator.py.
#
#
geek = {"404": " . . 404 '
'.".
"Googling": "'. n -.".
153
. 5.1 . :
geek. .
, , : "Keyboard Plaque" : ".
".
. , - . , "Keyboard
Plaque" - , ". " -
. ~>.'> ()
. , "Keyboard Plaque" ".
" .
. ,
, .
~ - >.'> ,
. ,
, ,
- .
, , -
. ;
.
154 5. .
r
,
.
. , geek ,
:
> geek["404"]
" . . 404 ' '."
> geek["Link Rot"J
' -. '
, .
,
, - .
. .
,
. ,
, , , .
,
Python . : -
, .
~~~~~~~~~~~~~~~~~~~~~~~~~~
n , r , ,
:
in
,
. , , ,
. i n:
> if "Dancing Baloney" in geek:
print(" . Dancing Baloney. ")
else:
print(" . Dancing Baloney.")
. Dancing Baloney.
"Danc~ng Baloney", "Dancing Baloney" in
geek .
m 155
i n , .
, ,
i n . . ,
, .
,
. (, ) ,
.
get()
-
get ). , 110
. ,
, . :
getC) . - 1
. ,
. ,
" ".
get ) ,
; .
, , ,
, , - (
) None. :
> print(geek.getC"Dancing Baloney"))
None
~ r . ,
geek ,
. , ,
.
choice = None
while choice != "":
print(
-
1
2
3
4
pri nt ()
#
if choice == "":
print("o .")
1,
, . ,
. , (),
(), . ,
.
#
1if choi == "1" :
term = input("Kao ? ")
i f term in geek:
definition = geek[term]
print("\n". term. "". definition)
else:
print("\nY. :", term)
-
- ; ,
. 2,
:
#
elif choice == "2":
term = input("Kao ? ")
if term not in geek:
definition = inut("\n : ")
geek[termJ = definition
print("\nTep". term. " .")
else:
print("\nTao ! .")
.
,
. :
geek[termJ definition
=
~~~~~~~~~~~~~~~~~~~~~~~~~~
. ,
- , ,
. ,
.
, - .
.
-
3,
:
#
elif choice == "":
term = input("Kao ? ")
if term in geek:
definition = inut(" : ")
geek[termJ = definition
print("\nTep". term. ".")
else:
print("\nTaoo ! .")
,
:
geek[termJ = definition
~~~~~~~~~~~~~~~~~~~~~~~~~
Pytho ( )
. , , ,
. ,
.
-
4, l i f:
#
elif choice == "4":
term = input("Kao ? ")
if term i n geek:
del geek[termJ
print("\nTep". term. ".")
else:
print("\nHe . ". term. " .")
,
. i n ,
. , :
del geek[termJ
158 5. .
( term ) geek.
. de 1,
, ,
.
, 1se
.
~~~~~~~~~~~~~~~~~~~~~~~~~
, , .
, r .
1se ,
:
#
else:
rint". ". choice)
inputC"\n\nHae Enter. .")
n
, .
.
, .
,
.
. ,
- , .
, .
. , ,
.
, - . ,
, , , -,
.
. . 5.2
,
.
n 5.2.
gt(, []) . ,
. , ,
, None
keys()
159
values()
items() .
: - , - -
~~~~~~~~~~~~~~~~~~~~~~~~~~
, - (views) ,
items(), - - <.
keys(), values()
for. rr . ,
, ,
. .
Python (www.python.org).
r
.1 , ' ,
~~.
. , , ,
: - , .
-
, .
r
. , ,
. radom,
.
- ( courseptr.com/
downloads) Chapter 5. hagma. .
#
#
# "". .
# .
#
. .
# ~
import random
,
. ,
, - :
, - - 12 .
- .
.
160 5. .
.
- :
. , .
HANGMAN (
, ).
#
HANGMAN = (
1
-+-
1
/-+-
161
1
1 / -+- /
1
1 / -+-/
1
1
1 /-+-/
1
1
1
1 /-+-/
1
1
1 1
1 1
"'"')
, -
, :
AX_WRONG = len(HANGAN) - 1
162 5. .
, HANGMAN.
,
, .
HANGMAN ,
, .
,
.
; .
WORDS = "OVERUSED". "CLAM". "GUAM". "TAFFETA". "PYTHON")
. random. choi ( )
WORDS word.
#
word = random.choiceCWORDS) 1
- so_fa r - ,
. - ,
. , (
), , .
so_far = "-" * lenCword) # . -
wrong .
, , :
wrong = # .
, , , used.
:
used = [] 1 .
, ,
:
print("opo ''. !")
while wrong < MAX_WRONG and so_far != word:
printCHANGMAN[wrong])
printC"\nB :\n". used)
rint"\n :\n". so_far)
.
;
, . ,
, so_far.
163
, ,
,
( , , ).
, .
, .
, ,
. ,
used.
guess = inputC "\n\n : ")
guess = guess.upper()
while guess in used:
printC"B ". guess)
guess = input("\n\nBee : ")
guess = guess.upper()
used.appendCguess)
, , .
,
so_far, ,
.
if guess in word:
print("\na! '', guess. " !")
# so_far
new = "1'
for i in rangeClen(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so far = new
,
wrong .
else:
printC"\nK . ". guess. " .")
wrong += 1
, .
, , .
<J .
164 5. .
, .
, .
if wrong == MAX_WRONG:
print(HANGMAN[wrong])
print("\nBac !")
else:
print("\nB !")
print("\no ". word)
input("\n\nHae Enter. .")
- .
,
, ,
. , , ,
, ( )
. ,
.
,
, . , ,
, ~ - -.
: .
, .
.
.
30 , : , ,
. , ,
, .
?, ,
- . ,
, .
, - .
? , , , , .
- - . ,
.
.
6 <<->>
, , ,
. ,
. ,
,
.
-
- .
:
;
- ;
, ;
;
-.
-
, , , ,
(),
. -
-.
( ) ,
; .
. 6.1-6.3.
, , , ,
len() range( ). Python
, , .
, :
- , .
, ,
166 6. . -
. 6.2. . ,
. 6.3.
167
. ,
, ,
, , , , - .
, , ,
.
-, ,
,
. ,
. ,
, , : -
. ,
.
. 6.4.
. 6.4. ,
- (courseptr.com/
downloads) Chapter 6. instructions. .
#
#.
def instructions():
'""' ."""
168 . . -
pri nt (
.
"-".
. 8.
- . :
1 1 1 2
1 4 1 5
6 1 7 1 8
. . -
. \n
)
#
print("o '-':")
i nst ruct i ons ()
printC"o :")
instructions()
print("Haec. .")
input("\n\nHae Enter. .")
def instructiosC):
, -
instructions(). . ,
i nst ruct i ons ) ,
. def , , -
. , ,
. , ,
.
, .
, .
def, , , ,
, .
, . ,
, , .
, .
. i nstruct i s ()
:
""" ."""
169
, ,
. .
, , ,
, .
, . :
, . , IDLE,
,
.
r
, :
.
:
i nstructions()
, ,
. .
r
, .
m , .
, , , instructions()
, .
- .
. :
, 3. ,
, , ,
, ,
, ,
, , .
, ,
, No 3.
, .
, ,
, . , len()
.
,
.
170 6. . -
-
- ,
.
,
, . . 6.5
.
. 6.5.
- (courseptr.com/downloads)
Chapter 6. recei ve_and_return. .
# -
#
def display(message) :
print(message)
def give_me_five() :
five = 5
return five
def ask_yes_no(question) :
"'"' '' ' ' . """
response = None
while response not in ("", "n") :
response = input(question) .lower()
return response
#
display("Ba . \n")
number = give me five()
print("Bo give_me_five() :" . number)
answer = sk_s_n("\n. 'n': ")
print( ". ". answer)
input("\n\nHae Enter. .")
, , di sp l () .
. -
171
.. - , , ,
, :
def display(message):
, ,
, . ,
display() mssg " . \n",
display() :
display("Ba . \n")
message , .
, message
. :
print(message)
" ".
message,
, di sp l () .
di sp l () , , ,
. ,
.
-, , - give_me_fiveC) -
. , :
return five
,
fi ve , , .
return .
, ,
- .
, :
number = give_me_five()
printC"Bo give_me_five():". number)
, , ,
number. number
5 - give_me_five( ). ,
, .
.
return .
~~~~~~~~~~~~~~~~~~~~~~~~~
, , , .
, ,
.
172 . . -
, ,
. , fi ve
? , - fi ve
give_me_fiveC ).
, ( ),
. .
;
() .
,
. , , ,
. ,
.
, , ,
.
. ,
.
, ~
~. -
, ,
. , .
, .
, .
~ ~ ,
. ,
.
~~~~~~~~~~~~~~~~~~~~~~~~
, ~ .
, .
8 9, -
.
response = None
while response not in ("", "n"):
response = input(question).lower()
wh i 1 ,
, , n N.
.
,
, :
return response
.
answer
:
:
. , , 4'/- -
. ask_yes_no()
, ,
. . ,
:
, !
, '! . , t n r. r
, r r r
r . n .
n . ,
n, .
. - , ;
r, .
. , ,
, .
no. - , ,
, .
-
. :
,
Python.
9.
174 . . -
.
. Python,
: .
~. . 6.6,
.
- .,
. .
n11
'.
;. 1&!l - ! Bar1 1 ~
1!16 "", ..
11?
.N " J< ! - 11 _ n 1 . ?
~)t(f1 Ente1~" - ._
. 6.6.
- (courseptr.com/
downloads) Chapter 6. i rthday_wi shes . .
#
#
#
def irthdayl(name. age):
pri nt( " . ". name . "!". " ". age. "
? \ n")
#
def birthday2(name = " ". age = 1):
pri nt( " ." . name. "'". " " . age . "
? \ n")
birthdayl("oap " . 1)
i rthdayl . " ")
175
, , ,
:
irthdayl("oap ". 1)
,
, .
, , - . .
name "
", age - 1. : .
! 1 . ?.
, .
, :
, .
, . .
, ,
. i rthdayl () :
irthdayl(name =" ". age; 1).
176 . . -
. ! 1 .
?, .
.
- .
, , .
~~~~~~~~~~~~~~~~~~~~~~~~~~
r,
. - r
, r .
, ,
.
, , .
,
. bi rthday2( ),
bi rthdayl() :
i rthday2()
. ,
: . !
1 . ?.
~~~~~~~~~~~~~~~~~~~~~~~~~~
<,
. :
, ?
-
. :
bi rthday2(name = "")
birthday2(age = 12)
age, 12,
name - " ".
: . 1 12 . ?.
:
~~~~~~~~~~~~~~~~~~~~~~~~~~~
,
. ,
, , ,
.
, , <1
, .
- ,
- ,
. .
: .
- ,
. , ,
178 . . -
.
. , , (. 6.7).
def funcl () :
varialel
def func2():
variale2
varialeO
def fuc2():
variae2
variaeO
. 6.7. :
-
. 6.7 .
funcl( ), - func2( ), -
, .
- , ;
. ,
, , ,
, - ( ).
va ri l 1 funcl (),
funcl( ), .
, func2() ,
va ri l 1, . .
. ,
- , - ,
. ,
, . ,
1 . >.'> -
, , ,
, , . , ,
, , ,
. - . . .
179
, , <~,
, .
,
. ,
variae2 funcl( ),
, variable2 func2( ).
. , ,
.
~ ,
.
. 6.8.
. 6.8. ,
- ( courseptr.com/
downloads) Chapter 6. global_reach. .
#
#
def read_global():
print( " read_global () value ".
value)
def shadow_global():
value = -10
print("B shadow_global() value ",
value)
def change_global():
global value
value = -10
print("B change_global() value ". value)
#
180 . . r-
# value - .
value = 10
print("B value ".
value. "\n")
read_global ()
pri nt (" . va 1ue - ".
value. "\n")
shadow_global ()
print("Bepec . value - ".
value. "\n")
cha nge_g l l ()
print("Bepec . value ".
value)
input("\n\nHae Enter. .")
,
: ,
~1 . , , m
. ,
( ).
.
, .
read_global ().
va 1ue.
,
;
( , ). ,
read_gl 1() - :
value += 1
.
, ,
, ,
. ,
, ,
.
,
, -
. ,
1 ,
181
value = -10
va l ue -10, va l ue . ,
va l ue -10.
, , ,
:
. :
, , .
.
gl l,
change_gl l ():
global value
va l ue
. :
value = -10
va l ue -10.
va l ue :
>.> >.> - , .
, , ,
. - . ,
, ,
. , .
182 . . -
, (,
) ,
. , , -
, - .
, , ,
. ,
. 28 ( )? , ,
TAX_RATE . 28,
.28 _R. : ,
-, , -, . ,
, ,
.
-
-~, , -
, .
, ,
. ,
.
,
.
-
, :
, .
,
. m .
, : .
,
.
.
, .
:
.
"-"
- 183
r
, ,
, . , ,
. , ,
, ?
,
: "" ""?
. ,
- .
- , .
,
. . 6.9.
4 5
6 7 8
. 6.9. ,
, ( ) .
, .
- ,
, .
q~ ( )
"" "", . , ,
, , "", .
,
. , ,
,
. . 6.1.
184 6. . r-
n 6.1. -
display_istruct()
ask_yes_o(questio) , .
, ''" ""
ask_umer(questio, low, .
high() , (low) (high) .
low high
pieces() -
.
ew_oard() .
display_oard(board) .
legal_moves(oard) . .
winer(board) . .
: " None
huma_move(oard, huma) , n .
.
computer_move(oard, . ,
computer, human) .
ext_tum(tur) . -
.
cograt_wier(the_winer, .
computer, huma) ,
,
. .
, .
- ( courseptr.com/
downloads) Chapter 6. tic-tac-toe. .
# -
# -
#
= ""
= ""
=
= ""
NUM_SQUARES = 9
- (" "), - ("").
.
, . I
. NUM_SQUARES - ~-.
r- 185
display_instruct()
. :
"--
".
. 8.
- . :
1 1 1 2
3 1 4 1 5
6 1 7 1 8
. . -
. \n
)
ask_yes_no()
, 4 4.
"" "n".
.
def ask_yes_no(question):
""" '' ''."""
response = None
while response not in ("". "n"):
response = input(question).lower()
return response
ask_number()
, .
, ,
pieces()
, ,
, , .
.
def pieces():
""" ."""
go_first = ask_yes_no("Xoe ? (y/n): ")
if go first =="":
printC''\nHy . : .")
human = computer = else:
print("\nTo ." .")
computer = human = return computer. human
, - ask_yes_
no( ). : .
new_board()
- ,
, :
def new_board():
""" .'""'
board = []
for square in range(NUM_SQUARESJ:
board.appendCEMPTY)
return board
display_board()
. -
, "" "", print.
4-~.
.
legal_moves()
.
: human_move() - ,
- 187
, computer _
move() - .
- . ,
, , 4- .
,
[. 2. 6. 8] ( , . 6.9). ,
, . ,
, .
.
winner()
.
: - ; -
, ; ,
None - .
WAYS_TO_WIN,
.
- ,
. :
(0. 1. 2). , , 1 2.
- (3. 4. 5) - . .
def winner(board):
""" .
WAYS WIN = ((0. 1. 2).
- - (3. 4. 5).
(6. 7. 8).
(0. 3. 6).
(1, 4. 7).
(2. 5. 8).
(0. 4. 8).
(2. 4. 6))
for , ,
. if
,
. , , ,
.
wi nner,
.
188 6. . -
None.
return None
human_move()
-,
, .
.
, ,
, .
, .
computer_move()
computer_move() ,
, .
~~~~~~~~~~~~~~~~~~~~~~~~~~
, , . , ,
,
. , ,
. ,
,
.
- 189
,
. , computer_move() -
, .
,
. (, .
.)
, ,
. - ,
. , ,
, .
,
5.
( ), ,
, .
, ,
:
board = board[: J
-----------------------
, , .
, .
---------------------------
,
( ), ,
, , .
{) .
, { ), ,
. ,
. ,
.
1. , ,
.
2. ,
, .
3.
.
, - ,
, - . ,
:
190 . . r-
#
BEST_MOVES = (4. . 2. 6. 8. 1. 3. 5. 7)
print(" ". end=" ")
. ,
, ( ,
) , . ,
; . ,
.
# .
#
for move in BEST MOVES:
if move in legal_moves<board):
print(move)
return move
r- 191
- .
, ,
. , , .
, ,
, IBM Deep Blue, '
, . Deep Blue
200 . , , , , ,
1050. ,
Deep Blue 1 585 489 ( ,
15 ).
next_turn()
,
, , .
turn, , , 11 -
.
def next_turn(turn):
""" ."""
if turn == :
return else:
return .
. .
congrat_winner()
,
. ,
the_wi nner ,
, , .
main()
,
.
. , , ,
, .
mai n( ), - ,
, .
, . ,
:
defmain():
display_instruct()
computer. human = pieces()
turn = board = new_board()
display_board(board)
while not winner(board):
i f turn == human:
move = human_move(board. human)
board[moveJ = human
else:
move = computer_moveCboard. computer. human)
board[moveJ = computer
di spl ay _boardCboard)
turn = next_turn(turn)
the_winner = winner(board)
congrat_winner(the_winner. computer. human)
i n (,
, ):
#
main()
inut"\n\ Enter. .")
. ,
. ,
,
. , -
193
, ,
, . , -
-.
' .
ask_numer() , -
( ). 1.
, ask_number().
( , ) ,
main(). ,
.
computer_move(), .
, .
.
7 <<>>
-
. ,
. ,
.
, ,
.
, :
- ,
. -,
. ,
-, .
( - ).
, - ,
. .
, , Windows,
() -
. . 7.1
.
Python .
,
195
, , - 1
. :
.
. 7 .1. ,
~>.>
. , ,
. ,
. . 7.2.
, .
- ( courseptr.com/downloads) Oiapter 7;
read_i t . txt. 2 :
1
2
3
,
ASCII, . ,
, . - . .
, ,
, . - . .
196 7. .
. 7.2.
- ( courseptr.com/downloads)
Chapter 7. read _i t. :
#
#
pri nt( " .")
text file = open("read it.txt". "r". encoding='utf-8')
text=file.close() -
print("\na .")
text file = open("read it.txt". "r")
print(text_file.read(l))
print(text file . read(5))
text_file .close()
print("\na .")
open( "read_ it . txt". "r". encodi ng= ut f-8 )
whole thing = text file.read()
print(whole_thing)-
text_file.close()
print("\na . ")
text_file = open("read_it .txt". "r". encoding='utf-8')
print(text_file . readline(l))
print(text_file . readline(5))
text_file .close()
197
print("\na .")
text_file = open("read_it.txt". "r". encoding='utf-8')
print(text file.readline())
print(text=file.readline())
print(text file.readline())
text_file.close()
print("\na .")
text_fi l = open( "read_i t. txt". "r". encodi ng=' utf-8' )
lines = text_file.readlines()
print(lines)
print(len(lines))
for line in lines:
print(line)
text_file.close()
print("\nepepa .")
text file = open("read it. txt", "r". encoding='utf-8')
for line in text file:-
print(line)
text_file.close()
input("\n\nHae Enter. .")
( ), ero
. ~:
6111 7 .1.
rrrn . , Python
"w" . , .
,
#
198 7. .
116n 7.1 ()
" r . r,
. ,
11+11 . , Python
llw+" . ,
. ,
"+" r . ,
. ,
text_file,
. ,
l ose ) ,
,
. closeC ):
>>> text_file.close()
, .
- , -
, .
readC) .
read () ;
. ,
:
read.
:
>>> print(text_file.read(5))
: , . Python ,
.
, read() ,
. ,
read() .
, .
:
>>> text_file.close()
> text_file = open("read_it.txt". "r")
199
,
.
, :
>>> text_file.close()
.
readl i ne( ). <1
, .
, .
,
. , , :
>>> print(text_file.readline(5))
>>> text_file.close()
, readl i ne() read( ).
readl i neC) , read()
. readl i ne()
. :
-
read l i nes (), ,
. :
>>> print(lines)
[ 1\n . ' 2\n' . ' 3\n' J
1i nes .
:
>>> print(len(lines))
3
>>> for line in lines:
pri nt l i ne)
1
2
3
>>> text_file.close()
, for
:
, ( l i ne)
.
, - . .
.
,
. Python
, . .
201
~ ,
read _ i t. txt.
.
. 7.3.
- ( courseptr.com/
downloads) Chapter 7. write_it. .
. 7.3. ,
, ,
. :
#
#
print("Coa write() . ")
text_file = open("write_it .txt". "w" . encoding='utf-8')
wri te _i t .txt ,
. wri te _i t . txt ,
, .
write( ),
:
, . ,
, .
, , \n.
, " 1\ n
2\n 3\n" -
wri te ( ) .
:
text_file.close()
, , ,
:
print("\na .")
text_file = open("write_it. txt". "r". encoding='utf-8')
print(text_file.read())
text_file.close()
wri te l i nes ()
. read l i nes ( ), wri te l i nes ( ) ,
: , .
:
print("\na .")
text_file = open("write_it.txt". "r". encoding='utf-8')
print(text file.read())
text_file.close()
input("\n\nHae Enter. .")
r 203
, ,
. . 7.2.
7 .2.
dose() . J)'
,
d([])
. , , -
readline([co]) r -
r. , ,
readlles() ,
write(crpoa) r
writelles( r
)
,
. :
.
, .
-
, . Python
.
. ,
, .
r
- n .
Python. ,
, - 1 (,
, , ).
,
.
: (
), .
- ,
. - . .
204 7. .
. 7.4, -
( courseptr.com/downloads) Chapter 7. pi ck l _i t ..
. 7.4. ,
, , -
:
#
#
import pickle. shelve
pickle
, she l ve
.
: ,
, .
, :
- .
, :
rint(" . ")
variety =[" . "". ""]
shape = ["" . "". ""]
brand = ["" . "". ""]
:
f = open("picklesl.dat". "wb")
() ,
. pi ck l es 1. dat
, "wb".
205
, ,
. 7.3.
7 .3.
"rb" . 01 , Pytho
tlw" . , .
01 ,
"" . 01 ,
. 01 ,
"r+" . , Python
"wb+" . ,
. 01 ,
"+" n . 01 ,
. ,
pickle.dump(variety. f)
pickle.dump(shape. f)
pickle.dump(brand. f)
f.close()
, ,
variety. , picklesl.dat
. ,
shape brand. .
, :
;
pi ck 1.1 oad ().
: ,
.
rint("\n .")
f = open ( "pi ck 1es1. dat . "rb")
variety = pickle. load(f)
206 7. .
shape = pickle.load(f)
brand = pickle.load(f)
,
, ["". "". ""].
vari ety.
, ["".
"". "" J shape.
()
[ "". "". " "J,
brad.
, , :
print(variety)
print(shape)
pri nt(brand)
f .close()
. 7.4.
7 .4. pickle
dum(, . n -
, [,n]) True, , False -
, .
in = False
ld() -
. shel ve ( . )
, ,
.
.\1 s:
rint("\n .")
s = shelve.open("pickles2.dat")
she l ve. open () , open ),
, shelve.open() ,
.
s; ,
.
------------------------
shelve.open() Python
, .
207
s . 1 "variety"
<J ["". "". ""], "shape" -
["". "". ""], "brand" - ["".
"". ""]. ,
.
sync() -:
s.sync() #.
, , Python ,
. ,
, sync ().
cl ose( ).
-----------------------
, shelve
. ,
, .
, , ,
. : s
, :
rint("\n :")
rint(" -". s["brand"])
printC"op -". s["shape"J)
rint" -". s["variety"])
. :
s.close()
inputC"\n\nHae Enter. .")
611111 7.5.
"" r . ,
''n" . , -
"r'' . , Python
"w" . , Python
208 7. .
- ,
'l, n n . n m
n - XMl. n Pytho
n. http://www.pytho.org.
Python ,
. , ,
( exception ), ,
. , Python
.
Python:
> num = flt("!")
Traceback Cmost recent call last):
File "<pyshell#l>". line 1. in <module>
num = flt"!")
ValueError: could not convert string to float: !
Python
"!" . ,
, .
Python
. ,
.t ,
!. ,
- .
.t
,
. ,
.
. 7.5. - (courseptr.com/
downloads) Chapter 7. handl e_it. .
try / except
( .t) -
try/except. try ,
. except, ,
, ,
.
209
. 7.5. ! ,
~ .
.
try except.
#
#
# try/except
try:
num = float(input("Bee : "))
except :
print("oxoe. !")
fl oat () - , - ,
, "!", - n
: .
! . , num
, , except,
.
. , ,
"!
float( ),
Va 1ueError,
(
210 7. .
). 20; . 7.6
.
6n8 7.6.
IOError , r /
, ,
IndexError ,
eyError ,
NameError , (,
}
SyntaxError , -
TypeError , rr -
ValueError , r
,
ZeroDivisionError ,
r -
except ,
. ,
except. ,
, V 1ueError:
#
try:
num = float(input("\nBee : "))
except ValueError:
print("o !")
print , ValueError.
,
: !. , try
, except
.
- :
.
, , .
.
~~~~~~~~~~~~~~~~~~~~~~~~
? ,
.
, r, .
r,
.
211
~~~~~~~~~~~~~~~~~~~~~~~~~~
, , , . :
. , ,
, ,
:
> 1/0
Traceback (most recent call last):
File "<pyshell#O>". line 1. in <module>
1/0
ZeroDivisionError: int division or modulo zero
, ZeroDivisionError.
, .
.
, .
- except
, :
#
print()
for value in (None. "!"):
try:
rint(" : value. "-->" end=" ")
print(float<value))
except (TypeError. ValueError):
print("oxoe. !")
.
, . fl oat (None)
TypeError,
. flt("! ") ValueError, "
! "- , ( ).
except .
:
except. t ry
except:
print()
for value in (None. "!"):
try:
rint(" : value. "-->" end=" ")
print(float(value))
except TypeError:
print(" !")
except ValueError:
print(" . !")
.
None, TypeError :
212 7. .
, -
.
, Python.
, as.
:
#
try:
num = float(input("\nBee : "))
except ValueError as :
print("o ! :")
print(e)
else
except t ry
el se. , try
.
# try/except/else
try:
num = float(input( "\n : "))
except ValueError:
print("o !")
else:
print("B ". num)
input("\n\nHae Enter. .")
num ,
try, ,
. , ,
num .
,
~ ~. -
213
. ,
. ,
; -
. , tri vi . txt,
, , .
, t ri vi . txt
.
r
, ,
tri vi . txt. -
. - ,
. () .
:
< >
<>
< 1>
< 2>
< >
< 4>
< >
<>
.
. . . . . /
. / .
?
1
- !
. " "
. . /
?
3
" " Soul .
15 - .
tri vi . txt - (www.courseptr.com/
downloads), Chapter 7.
214 7. .
, (.
) - , .
, -
. , " " - (, ,
) . -
. - ". .
. . . / .
/ '"1. ?" -
. - "", "'', "", "" -
, .
, 1,
. - (""). ,
- ,
- " - !"
.
.
, (/).
. , Python
, .
, s- .
, .
open_file()
open_fi le( ),
( - ),
. try except
IOError, -,
.
, .
;
sys .exit( ).
, .
sys . exi t ( ) . ,
sys .exit() sys.
#
# .
#
import sys
def open file(file name. mode):
"'"' .'"'"
try:
the_file = open(file_name. mode. encoding='utf-8')
except IOError as :
rint(" ". file_name. "
.\n". )
input("\n\nHae Enter. .")
215
sys .exit()
else:
return the file
next_line()
next_l i ne( ),
:
def next_line(the_file):
""" .
line = the_file.readline()
line = line.replace("/". "\n")
return l i ne
, - :
s- . , Pytho
, . ,
,
: , ,
. , , tri vi . txt
.
, .
next_ock()
next _b1ock ( ) ,
. (
, , , ), (
- ).
def next_ock(the_file):
""" ."""
category = next line(the file)
question = next=line(the=file)
answers = []
for i in range(4):
answers.append(next line(the file))
correct = next_line(the_file)
i f correct:
correct = correct[OJ
explanation = next_line(the_file)
return category, question. answers. correct. explanation
,
. , tr~ via. txt,
category "". category
, main() .
216 7. .
welcome()
we l come() .
;
.
def welcome(title):
""" ."""
print("\t\topo '' !\n")
print{"\t\t". title. "\n")
r
i n(),
. :
, ( ),
.
def main():
trivia file = open file("trivia.txt". "r")
title: next lineCtrivia file)
welcomeCtitle) -
score =
, ,
whi le,
, category .
,
.
: (),
.
#
category, question. answers. correct. explanation = next_ock(trivia_file)
whi l category:
#
printCcategory)
print(question)
for i in range(4}:
print("\t". i + 1. " " ar1swers[iJ)
#
answer = input("Ba : ")
217
. ,
;
, .
( , ) .
#
if answer == correct:
print("\na!". end=" ")
score += 1
else:
print("\nHe.". end=" ")
print(explanation)
printC"Ce:". score. "\n\n")
n
next_ockO, ,
. , category
.
#
category. question. answers. correct. explanation = next_ock(trivia_file)
w
tri vi . txt
:
trivia_file.close()
print("o !")
print("Ha ". score)
main()
ma i n( ) :
main()
input("\n\nHae Enter. .")
.
, ,
.
( , , ).
, , ,
218 7. .
. ,
, ,
, , .
,
: ~.>
, .
, ,
~,.. .
_ , ' -- - _, - ;
, -
. ,
.
, . n
-.
.
, , :
.
,
Python.
8
.
<< >>
- () -
. ,
;
. -
, .
.
:
, ;
;
;
.
r
~
. ;
,
- .
, . , ,
; -
. ~
. 8.1-8.3.
,
. ,
. ,
. , ,
, .
220 8. .
. 8.1.
. 8.2. ,
. 8.3. ,
, 221
, - , ,
, , . ,
.
, (
), -
. .
, ,
, ,
.. ,
, ,
- .
(, ,
) , . - ,
. :
, .
,
. ,
, . ,
, ,
- , .
, , .
, ,
, ,
. ,
100, - 1 .
-----------------------
, .
, . ,
. Pytho,
, .
,
, - .
- ($~ . ,
.
r r
($ ~ - , Python.
,
222 8. .
(, ).
. 8.4.
- (courseptr.com/
downloads) Chapter 8. simple_critter. .
:
#
#
class Critter(object) :
""" """
def talk(self) :
rint(". - Critter.")
#
crit = Critter()
crit.talk()
input(" \ n \ nHae Enter. .")
- <1j>,
.
:
class Critter(object) :
1ass - Cri tter.
, .
, Python , .
.
, 223
object. object
,
. object.
.
, .
:
""" """
.
:
def talkCself):
rint(". - Critter.")
, ,
( ).
ta l k ) . -
Cri tter ..
, ta l k) se l f,
. .1 rt.ll, ,
, ,
sel f. .
sel f: ,
.
~~~~~~~~~~~~~~~~~~~~~~~~~~
n ,
. ,
self.
, ( -)
:
crit = Critter()
Cri tter
crit. , Critter .
.
- -
, . ,
, , ,
: .
224 8. .
ta 1k ). ,
, - , , .
, :
cri t . ta 1k ()
ta 1k () Cri tter,
cri t. : .
- Critter ..
ta 1k(), .
, ,
. - .
,
. ,
, .
~> Cri tter,
-.
, .
. 8.5.
. 8.5. ,
225
- (courseptr.com/
downloads) Chapter 8. constructor_critter. .
#
# -
class CritterCobject):
""" """
def init Cself):
rint(" !")
def talk(self):
print("\npe. - Critter.")
#
critl = Critter()
crit2 = Critter()
critl.talk()
cri t2. ta l k()
input("\n\nHae Enter. .")
r
, , - -
( ):
def _init_Cself):
rint" !")
,
, .
_init_, Python , -. , _init_C)
Critter. , ,
:n !.
-------------------------
8 Python ,
. - _init_ - .
, ero .
:
#
critl = Critter()
crit2 = Critter()
. -
: !.
- , r .
, ta l k() :
226 8. .
critl. talk()
crit2.talk()
: "\n . -
Cri tter. ", - .
-.
.
r
name.
Critter -,
name. , ,
, . . 8.6.
#
#
class Critter(object) :
""" """
def i nit se lf. name) :
rint(" !")
r 227
self.name = name
def ~str~Cself):
rep = " Critter\n"
rep +=": "+ self.riame + "\n"
return rep
def talkCself):
rint". ". self.name. "\n")
#
critl = CritterC"o")
critl.talk()
crit2 = Critter( "")
cri t 2. ta 1k()
print("Bo critl :")
print(critl)
rint(" critl.name:")
print(critl.name)
input("\n\nHae Enter. .")
, ~>, -
!, .
name,
name.
:
critl = CritterC"o")
Critter, nm "".
cri t.
,
self. , self
,
. , sel f
, ( , ,
).
~~~~~~~~~~~~~~~~~~~~~~~~
self, - ,
r . Python, ,
, .
, -, ,
Critter sel f
, name "". :
self.name = name
name name,
"".
228 8. .
crit.
, cri t name,
"". , !
:
crit2 = Critter("Myp")
. Critter
name, "", crit2.
r
, .
ta l k() , name
Critter: , .
, talk( ):
critl.talk()
sel f :
def talk(self):
pri nt . .
se l f. name name :
rint(". ". self.name. "\n")
:
crit2. talk()
ta l k() . ,
name cri t2 "".
,
, . ,
name critl:
print(critl.name)
.
, ,
: _. _.
~~~~~~~~~~~~~~~~~~~~~~~~
.
, ,
.
print(critl), Python
, :
,
Cri tter.
. , :
_st r_ (),
. ,
, _st r _ ( ).
,
name. :
print(critl)
:
Critter
:
~~~~~~~~~~~~~~~~~~~~~~~~~~
, _str_()
. , ,
.
m . , , ,
. ,
, . ,
.
Cri tter tota l.
tota l
. .
, Python , ;
. - , -
.
1 .
Python , .
.
r r
,
. ,
-4, 4
. - t. . .
230 8. .
, . ,
Critter,
, .
. 8.7.
. 8.7. !
,
- (courseptr.com/
downloads) Chapter 8. cl assy_critter. .
#
#
class Critter(object):
""" """
total =
@staticmethod
def status <) :
print("\nBcero " . Critter.total)
def init (self. name):
rint(" !")
self.name = name
Critter .total += 1
#
print("Haxoy Critter .total :". end=" ")
print(Critter .total)
print("\nCoa . ")
critl = rittr(" 1")
crit2 = rittr(" 2")
crit = rittr(" 3")
Critter .status()
print("\nOpaac :" . end=" ")
print(critl .total)
input("\n\nHae Enter. .")
231
total =
total Critter .
, (
) .
- Pytho11 .
, ,
, , ,
.
;
. total
Critter :
print Critter.total
status()
:
Critter.total += 1
-
, - tota l 1.
:
_._.
, ,
. :
print(critl.total)
tota l,
Critter, .
, : pri nt (cri t2. to-
ta l) print(crit. total ), .
~~~~~~~~~~~~~~~~~~~~~~~~~-
,
. ,
.
232 8. .
r
status( ):
def status :
print("\nBcero ". Critter.total)
- . ,
se 1f. , status( ),
, , . ,
,
se 1f, . , ,
, .
status ( ) - ,
, , - (~~)
. :
@staticmethod
,
status( ),
Critter, total.
.
@stat i cmethod, , ,
, ,
self.
r
.
:
Critter.status()
, ,
. ,
, .
, , .
status ( );
, . , ,
, -
tota 1 1.
4
\'> 6. ,
,
233
( ).
,
. , , .
,
.
.
, . Checking_
Account ( ) 1ance. , ,
; 1ance
- . ,
1ance .
.
, , ,
, , .
wi thdraw(),
, - .
: , ,
, .
- .
(pulic ):
.
(private ). ,
.
~ , ,
. . 8.8.
. 8.8.
234 8. .
,
- (www.courseptr.com/downloads)
Chapte . pri vate_critter. .
,
. -
: :
#
#
class Critter(object):
""" """
def _init_(self. name. mood):
rint(" !")
self.name = name # ~
self ._mood = mood #
, ,
.
i ,
.
~~~~~~~~~~~~~~~~~~~~~~~~
( , ~
). ta l k( )
_ mood:
def talk(self):
print("\nMe ", self.name)
print("Ceac ". self._mood. "\n")
,
.
Critter, . ,
, :
>>> print(crit._Critter~mood)
mood,
"".
,
? - . Python -
,
. , ,
.
-----------------------
,
.
,
: .
, :
def ~private_method(self):
print("o .")
. ,
( )
.
,
. u ic_method( ),
:
236 8. .
def puic_method(self):
print("o .")
self.~private_method()
.
.
,
.
private_method:
>>> crit.private method
Traceback (most recent call last):
Fi l "<pyshe 11#0>". l i ne 1. i n <modul >
crit.private method
AttributeError: 'Critter' object has no attribute 'private_method'
Attri buteError: Python
, crit (
).
, :
>>> crit.~private_method()
Traceback (most recent call last):
File "<pyshell#l>". line 1. in <module>
crit.~private_method()
AttributeError: 'Critter' object has no attribute ~private_method'
(
) .
:
>>> crit._Critter~private_method()
.
, ,
.
~~~~~~~~~~~~~~~~~~~~~~~~
:
.
. , :
#
crit = Critter(name ="". mood ="")
crit.talk()
crit.pulic_method()
input("\n\nHae Enter. .")
r 237
_i ni t _ () Cri tter,
, ,
. ta l k() cri t .
, publ ic_method() crit
. ,
.. .
. ,
?
, . ,
, ,
. Pytho
, ,
.
-----------------------
: , r
r ,
r , r .
n : r
r
.
, ,
. , , ,
, . Python
- , .
.
, - Critter.
, , -
, -
. . 8.9.
,
- (www.courseptr.com/downloads)
Chapter 8. property_critter. .
238 8. .
. 8.9. Critter
-
,
- . -
Critter, name,
_ name:
#
#
class Critter(object) :
""" "" "
def _init_(self. name):
rint(" !")
self . name = name
@property-
def name( se lf):
return self. name
, ,
( _name ),
@property. ;
name. name Critter
_name - ,
.
( name
).
, , ,
,
@property. .
239
- , , ,
( ).
, ~
, .
.
name _name
:
@name.setter
def name(self. new name):
if new name ==-
print( " .")
else:
self. name = new name
print(" .")
r
name, ,
. :
Python,
. - ,~~. .
240 8. .
"". , name
, , :
, m
, _.
new_ame ,
: .,
_ cri t . ,
, name :
pri nt " ". end= " ")
print(crit.ame)
iut("\n\n Eter. .")
. - .
,
. ,
. ,
- (www.courseptr.com/downloads)
Chapter 8. critter_caretaker. .
241
Critter
, Critter - , m
. ,
.
-r
-
Critter: name, hunger boredom. , hunger boredom
, ,
.
#
# .
class Critter(object):
""" """
def _init_Cself. name. hunger =. boredom = 0):
self.name = name
self.hunger = hunger
self.boredom = boredom
. ,
Critter.
__pass_time()
Meo _pass_time() - ,
(hunger) (boredom) .
, , ; -
. , ,
, ,
- : , , .
@property
def moodCself):
242 8. .
eat()
eat () ,
food. , food
4. ,
. , , _pass_time( ).
def eat(self. food = 4):
pri nt ( "". ! ")
self.hunger -= food
if self.hunger < :
self. hunger =
self._pass_time()
play()
play() ,
fun. , fun
4. ,
. , , _pass_
time( ).
def play(self. fun = 4):
print("Y!")
self.boredom -= fun
if self .boredom < :
self.boredom =
self._pass_time()
w
ma i n( ).
Critter. hunger boredom -
243
,
.
def mainO:
crit_name = input("Ka ? ")
crit = Critter<crit_name)
.
, . 1,
ta l k( ). 2, eat ( ).
3, l ( ). ,
.
choice = None
while choice !="":
print \
( 1t 11"
-
1 -
2 -
3-
11 11 11)
nr1
main() .
, , .
main()
input("\n\nHae Enter. .")
244 8. .
,
. , oryr
( ) (),
. - ~
. -,
. , ,
. ,
, ,
. -
. , ,
, .
,
,' :
, ,
(
).
, .
, . ,
.
- 1
. , , ,
, ( Critter 1
_str_()).
, Critter,
.
, . , ,
: 1 , .
,
.
9
.
<<->>
.
, .
, ,
, , .
.
, :
;
;
;
;
;
.
n-
, ,
-- 1. :
, - ,
21 , . ,
, ; ,
10 , - 1 11 ( , ).
2 , .
,
. - . .
- . - . .
246 9. - . -
, . ,
. , ,
, .
. ,
21 . ,
, . ,
.
, .
, <~-~,
, 17 .
, - , ,
, . ,
, . (
) .
.
. 9.1.
. 9.1. ,
- - ,
- . ,
; .
, -
.
.
. , , , ,
.
247
w
,
. : ,
(, ,
).
. . 9.2.
. 9.2. ,
hero.ast(invader)
, , ,
.
. /-
. - UML ( ),
, --
i __ _~_ ~_~-~- ________________________________________________________________________________________________________ _
- (courseptr.com/
downloads} Chapter 9. al ien_blaster. :
#
#
class PlayerCobject):
""" -. """
def ast(self. enemy):
printC"po .\n")
enemy. di ()
class Alien(object):
""" - -. """
def die(sel f):
print("Teo . : ', .
. \n" \
" ... .
". \n" \
". . '")
#
print("\t\te \n")
hero = PlayerC)
invader = Alien()
hero.ast(invader)
input("\n\nHae Enter. .")
, ,
! :
Pl ayer, hero, l i en,
i nvader.
, .
hero.ast(i nvader) ast() hero
i nvader. st ) , ,
enemy. l ast ()
enemy l i en. ,
last() enemy.die() die() Al ien. ,
, Pl ayer l i en ,
die( ).
249
i nvader hero :
di () ,
.
. ,
, , ,
, : , , . .
: , .
, , , .
. ,
Drag_Racer, ;
engine, Race_Engine
(). Zoo, ,
ani ma 1s - ( Ani ma 1).
, , .
r
,
-
( , ).
(Hand),
; , -.
. 9.4.
,
- (www.courseptr.com/downloads)
Chapter 9. 1ayi ng_ rds . .
Card
Card,
.
#
#
class Card(object):
. """
RANKS = ["". "2". "". "4". "5". "6". "7". "". "9". "10". "J". "Q". ""]
SUIS = ["". "d". "h". "s"J
def init (self. rank. suit):
self.rank = rank
self.suit = suit
def _str_(self):
rep = self.rank + self.suit
return rep
Card rank, -
. RANKS : (""),
2 10, ("J"), ("") ("").
suit, .
SUS: "" (lus)-, "d" (diamonds)-y
, "h" (hcarts)- , , "s" (spades) - .
, rank, "", suit, "d",
. ,
, _str _( ).
Hand
, , - Hand,
-:
class HandCobject):
""" : . """
def _init_Cself):
self.cards = []
def str Cself):
if seif .cards:
rep = ""
for card in self.cards:
rep += strCcard) + " "
else:
rep = "<n>"
return rep
251
def clear(self):
self.cards = []
def add(self. card):
self.cards.append(card)
def give(self. card. other_hand):
self.cards.remove(card)
other_hand.add(card)
Hand rds,
. , - ,
.
_str_() .
Card
. Hand ,
<>.
1 r ( ) : rds
. add() cards. gi ve()
cards, ,
Hand ( add( )).
, Hand Hand :
cards Card.
-
Card:
#
cardl = Card(rank = . suit ="")
print("Boy -:")
pri nt(cardl)
card2 = Card(rank = 2. suit ="")
card = Card(rank = "". suit ="")
card4 = Card(rank = "4". suit = "")
card5 = CardCrank = "5". suit = "")
print("\nBoy :")
pri nt rd2)
pri nt ( card)
print(card4)
print(card5)
Card rank "",
su i t - "" ( ). ;
.
- Hand
Hand, my_hand
:
252 9. - . -
my_hand = Hand()
print("\neaa . :")
pri nt (my_hand)
cards ,
<>.
my_hand Card
:
my_hand.add(cardl)
my hand.add(card2)
-hand.add(card)
my-hand.add(card4)
my-hand.add(card5)
print("\neaa . :")
pri nt (my_hand)
2 4 5.
Hand your_hand.
my_hand give( ), ~ ~
~ :
your_hand = Hand()
my_hand.give(cardl. your_hand)
my_hand.give(card2. your_hand)
print("\nepe .")
pri nt (" :")
print(your_hand)
print("A :")
pri nt (my_ hand)
, your _hand 2, my _hand - 4 5.
1 r ( ) my_ha nd
:
my_hand.clear()
print("\nY . :")
print(my_hand)
input("\n\nHae Enter. .")
<>.
- .
,
() .
, ,
!
253
~~~~~~~~~~~~~~~~~~~~~~~~~
Python 1<, nr ;
r .
- r, .
,
. ,
.
.
, , Drag_Racer -
stop() go( ). ,
(
400 / ).
stop() go() Drag_Racer. ,
,
.
r 2.0
2.0 - ,
Deck ().
, , Deck
Hand. Deck
Hand. Deck , -, ,
, ,
. , <~: ,
. .
, . -,
, -,
. 2.0 ,
.
. 9.5.
, , , ,
.
,
- (www.courseptr.com/downloads)
Chapter 9. playing_cards2.py.
, .
- Card Hand - :
254 9. - . -
. '. l!ID~
3<\ KOJ10J1a.
IJur :
<)
JJ n11 .
r. :
Rc 2 3 4 5 & ? 8 9 HJt
.Jc Qc Ad 2d d 4d 5d &d ?d
l!d 9d 1d Jd Qd Kd /1 2h 311 411
5}1 6/1 ?11 811 911 1011 Jh Q!1 \1 As
2s s 4:; 5s 6s ?s 8s 9s 10s Js
Qs Ks
}(._. . 110na neper1catia.
rn :
Q/1 Qd . Js 511 Jc ?d ? 9d 9 ?11
l{d 2d /{ 311 8 2 211 Qc 4d
6<1 Sh s Ss 3 3s JJ1 4s Qs Rd
Ks 5s 2s 6 10h d 9s J(h Sd 10s
11<\ 1 4 Jd 4h 611 As 5 ?s !d
911 Al1
r1 l> 5 .
!:J:
Ql1 Js Jc ? 9
:
Qd ""511 ?d 9d ?h
:
! 2d 11 8 2 211 Qc 4d
d 811 s s s J]1 4s Qs Ad
1(, Ss 2" 6 1011 3<1 9s \1 5d 1fiJs
d 10 4 Jd 411 611 As 5 ?s 1fiJd
911 Ah
J<o11ona .
Bor . : ()
~r,r Ente". ._
# 2.0
#
class Card(object):
.
RANKS = [ . 2. .. . 4.. "5.. "". 7 . . 9. 10. J.. . ]
SUIS = [ " " . "d". "h". "s"J
def _init_(self. rank. suit):
sel f. rank = rank
self.suit = suit
def _str_(self) :
rep = self.rank + self.suit
return rep
class Hand(object):
'' : .
def _init_(self) :
self.cards = [J
def str (self):
if self.cards :
rep =
for card in self .cards:
rep += str(card) + "\t"
else:
rep = "<>"
u 255
return rep
def clear(self):
self. cards = [ J
def add(self. card):
self.cards.appendCcard)
def give(self. card. other hand):
self.cards.remove(card)
other_hand.add(card)
Oeck.
, Hand:
class Deck(Hand):
Hand , Deck - ,
Hand.
Deck Hand. ,
, Deck
- :
_init_O;
_str _();
cl ear( );
add();
give().
, Hand
Deck.
, . .
Deck:
""" .
def populateCself):
self.cards = [ ]
for suit in Card.SUITS:
for rank in Card.RANKS:
self.add(Card(rank. suit))
def shuffle(self):
import random
random.shuffleCself.cards)
def deal(self. hands. per hand = 1):
for rounds in range(per_hand):
for hand in hands:
if se lf. rds :
top_card = self.cards[OJ
256 9. - . -
self.give(top_card. hand)
else:
print("He : !")
, , ,
:
populateO;
shuffleO;
deal .
, Deck :
Hand, Deck.
Deck ,
.
r
Deck:
#
deckl = Deck()
, , - Deck
. Oeck Hand,
Deck. ,
rds ;
$>.
deck 1.
, , . :
print("Coaa .")
print("Bo :")
print(deckl)
_ s t r _ ( ) Deck ,
Hand. ,
<>.
. ,
.
deckl. shuffl ()
Deck shuffle(), random
random. shuffl ) cards .
, random. shuffle() ,
, , . ,
, - .
deckl.deal(hands. per_hand = 5)
dea l () - , Deck.
: , .
.
, : : !.
,
. ,
deckl my_hand your_hand.
, :
printC"\nMe 5 .")
pri nt( " :")
printCmy_hand)
pri ntC :")
printCyour_hand)
printC"Ocaoc :")
printCdeckl)
, ,
, 42.
258 9. - . -
deckl.clear()
pri nt ( "\ n .")
, ,
. , ,
, .
. , :
,
.
Drag_Racer. , ,
stop() .
, ,
- , - Drag_Racer
Parachute_Racer stop( ).
stop( ), stop() Drag_Racer
(, , ),
.
r nti .
3.0 rd, ,
. ,
. ,
< >.
, .
.
, rd.
, .
. 9.6.
.1 ,
- (www.courseptr.com/downloads)
Chapter 9. playing_cards. .
, .
Card, ,
, :
259
# 3.0
#
class Card(object) 1 :
.
RANKS = ["" . "2". "3". "4". "5" . "6". "7". "8". "9". "10". "J". "Q". ""]
SU IS = [ "" . "d " . "h" . "s " J
def init <self. rank. suit):
self.rank = rank
self.suit = suit
def _str_(self):
rep = self .rank + self .suit
return rep
Card , (
) . :
class Unprintae_Card(Card) :
, Unpri ntab l _ rd
rd. ,
. :
""" . . """
def _str_(self):
return "< >"
Python 3 object, 2- .
, object 2- .
object. - . . .
260 9. - . -
. ,
rd. ,
, , .
, -, Card, ,
i s_face_up.
, , ,
ra nk su i t. rd :
, ,
rank suit .
,
.
Pos i t i ona _ rd:
cl ass Pos iti n _ rd(Card):
'"'" . n .
def init (self. rank. suit. face up = True):
super(Positionae Card. self).- init (rank. suit)
self.is_face_up = face_up - -
super() ,
r . super<Positionae_Card. sel f) ._init_(rank.
su i t) 1 _i ni t _ ( ) ~d, Pos i t i n _
rd . - _ i nit_ ( rank. suit) -
-
, rank suit.
Pos i t i ona _ rd (
) , Card:
super() . - . . .
261
else:
rep = ""
return rep
_str_() is_face_
up. True, , .
,
_str_() Card,
Positionae_Card. , ,
, rd.
, , .
, :
def flip(self):
self.is_face_up = not self.is_face_up
, i s _face _up
. True, fl i ()
Fa 1se, , Fa 1se, fl i ()
True.
: - rd, -
Unprintae_Card, , - Positionae_Card:
#
cardl = Card("A". "")
card2 = Unprintae_Card("A". "d")
card = Positionae_Card("A". "h")
Card:
rint(" Card:")
pri nt ( rdl)
, .
Unpri ntab l _ rd:
print("\nneaa Unprintae_Card:")
print(card2)
rank "", suit -
"d", : <
>, Unprintae_Card
_str_() "< >".
Positionae_
Card:
pri nt( "\n Pos i t i n e_Card: ")
print(card)
262 9. - . -
(i s_face_up = True},
_str_) _str_) Card,
Ah.
fl i () Positiona e_Card:
rint" Positionae Card. ")
rd. fl i () -
, is_face_up .
Pos i t i n rd:
print("\neaa Positionae_Card:")
pri nt ( rd)
input("\n\nHae Enter. .")
,
.
,
.
, ,
,
,
, ,
.
random
" " 3.
Python , ,
.
.
-, , ,
. , , rd,Hand
Deck ,
,
.
263
-, ,
.
; , .
(
) .
, , .
, I-
.
-, , .
, , ,
, ,
Python.
r r
, , .
, ,
, ,
, . ;
- , .
,
. . 9.7.
. 9.7. ,
~ ~.
, ,
, .
264 9. - . -
, Python.
,
(, ), ,
, .
games
, .
- (courseptr.com/downloads) Chapter 9.
games . .
#
#
class PlayerCobject):
""" . """
def _init_Cself. name. score = 0):
self .name = name
self.score = score
def str Cself):
rep =self.name + ":\t" + strCself.score)
return rep
def ask_yes_no(question):
""" '' '."""
response = None
while response not in ("". "n"):
response = input(question).lower()
return response
def ask_numerCquestion. low. high):
""" ."""
response = None
while response not in range(low. high):
response = intCinputCquestion))
return response
if name == " ma i n " :
- - - -
printC"B . .")
input("\n\nHae Enter. .")
games,
games . .
. ; .
. Player
: name score, -. , ,
_str_), .
- ask _yes _no() ask _number() -
q "-" 6.
,
. i f _name_ == "_mai n_"
, .
, . ,
games . ,
, .
265
, games, <1
. ,
- (www.courseptr.com/downloads)
Chapter 9. simple_game. .
#
#
import games. random
import , ,
, . ,
.
~~~~~~~~~~~~~~~~~~~~~~~~~~
, , , ,
, Pytho . . ,
, , ,
, .
, .
, , .
<1
.
.
, :
printC"opo - !\n")
again = None
while again != "n":
players = []
num = games .ask_number(question = " ? (2 - 5): ". low = 2.
high = 5)
, ask_number()
games. , ,
: _. _.
1 100 ( randrange() random)
. ,
Pl ayer. games,
, .
- .
for i in range(num):
name = input(" : ")
score = random.randrangeC100) + 1
player = games.Player(name. score)
players.append(player)
266 9. - . -
print("\nBo :")
for player in players:
pri nt Cpl ayer)
ask_yes_no() games ,
:
&-
,
Python, , ~- .
- , , (,
).
cards
-~- ~
rds. Hand Deck , 2.0i-,
rd Pos i t i onab1_ rd 3.0i-.
- ( courseptr.com/downloads)
Chapter 9. cards. .
# cards
#
class Card(object);
"'"' . """
RANKS = ["". "2". "3". "4". "5". "". "7". "8". "9". "10". "J", "". ""]
SU 1TS = [ "" . "d" . "h" . "s" J
def ~init~(self. rank. suit. face_up = True):
self. rank = rank
self. suit = suit
self.is_face_up = face_up
def str (sel f):
if self.is face up:
rep = self.rank + self.suit
else:
rep = ""
return rep
def flip(self);
self.is face up = not self.is_face_up
class Hand(object): -
""" : .
def ~init~(self);
self.cards = []
- 267
,
, . , ,
.
- . 9.1.
n 9.1. -
&
J_carc1 carcls.card -.
value - , -
.-
268 9. - . -
9.1 ()
&
IUl8CC
J_Deck cards.Deck -.
BJ_Card
J_Hand cards.Hand -. : name, -
, total,
J_Player J_Hand -
J_Dealer J_Hand ( -)
J_Game object -. : deck - -
J_Deck, dealer - J_Dealer players,
J_Player
, , ,
, ,
: ( ). r
,
.
,
, .
. 9.8.
BJ_Player BJ_Dealer
. 9.8. -
, , . 9.8,
.
,
. ,
. :
- 269
2
f<
.
.
.
cards games
, , .
-),) :
cards games.
,
- (www.courseptr.com/downloads) Chapter 9.
ackjack. .
# -
# 1 7
import cards. games
games, , ,
.
B_Card
BJ _Ca rd rds . rd.
BJ_Card value, :
cl ass J_Card(cards. Card):
""" -. """
VALUE = 1
@property
def valueCself):
if self. is_face_up:
v = BJ_Card.RANKS.indexCself.rank) + 1
270 9. - . -
if v > 10:
v = 10
else:
v = None
return v
va l ue 1 1 - ,
. J _ rd. RANKS.
i ndex ( se1f. rank). rank -,
(, "6" ),
BJ _ rd . RANKS ( 5 ).
, ( ,
"6" 6). ,
1; 1
. is_face_up False,
None.
n J_Deck
BJ_Deck --.
rds. Deck.
, cards. Deck' s popul ate( ),
BJ_Deck BJ_Card:
class BJ_Deck(cards.Deck):
""" "-".
def populate(self):
for suit in BJ Card.SUITS:
for rank in BJ Card.RANKS:
self.cards~append(BJ Card(rank. suit))
n J_Hand
BJ _Hand, rds. Hand, - ~.
-~. cards .Hand,
name, ~:
class BJ Hand(cards.Hand):
""" 7 ': "-" .
def _init_Cself. name):
superCBJ_Hand. sel f) ._init_()
self.name = name
_str _(),
:
def _str_Cself):
rep = self.name + ":\t" + superCBJ Hand. self)._str_()
if self.total: -
rep += "(" + strCself.total) + ")"
return rep
- 271
name ,
cards. Hand _ str_ () . tota l
None, .
.
tota l,
. 4 , ,
None. ,
, , 4.
@property
def total(self):
# value None. None
for card in self.cards:
if not card.value:
return None
# . 1
t =
for card in self.cards:
t += card.value
#.
contains_ace = False
for card in self.cards:
if card.value == BJ_Card.ACE_VALUE:
contains = True
# 11. 11
def is_busted(self):
return self.total > 21
,
se l f. tota l > 21 ,
. return
(, )
.
272 9. - . -
, ,
True F l se. ,
( ,
). is (
i s_on () ).
BJ_Player
J _Pl ayer, J _Hand,
:
class BJ_Player(BJ_Hand):
""" "-".
def is hitting(self):
response = games.ask yes no("\n" + self.name +" ?
(Y/N): ")
return response == ""
def bust(sel f):
print(self.name. ".")
self.lose()
def lose(self):
pri nt (self. name. ".")
def win(self):
printCself.name. ".")
def push(self):
printCself.name. " .")
).
BJ_Dealer
BJ_Dealer, BJ_Hand,
:
class BJ_Dealer(BJ_Hand):
""" "-".
def is hitting(self):
return self.total < 17
def bust(self):
pri nt ( se lf. name. . )
- 273
def flip_first_card(self):
first_card = self.cards[OJ
first_card.flip()
- i s_hi tt i ng ( ) - ,
. , 17 ,
, True, tota l
17, Fal se. bust() ,
. , fl i p_fi rst _ca rd()
.
BJ_Game
BJ_Game ,
(!-". play()
. , ,
,
_init_()
.
, .
class BJ_Game(object):
""" -. """
def _init_(self. names):
self.players = []
for name in names:
player = BJ_PlayerCname)
self.players.append(player)
self.dealer = BJ_Dealer("Dealer")
self.deck = BJ_Deck()
self.deck.populate()
self.deck.shuffle()
still_playing
sti l l_pl ayi ng ,
( ):
@property
def stil l_playingCself):
sp = [J
for player in self.players:
if not player.is_busted():
sp.appendCplayer)
return sp
274 9. - . -~
_additional_cards()
_additional_cards( ) .
player BJ_Player BJ_
i s_busted() Fal se,
Deal er.
i s_hitting() True, .
is_busted() True,
bust().
def additional cards(self. player):
while not player.is busted() and player.is hitting():
self.deck.deal(fplayer)) -
print(player)
if player.is_busted():
l ayer. bust ()
. -,
player. is_hitting() ,
player: J_Player J_Dealer. _additianal_cards() ,
. -, J _Pl ayer J _
Dea 1er bust (), l ayer. bust ()
.
play()
l ( )
:
# . ;
for player in self.still playing:
if player.total > self.dealer.total:
pl ayer. wi n()
elif player.total < self.dealer.total:
pl ayer .1 ose()
else:
1ayer. push ()
#
for player in self.players:
pl ayer. cl ear()
self.dealer.clear()
. ,
, ,
. <11> .
,
. ,
<1~>.
. ,
17. ,
.
. ,
, , - , -
.
main()
ma i ( ) ,
BJ _Game, .
l ( ) ,
.
def main():
print("\t\topo -!\n")
names = []
number = games.ask_number("Coo ? (1 - 7): " low = 1. high
= 8)
for i in range(number):
name = iut(" : ")
names.append(name)
print()
game = BJ_Game(names)
again = None
while again != "n":
game. l ()
again = games.ask_yes_no("\nXoe ? ")
main()
iut("\n\ Enter. .")
276 9. - . -
. ,
.
. -
. ,
.
.
,
.
, .
, : m
, , n .
- , . n
- , .
n - ,
, , .
10
.
<<
>>
, ,
.
. (GUI) -
. GUI
;
.
GUI. , :
GUI;
;
;
;
.
,.
'!>,
, .
,
.
. ,
. . 10.1-10.3. ,
~ GUI.
278 10. .
7~ 11 11 1! 1~,n...,i
~ r 3
: 1
. .: 1
11>11>: 1
l4 (-): n11 11!8011
: r r ~ r nr !
pa<(J(o I
1
- -- - - - -- - - -- - ~ -
. 10.1 . GUI
7~ l\
1 > .\ @) i._,,a.d
n !
8t<:~; !
. . : l
11: !!
nn (-): J;1' nl /;1 n
: r r. (' nG
pac(J(o I
'
_.. _____ - -- --~ -- - - -- - -
. 10.2.
7'
n
: !
. .: ~!__
n-__
_ _ _ __
11111111: !!
11 (-): ' j'; n1138811
: r (' nano r n1
11
s ceoeti - n
, , , ~. ~<!
11 . 1 f180J ,
t'! . n~. , HI!
. nepewn11 ~ 1
. ? J .
. 10.3.
GUI 279
GUI
, GUI,
,
. . 10.4
.
8J1 R 311
111 : ,..,
__ __
11.n . .:
r : 1l
(
r -~): w n11~
: r r. 611W11 u r
! t+< ! :
, I<, , ..
J1.1 "111t1. J n111J n1'13, 1'1 11
wy nyew ~-11. not1Ctc:OD 1 :11. 1
w r n . f\f1-t J
. d? , ~ ) .
. 10.4.
GUI Python,
GUI. ;
- Tkinter.
~~~~~~~~~~~~~~~~~~~~~~~~
Windows, - ,
kinter , ,
. kinter Python: http://www.python.org/
topics/tkinter.
n 10.1. GUI
n n tkinter n n
Frame GUI
Lael , -
.,
280 10. .
10.1 ()
llacc tkinter
Button n <r -
Entry
Text
Checkbutton
-
Radiobutton
~~~~~~~~~~~~~~~~~~~~~~~~
. ,
.
GUI, , -. ,
. - () -
, .
GUI (, ),
- .
, ~
. ,
Python, ,
, ,
input( ). ,
, . .
, . ,
, GUI,
.
.
(, )
(, ).
. ~
( ), ,
( ).
, , .
, ,
. , U1',
.
,
.
GUI 281
,
. , ,
- .
- ,
, , GUI.
GUI , . <:<
~ ,
.
GUI
GUI~ , ,
: . . 10.5.
. 10.S. - .
- , ?
~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~
,
: , ,
. Windows ,
,
. , ,
simple_gui.py, :
simple_gui.py
pause
, .
, , ( Word
WordPad). . . t (, simple_gui . t) .
, .t .txt.
.
- (www.courseptr.com/downloads) Chapter 10.
282 10. .
, . 10.5, GUI
( ) -
, . 10.6.
. 10.6.
, GUI,
. ( )
Tkinter ,
. , GUI
.
~~~~~~~~~~~~~~~~~~~~~~~~~~
GUI-, , ,
. Windows,
. .pyw.
- (www.courseptr.com/
downloads) Chapter 10. simple_gui . .
tkinter
!
GUI tkinter:
# GUI
#
from tkinter import *
tk i nter
. , -
GUI 283
, tki nter, .
, .
r
, Tk tk i nter:
#
root = TkO
, tkinter Tk
. , tk i nt.er .
,
, .
~~~~~~~~~~~~~~~~~~~~~~~~~-
8 l<inter .
, , .
r
,
:
#
rt.titl(" GUI")
root. geometry( "200100")
title() . ,
.
" GUI ".
geomet ry ) .
( ) ,
.
200 , - 100 .
r r
mainloop(),
:
#
root. mai nl ()
,
. ,
. ,
, .
; simple_gui. bat.
284 10. < .
GUI . ,
, - / ,
. ~~
- , .
, :
, . ,
. ,
.
,
Labe1,
. . 10.7.
74 , '"'
' ~!
. 10.7. GUI
- (www.courseptr.com/
downloads) Chapter 10. labeler. .
: tki nter
.
# .
#
from tkinter import *
#
root = Tk()
root.title("o . ")
root .geomet ry ( 20050")
- ,
, .
, .
, :
#
= Frame(root)
285
,
, . -
Frame root. ,
.
grid() :
app.grid()
grid() . .
, .
,
.
u Label:
#
l = Label(app. text =" !")
Label .
, - .
.
."1,
. . ,
, text ! ",
!.
gridC) -:
l .grid()
GUI.
,
GUI:
#
root.mainloop()
, Button, -
- . , ,
.
286 10. .
~ , ,
, . -
. ,
. . 10.8.
. 10.8. :
- (www.courseptr.com/
downloads) Chapter 10. l azy_buttons. .
, , tki nter, :
#
#
from tkinter import *
#
root = Tk()
rt . titl(" ")
root. geomet ry ( 20085 )
#
= Frame(root)
app .grid()
, Button.
:
#
bttnl = Button(app . text = !")
bttnl .grid()
!.
- ; ,
.
,
, tk i nter . ,
GUI 287
, . ,
, , .
, .
:
#
bttn2 = ButtonCapp)
ttn2.grid()
, : -
. ,
. . ,
configure( ):
ttn2.configureCtext =" !")
#
ttn = Button(app)
ttn.grid()
text :
, text ,
. " ! ",
!. (~),
, .
, GUI
:
#
root. mai nl ()
GUI
,
.
. , ,
GUI-, .
288 10. .
r - 2
- 2 - ,
. , ,
.
. 10.9.
' 7~ 61113 ~ 2 [ =1
@J 1 d'
. 10.9. -. ,
,
- (www.courseptr.com/
downloads) Chapter 10. lazy_buttons2. .
tkinter
,
- :
# - 2
# tkinter
from tkinter import *
Application
Appl ication, Frame:
class Application(Frame):
GUI- .
Frame,
l i cat i on, .
, l i cat i on - .
-
l i cat i on :
def _init_(self . master) :
" . "
super(Application. self) ._init_(master)
self.grid()
self .create_widgets()
. l i -
cat i on ();
GUI 289
, . create _
widgets( ), .
, r
create_wi dgets ), :
def create_widgets(self):
""" . """
#
self.ttnl = Button(self. text = " !")
self.bttnl.grid()
#
self.ttn2 = Button(self)
self.ttn2.grid()
self.ttn2.configure(text =" !")
#
self.ttn = Button(self)
self.bttn.grid()
self.ttn["text"J =" !"
,
4 .
, bttnl, bttn2 ttn - 1i cat i on.
: se 1f,
, 4 1i cat i on.
Application
,
:
#
root = TkO
root.titleC"ecnoee - 2")
root .geometry( "20085")
l i t i on
root:
= Application(root)
1i cat i on root. -
create_widgets( ), , ,
1i cat i on .
, , ,
GUI:
root.mainloop()
290 10. .
GUI-, , .
,
. ,
, ~> .
GUI- ,
.
:~- : ,
. ,
()
. . 10.1.
11111 : s I
. 10.10. , ,
,
- (www.courseptr.com/
downloads) Chapter 10. cl ick_counter. .
- :
#
#
from tkinter import *
l i cat i on:
class Application(Frame):
GUI-. .
def _init_(self. master) :
""" . "'"'
super(Application, self) ._init_(master)
sel f .grid()
self.bttn_clicks = #
self .create_widget()
. ,
sel f . ttn_cl icks = , ,
.
. Grid 291
create_widget() :
def create widget(self):
""" . -
.
self .bttn = Button(self)
self.ttn["text"J= " : "
self.ttn["command"J = self.update count
self.ttn.grid() -
comand update_count ( ). ,
, li .
, " ( ) (
upda te_count ( ) ). comma nd
, -.
update_count ( ), :
def update count(self):
""" . '""'
self.ttn clicks += 1
self.ttn["text"J = " : " + str(self.bttn_clicks)
,
. , - .
#
root = Tk ()
root.title("Koeco ")
root. geometry( "20050")
= Application(root)
root.mainloop()
root, .
1i cati
root.
, GUI .
.
Grid
GUI- ,
- .
292 10. . r
. :
, ,
. ,
. ,
.
,
.
Grid, . Grid
GUI.
,
.
, 100 ,
secret.
.
, , ,
. . 10.11 10.12.
'7~ r:1G1<
l ::> 11;;] ~..,, .,,j
: ! !I
. 1
,
.
. 10.11. ,
'74 :
i=l!;;JJ..13 ,,
,
: /secret
. 1
100 ,
99,
.
. 10.12. , ,
,
- (www.courseptr.com/
downloads) Chapter 10. longevity. .
. Grid 293
r r
, :
#
# . Grid
from tkinter import *
class Application(Frame):
""" GUI - . . """
def _init_Cself. master):
""" . """
super(Application. self). init (master)
self.grid() - -
self.create_widgets()
tkinter Appl ication.
- l i cat i . ,
, create_widgets( ).
Grid
create_widgets()
:
def create_widgets(self):
""" . . """
# -
sel f. inst_l = Label (sel f. text = " .
")
, ?
Grid , :
, .
2,
: - , ,
- , 1 ( rowspan
).
. 10.13. ,
row column
- .
( ), sticky. ,
, - : (N), (S), ()
(W). ( ),
. W
sticky -,
- .
,
:
#
self.pw l = Label(self. text = " : ")
self.pw-l .gridCrow = 1. column = . sticky = W)
- Entry:
#
self.pw_ent = Entry(self)
, .
,
:
#
self.submit_bttn = Button(self. text " " . command self .
reveal)
r r. Grid 295
revea l (),
, .
:
r o6nacr
- Text:
# .
self.secret_txt = Text(self. width = 35. height = 5. wrap = WORO)
, wi dth hei ght,
. wrap ,
: - WORD, CHAR NONE.
WORD ,
, . CHAR
:
. , NONE
.
,
~ ~:
self .secret_txt.grid(row = 3. column = . columnspan = 2. sticky = W)
r : r
revea l (), ,
. ,
, , , .
, .
get() Entry:
def reveal(self):
~. """
contents = self.pw_ent.get()
get ( ) .
Entry, Text. , secret. ,
(, message)
, 100 .
, .
if contents == "secret":
message =" 100 . 99. " \
" ."
else:
message = " . "\
" ."
296 10. .
, , .
. ,
Text. delete( ):
self.secret_txt.delete(0.0. END)
.
: . 4"
,
: - ,
- . , ,
. , , ,
- - -
.
tk i nter , ,
END, . ,
. delete()
: Text, Entry.
, , :
self.secret_txt.insert(O.O. message)
i nsert () .
: .
, 4~ . , .
r message,
. i nsert () .
~~~~~~~~~~~~~~~~~~~~~~~~~~
insert() , .
, delete().
,
. l i cat i , .
, , .
#
root = Tk()
rt.titl("")
root. geometry( "300150")
= Application<root)
root. mai nl ()
, .
297
,
.
~
: , , .
,
, . .
. 10.14.
i= l @Jl... ."J
7/J
, :
" >t
'
.
s .
. 10.14.
- (www.courseptr.com/
downloads) Chapter 10. movie_chooser. .
~ tki nter
l i cat i on:
#
#
from tkinter import *
class Application(Frame) :
""" GUI-. . """
def _init_(self. master):
super(Application. self)._init_(master)
sel f.grid()
self.create_widgets()
, :
def create_widgets(self) :
'"'" . . """
298 10. .
# -
LabelCself.
text = " ~ "
).grid(row =. colLmn =. sticky = W)
, , :
Label .
, ,
, . tkinter
Labe1, ,
. ,
, .
- .
. - ,
. Labe 1 ,
.
:
# -
LabelCself.
text = " . :"
).gridCrow = 1. column =. sticky = W)
,
.
- .
, .
, ,
.
~ BooleaVar tkinter.
~ BooleanVar
1i kes_comedy, :
# ""
self.likes_comedy = BooleanVar()
() - ,
. n . n-r w11 ,
.
CheckbuttonCself.
text ="".
variae = self.likes_comedy.
299
cornand = self.update_text
).grid(row = 2. column =. sticky = W)
, .
se l f. 1i kes _comedy va ri 1, ( <~:-.
<~:) l ikes_comedy. command self .up-
date_text( ), ( )
update_text ( ). .
, Checkbutton .
,
likes_comedy.
:
# " "
self.likes_drama = BooleanVar()
Checkbutton(self.
text = "".
variale = self.likes_drama.
cornand = self.update_:ext
).grid(row = 3. column =. sticky = W)
# " "
self.likes_romance = BooleanVar()
Checkbutton(self.
text = " ".
variale = self.likes_romance.
command = self.update text
).grid(row = 4. column =. sticky = W)
,
, update_text( ).
Checkbutton - ,
1i kes_drama, -
1i kes_romance.
, , -
:
#
self.results_txt = Text(self. width = 40. height = 5, wrap = WORD)
self.results_txt.grid(row = 5. column =. columnspan = 3)
r
update_text( ),
,
:
def update_text(self):
""" .
. """
likes = .".
i f se l f. l i kes _comedy. get ( ) :
300 10. < . <
,
1i cat i , .
#
root = TkO
root.title("Koa")
= Application(root)
root. ma i nl ()
,
. , ,
.
.
-2
4'-2 .
, ,
, .
,
.
. 10.15.
- (www.courseptr.com/
downloads) Chapter 10. movi e_chooser2. .
301
r- R
i
- 11 .
. 10.1 S.
r
tki nter:
# -2
#
from tkinter import *
Appl ication. ,
1i cat i :
class ApplicationCFrame):
""" GUI -. . ."."
def _init Cself. master) :
""" . """
superCApplication. self) . init Cmaster)
self.grid() - -
self.create_widgets()
,
:
def create_widgets(self) :
."". . . ."".
# -
Labe 1 se lf .
text = " "
).gridCrow =. column = . sticky = W)
# -
Labe 1 se lf .
text =" :"
).grid(row = 1. column =. sticky = W)
, ,
, , , .
-
StringVar tkinter.
302 10. . <
. ,
, StringVar,
. favorite
set() None:
#
self.favorite = StringVar()
self.favorite.setCNone)
:
# ""
Radiobutton(self.
text = "".
variale = self.favorite.
value ="..
command = self.update_text
).grid(row = 2. column =. sticky = W)
va ri 1 se l f. favori te,
val ue , ,
. va l ue
". ", , ,
StringVar, self. favorite,
".".
:
# ""
RadiobuttonCself.
text = "".
variae = self.favorite.
value =".".
corrnnand = self.update_text
).grid(row = 3. column =. sticky = W)
# " "
Radiobutton(self.
text = " ".
variale = self.favorite.
value =" ..
command = self.update_text
).grid(row = 4. column =. sticky = W)
va ri l se l f. fa-
vori te, value- ".". ,
StringVar, self. favorite,
"."
.
,
:
#
self.results txt = Text(self. width = 40. height = 5. wrap = WORO)
self.results-txt.grid(row = 5. column =. columnspan = 3)
JJ 303
, get ( )
Stri ngVar:
def update_text(self):
"'"' . .
message = "
message += self.favorite.get()
, se 1f. favori te. get ()
".", - ".". ,
, sel f. favori te.get() " '1. ".
, , , ,
-
:
self.results_txt.delete(O.O. ENO)
self.results_txt.insert(O.O. message)
, 1i cat i on,
, GUI.
#
root = Tk()
root.title("Koa-2")
= ApplicationCroot)
root. mai nl ()
,
, ,
GUI. ~ ~
, .
(www.courseptr.com/downloads) Chapter 10.
mad_l ib. .
tkinter
, , , , tki nter,
:
#
#
from tkinter import *
304 10. .
- Application
,
Appl ication create_widgets( ):
class Application(Frame):
""" GUI-n. . """
def ~init~(self. master):
""" . """
superCApplication. self). init Cmaster)
self.grid() ~ ~
self.create_widgets()
create_widgets() Application
GUI .
, u,
, , text va 1ue:
def create_widgets(self):
""" .
.
# -
LabelCself.
text = " "
).grid(row =. column =. columnspan = 2. sticky = W)
#
LabelCself.
text = " : "
).grid(row = 1. column =. sticky = W)
self.person_ent = Entry(self)
self.person ent.grid(row = 1. column = 1. sticky = W)
#
Label Csel f.
text = " . . : "
).grid(row = 2. column =. sticky = W)
self.noun ent = Entry(self)
self.noun-ent.grid(row = 2. column = 1. sticky = W)
#
Label(self.
text =" :"
).grid(row = 3. column =. sticky = W)
self.verb_ent = Entry(self)
self.verb ent.gridCrow = 3. column = 1. sticky = W)
#
Label(self.
text =" (-):"
).grid(row = 4. column =. sticky = W)
# ""
self.is_itchy = BooleanVar()
Checkbutton(self.
305
text = "",
variae = self.is_itchy
).grid(row = 4. column = 1. sticky
= W)
# ""
self.is_joyous = BooleanVar()
Checkbutton(self.
text = "".
variale = self. is_joyous
).grid(row = 4. column = 2. sticky = W)
# "1"
self.is electric = BooleanVar()
Checkbutton(self.
text = "".
variale = self.is electric
).grid(row = 4. column = 3. sticky = W)
#
Label(self.
text = "Body rt:"
).grid(row = 5. column =. sticky = W)
# n.
se 1f. body_part = Stri ngVar()
self.body part.set(None)
# n
body parts = ["n". " ". "n "]
column = 1
for part in body_parts:
Radiobutton(self.
text = part.
variale = self .body_part.
value = part
).grid(row = 5. column = column. sticky = W)
column += 1
#
ButtonCself.
text = " ".
command = self.tell_story
).grid(row = 6. column =. sticky = W)
self.story txt = Text(self. width = 75. height = 10. wrap = WORO)
self.story=txt.grid(row = 7. column =. columnspan = 4)
tell_story() Application
, ,
- .
, , , ,
.
r
.
l i cat i on,
mainloop() .
#
root = Tk()
rt.titl(" ")
= ApplicationCroot)
root. ma i nl ()
307
. ~
- -
.
, , , ,
. ,
, Gri d.
,
- . ,
- GUI.
,
>>,
11 .
3: .
, !.
, .
.
11 << >>
, ,
.
. ,
,
Python. :
;
;
;
;
, ;
.
, ,
. :
-
.
, :
.
.
,
, . . 11.111.2.
pygame livewires
pygame l i vewi res (
), Python
.
, , . .-
pygame livewires 309
. 11.1 .
. 11 .2. -
310 11. .
:
, . pygame 1i vewi res, r
, , ,
r
. r r.
r.
pygame, (Pete Shinners), - ,
.
Python .
, .
, l i vewi res - ,
r, , ,
pygame, .
1i vewi res
. 1i vewi res
pygame,
.
, ,
pygame l i vewi res.
- (www.courseptr.com/downloads) Software.
, .
~~~~~~~~~~~~~~~~~~~~~~~~~~-
UveWires (http://www.tivewires.org.uk),
, LiveWires livewires,
-. ,
. , ;
.
pygame, http://www.pyga-
me.org.
, 1 -
<11>, .
,
l i vewi res. <1 , ,
. . 11.3.
. 11.3. . ,
~~~~~~~~~~~~~~~~~~~~~~~~~~
, n kinter,
livewires IDLE. Windows, ,
. ,
" GUI" 10.
- (www.courseptr.com/
downloads) Chapter 11. new_graphics_wi ndow. .
games
1i vewi res . games,
.
- ,
from. : from, , import (
, ).
games
1i vewi res:
#
#
from livewires import games
312 11. .
games ,
.
games . 11.111.2.
, .
Message Text. ,
r
games.screen.mainloop()
games,
screen -
. mainloop() fps
. , ,
, 50 .
screen . 11.3,
- . 11.4.
313
11.. screen
width r
height
fps n ( )
back.ground
all ojects ,
event_grab , , n
. , True, - False
11.4. screen
add(sprite) Sprite ( )
d()
mainloop()
quit()
. - .
screen , Ji.
" ~ - " ~.
. 11.4,
.
4' ~. "
~. mainloop( ).
- (www.courseptr.com/
downloads) Chapter 11. background_image. .
#
#
from livewires import games
games.init(screen_width = 640. screen_height = 480. fps = 50)
wall image = games. load image("wall .jpg". transparent = False)
games.screen.background-= wall_image
games.screen.mainloop()
- ,
,
314 11. .
.
, :
l oad_image() games,
wa l l . j pg -
wa l l _i mage.
~~~~~~~~~~~~~~~~~~~~~~~~~~
, , ,
, 7. , ,
, , .
, .
load_image() : () -
, () - transparent.
, , , transparent.
:
transparent = False.
, , ,
JG. l oad_ image() -
315
. ,
, GIF, PNG, TGA.
- -
, background screen.
:
games.screen.background = wall_image
- wa 11 _i mage.
i n1( ) ,
.
r
, , 640
480 ; .
.
640
480 . -
, . , r
, : ( ) (
). - .
,
, (; ).
, - . ,
, ,
(639; 479). . 11.5
.
, Game Over,
:
. ,
.
, ,
, , , ,
.
, .
!
316 11. .
. 11.5. :
,
. ,
, .
, <:< :
, - .
, .
. , I-
: - , Microsoft Office
. ,
. (!.
Microsoft , , Office 2007 .
: ,
, .
,
, :
.
01 317
-
-, ,
,
.
. 11.6.
- - ,
mainloop() ,
. -
(www.courseptr.com/downloads) Chapter 11. pizza_sprite.py.
. 11.6. - , ,
Sprite
# -
#
from livewires import games
games.init(screen width = 640. screen height = 480. fps = 50)
wall_image = games.load_image("wall .jpg". transparent = False)
games.screen.background = wall_image
pizza_image = games . load_image( "pizza .bmp")
pizza = games.Sprite(image = pizza_image. = 320. = 240)
games.screen.add(pizza)
games .screen .mainloop()
318 11. .
,
-:
. 11.7. .
transparent,
, ( , ),
;
. . 11.8 ,
, ~ .
, ,
,
.
~~~~~~~~~~~~~~~~~~~~~~~~~
, , ,
. ,
, , .
Spri te
(320; 240 ), .
pizza. Sprite,
, () ().
, ,
. :
games .screen.add(pizza)
add() .
~~~~~~~~~~~~~~~~~~~~~~~~~~
, . ,
- .
. , .
, .
, . , -
.
, , , ,
: ,
. ,
,
.
320 11. .
11.5. Sprite
it
angle
dx
dy r
left ~
right 01
top
ottom 01
image -, 01
over1appig_sprites ,
is_collideae , , ,
-
n 11.6. Sprite
update() .
mainloop()
destroy()
r
- ,
, -
. : games
Text.
r
!
,
Text. 4 !,
4 ,
, , .
, . 11.9.
r 321
. 11.9. Text
- (www.courseptr.com/
downloads) Chapter 11. bi g_score. .
# !
#
from livewires import games . color
games .init(screen_width = 640. screen_height = 480. fps = 50)
wa 11 _i mage = games .1oad_ i mage( "wa 11 . jpg". transparent = Fa 1se)
games.screen.background = wall image
score = games .Text(value = 1756521.
size = 60 .
color = color.ack .
550.
=
= 30)
games.screen .add(score)
games.screen .mainloop()
color
livewires, games, color,
, .
, Text Message
322 11. .
( ,
l i vewi res ).
,
color.
i mport :
from livewires import games. color
l i vewi res 1or games.
Text
Text .
mai nl ( ), Text score:
score = games.Text(value = 1756521.
size = 60.
color = color.ack.
= 550.
= 30)
- Text
: , , , ,
.
val ue 17 56521. ,
(, va 1ue, Text
). s i ze 60 -
. , .
1or 1or.1 ack, l or.
, . ,
550 30,
(550; 30) - .
Text
,
:
games.screen.add(score)
mai nl () ,
score.
Text - Sprite,
, . ,
Text, . 11.7.
11.7. Text
value , r
color
323
, -
. , ,
~, , 7 .
Message.
r r
- .
Message mainloop( );
: !.
, , .
. 11.10.
.11.10. !
- (www.courseptr.com/
downloads) Chapter 11. you_won. .
#
#
from livewires import games . color
324 11. .
color
accaMessage, Text, color.
,
games l or:
Message
Message, games.
- Text: ,
.
, .
- Message , Text,
: l ifetime after_death. l ifetime
, ma i n1( ),
. after _death
, r, Message .
after _death None,
- .
Message mainloop():
won_message = games.Message(value ="!",
size = 100,
color = color.red.
= games.screen.width/2.
= games.screen.height/2.
lifetime = 250.
after_death = games.screen.quit)
,
! ,
. Message
1i fet i me, 250, <1 ~
5 , mainloop() 50-.
01 325
~~~~~~~~~~~~~~~~~~~~~~~~~
after_death ,
.
screen width, ,
height, .
,
.
, , Message ,
games. screen. width/2 games. screen. height/2.
, - ,
. ,
.
Message
:
games.screen.add(won_message)
Message - Text,
, . ,
Message, . 11.8.
lifetime , mainloop(),
.
. -
after_death , -
. None
, .
,
Spri te ,
.
326 11. .
r
- ~-1>.
,
- !
. 11.11.
. 11.11. , ,
- (www.courseptr.com/
down!oads) Chapter 11. movi ng_pi zza . .
#
#
from livewires import games
games.init(screen_width = 640 . screen_height = 480 . fps = 50)
wall_image = games.load_image("wall.jpg". transparent = False)
games .screen.background = wall_image
pi zza_ image = games . l oad_ i mage( "pi zza . bmp")
the_pizza = games .Sprite(image = pizza_image .
= games .screen.width/2.
= games.screen.height/2 .
dx = 1.
dy = 1)
games.screen.add(the_pizza)
games.screen.mainloop()
327
r r
, , , - ,
. -
dx dy:
the_pizza = games.Sprite(image = pizza_image.
= games.screen.width/2.
= games.screen.height/2.
dx = 1.
dy = 1)
Sprite dx dy,
(d - , ). , dx-
, ma i n1 ( )
dy - .
dx , - ;
dy , - .
- dx dy
. dx dy,
. ,
dx dy 1, ,
ma i nl ( ) , 1
() 1 ().
r
- , ,
.
, , .
,
. .
, -,
. -, (, ).
-, , . , -,
, , ,
. , , , .
, , , ,
, ,
, . , ,
, dy
, .
328 11. .
, dx. . 11.12
.
. 11.12. ,
- (www.courseptr.com/
downloads) Chapter 11. bounci ng_pi zza. .
- :
#
#
from livewires import games
games.init(screen_width = 640. screen_height = 480. fps = 50)
, games
.
Sprite
-,
: . Spri te . -
329
,
Pizza:
class Pizza(games.Sprite):
""" . '""'
update()
, Pizza
. ,
mai nl ( ), :
dx dy;
update() .
Spri te update(),
. update() Pi zza -
.
def update(self):
""" .
.
bottom, ,
games. screen. hei ght, - .
top, ,
, .
dy - .
,
:
def main():
wall_image = games.load_image("wall.Jpg", transparent = False)
games.screen.background = wall_image
330 11. .
pizza_image = games.load_image("pizza.bmp")
the_pizza = Pizza(image = pizza_image.
= games.screen.width/2.
= games.screen.height/2.
dx = 1.
dy = 1)
games.screen.add(the_pizza)
games.screen.mainloop()
#!
main() 1
. :
, Pizza, Sprite.
update(), , ,
",
l i vewi res, -
: .
.
l i vewi res .
r r
mouse games .
.
, ~.
, , .
. 11.13.
- (www.courseptr.com/
downloads) Chapter 11. . movi ng_pan. .
r r
, , :
#
#
from l i ve 1i res i mport games
games.init(screen_width = 640. screen_he;ght = 480. fps = 50)
main() :
if name _main_
main()
,
. main()
, - import . - .. . .
331
. 11.13.
, games
. i ni t () mouse,
.
Pan -:
class Pan(games.Sprite):
"""" . """
def update(self) :
'""' .
self .x = games .mouse.x
self.y = games.mouse .y
Spri te, mouse ,
, -
.
. update() Pan
, ( mouse ), ,
( mouse ). ,
.
332 11. .
main() ,
.
:
def mainO:
wal l_image = games. load_image("wall .jpg". transparent = False)
games.screen.background = wall_image
pan_image = games. l oad_i mage( "pan. bmp")
the_pan = Pan(image = pan_image.
= games.mouse.x.
= games.mouse.y)
games.screen.add(the_pan)
games . mouse. , -
games .mouse.y, Pan , .
ma i n <) i s_vi si l mouse,
.
games.mouse.is_visile = False
True,
, Fa l se, :
, .
main() event_grab screen,
( ) :
games.screen.event_grab = True
True,
, .
event_grab False,
: .
~~~~~~~~~~~~~~~~~~~~~~~~~
n , .
, Esc.
, , ma i n() ma i nl ( ) ,
, ma i n().
games.screen.mainloop()
# !
mai n()
333
mouse
. 11.9.
is_visie , , :
True - , False - . - True
.
,
;
. .
, .
- . ,
, ,
: .
,
.
. 11.14 11.15.
- (www.courseptr.com/
downloads) Chapter 11. s l i ppery_pi zza . .
#
#
from livewires import games
import random
games.init(screen_width = 640. screen_height = 480. fps = 50)
random - ,
,
.
334 11. .
. 11.14. , - ...
. 11 . 15. . ..
335
Pan,
:
class PanCgarnes.Sprite):
"""" . . '"'"
def update(self):
""" . .
self.x = games.mouse.x
self.y = games.mouse.y
self.check_collide()
def check_col l ideCself):
""" . .
for pizza in self.overlapping_sprites:
pizza.handle_collide()
update() check_collide(),
, , ,
overlapping_sprites Pan. ,
Pan .
handle_col l ide( ). , @~
.
Pi zza:
class Pizza(games.Sprite):
"""" . """
def handle_collide(self):
'""' . """
self.x = random.randrange(games.screen.width)
self.y = random.randrangeCgames.screen.height)
handl _ l l i de(),
Pi zza.
main( ):
def main():
wall_image = games.load_image("wall.jpg", transparent = False)
games.screen.background = wall_image
pi zza _image = games. l oad_imageC "pi zza. bmp")
pizza_x = random.rar.drangeCgames.screen.width)
pizza_y = random.radrange(games.screen.height)
the_pizza = PizzaCimage = pizza_image. = pizza_x. = pizza_y)
games.screen.addCthe pizza)
pan _image = games. l oad_ image( "pan. bmp")
336 11. .
= games.mouse.y)
games.screen.add(the pan)
games.mouse.is_visible = False
games.screen.event_grab = True
games.screen.mainloop()
# !
main()
, , .
, Pi zza Pan.
, .
;
. ma i n( ) ma i nl ( ). r
mai n( ).
, l i vewi res,
,
.
,
. -
(www.courseptr.com/downloads) Chapter 11. pizza_
panic.py.
r
,
:
#
# .
from livewires import games. color
import random
games.init(screen_width = 640. screen_height = 480. fps = 50)
games , l or
. random ,
- . ,
i ni t ( )
games.
Pan - ,
. ,
337
: .
.
:
- image. ,
~>
- ,
ma i ().
class Pa(games.Sprite):
. .
_init_()
-,
:
def _iit_(self):
""" Text -
.
superCPa. sel f) ._init_(image = . image.
= games.mouse.x.
bottom = games.scree.height)
self.score = games.Text(value = . size = 25. color = color.ack.
top = 5. right = games.scree.width - 10)
games.scree.add(self.score)
super() , - i i t ()
Sprite. score -
, . ,
.
update()
:
self.x = games.mouse.x
if self. left < :
se lf. l eft =
if self.right > games.scree.width:
self.right = games.scree.width
self.check_catch()
,
-. , l eft
338 11. .
, , ,
. ,
l eft .
, ri ght, , ,
games. screen. wi dth, .
, ri ght games . screen. wi dth
.
check_catch() . ,
:
def check_catch(self):
"'"' . .
for pizza i self.overlapping sprites:
self.score.value += 10 -
self.score.right = games.screen.width - 10
pizza.handle_caught()
, ,
10 . Text
1 - ,
. handle_caught() ,
.
Pizza
,
:
class Pizza(games.Sprite):
. .
image = games.load_image("pizza.bmp")
speed = 1
: image - speed -
. 1,
. -
Pi zza, .
_init_()
Pi zza:
def init Cself. . = 90):
-;;-;;-" Pi zza. "'"'
super(Pizza. self).~init~(image = Pizza.image,
= . = ,
dy = Pizza.speed)
,
Pi zza. , 90,
339
update()
:
def update(self):
. -
.
end_game()
. ,
.
~~~~~~~~~~~~~~~~~~~~~~~~~
end_game() , . ,
5 , , , ,
. 12 , ,
, ,
.
340 11. .
Chef
Chef - -, , ,
.
class Chef(games.Sprite):
. . -. .
_init_()
-:
dx = speed)
self.odds change = odds change
self.time-til drop = -
. image
Chef. image. ,
, - 55,
. dx
2.
: odds _change ti me_t i l _drop.
- odds_change - , ,
. , , odds _
change 200, 200,
. ,
update( ).
t i me_t i l _drop - i nl (),
.
; , Chef
. ,
check_drop( ).
update()
,
- :
check_drop()
ma i nl (), , ,
, 50 :
def check_drop(self):
'""'
.
if self.time_til_drop >:
self.time til drop -= 1
else: - -
new_pizza = Pizza(x = self.x)
games.screen.add(new pizza)
# ""
30 %
self.time_til_drop = int(new_pizza.height * 1.3 / Pizza.speed) + 1
t i me_t i l _drop, , - ,
. , ,
, 1;
Pizza, time_til_drop .
, Chef (
), , ,
. t i me_t i 1_
drop ,
30%
. .
main()
ma i n( ) :
def main():
""" . """
wall image = games.load image("wall.jpg", transparent = False)
games.screen.background-= wall_image
the chef = ChefC)
games.screen.addCthe_chef)
342 11. .
the_pan = )
games.screen.add(the_pan)
games.mouse.is_visie = False
games.screen.event_grab = True
games.screen.mainloop()
#!
main()
.
- .
, ,
. ,
ma i nl ( ). ma i n( ) .
, l i vewi res
.
. , ,
. -
-
. ,
4'- ,
. ,
, .
, n .
n : /
, , ,
, , , ( )
- , .
- . r
, - .
, .
12 , ,
.
<< >>
, .
, .
, , :
;
;
,
.
, ,
, . ,
~., ,
.
, , .
. , ,
, , .
, ,
.
, ,
. . 12.1 1 12.2.
. : N ASA, The
u Heritage Team - AURA/STScl.
344 12. , , .
~~ g wi~v
. 12.1. . ,
. 12.2.
345
i nput ( ) , . -
. , games ,
.
r
~
. ,
. , W , S-
, - , D- . ,
. ,
W D .
. 12.3.
.12.3. ,
- (www.courseptr.com/
downloads) Chapter 12. read_key . .
346 12. , , .
l i vewi res,
, :
#
#
from livewires import games
games.init(screen_width = 640. screen_height = 480. fps = 50)
- .
update() , , .
, .
class Ship(games.Sprite):
""" . """
def update(self):
""" . .
if games. keyboa rd. i s_pressed (games. K_w):
self .y -= 1
if games. keyboa rd. i s_pressed(games. K_s):
self.y += 1
if games.keyboard.is_pressed(games.K_a):
self.x -= 1
i f games. keyboard. i s_pressed(games. K_d):
self.x += 1
keyboard games.
( ) .
is_pressed() keyboard, True,
, Fal se - .
is_pressed() ,
,
W, S, D. W, ()
1 . S,
1 .
() 1, , D
1, .
i s_pressed()
,
, . , ,
D S :
update( ), ,
Shi .
games , .
i s_pres sed ( ).
W games. K_w, S - games. K_s, - games. _
347
D - games. K_d. . ,
, .
games. _.
,
. , , ,
games. _.
,
. , , 1, games. _1.
, . , ,
games. K_SPACE.
l i vewi res
.
ma i n ) .
,
mai nl ( ).
def mainO:
nebula_image = games.load_imageC"nebula.jpg", transparent = False)
games.screen.background = nebula_image
ship_image = games. load_image("ship.bmp")
the ship = Ship(image = ship image.
- = games.screen.width/2.
= games.screen.height/2)
games.screen.add(the ship)
games.screen.mainloopC)
mainO
11 , .
1i vewi res .
-.
<<
, ,
. -, ,
+--, . 1
0. 2
90, - (180),
4- 270,
. . 12.4.
348 12. , , .
~~~~~~~~~~~~~~~~~~~~~~~~~~
,
, , .
.12.4. , ,
- (www.courseptr.com/
downloads) Chapter 12. rotate_sprite. .
#
#
from livewires import games
games.init(screen_width = 640. screen_height = 480. fps 50)
l ass Shi ( games. Spri te):
.
def update(self) :
'""' . . "
if games.keyboard .is_pressed(games.K_RIGHT):
self .angle += 1
i f games. keyboa rd. i s_pressed (games. K_LEF) :
self.angle -= 1
if games.keyboard.is_pressed(games.K_l):
self.angle =
if games .keyboard.is_pressed(games .K_2):
self .angle = 90
349
angle
angl .
( ).
, ,
, .
update() , -. ,
angle Ship , ,
1. ,
+-. , angl
1 .
: angl . 1
angle
0. 2 angl 90,
90.
3, angl 180 .
, 4, angle 270,
.
, -
. games
, - Animation.
~
. ,
. , , ,
350 12. , , .
.
. 12.5.
. 12.5. , , ,
n
- ( ),
.
, , ,
. . 12.6.
- (www.courseptr.com/
downloads) Chapter 12. l os i on. .
,
:
#
#
from livewires import games
games.init(screen_width = 640 . screen_height = 4. fps 50)
351
. 12.6. ,
Ani mat i on -
, .
. ,
. 12.6:
explosion_files = ["explosionl .bmp".
"explosion2.bmp".
"explosion.bmp".
"explosion4.bmp".
"explosion5 .bmp".
"explosion . bmp".
"explosion7 .bmp".
"explosion8 .bmp" ,
"explosion9.bmp"J
352 12. , , .
u Ani mat i on :
explosion = games.Animation(images = explosion_files.
= games.screen.width/2.
= games.screen.height/2.
n_repeats = .
repeat_interval = 5)
games.screen.add(explosion)
Animation Sprite ,
. ,
.
,
.
,
, , .
(
) -. l osi on_fi l es
.
n_repeats (
, ).
, .
n_repeats . ; ,
,
.
repeat _i nterva l (
) .
, ; ,
, , . repeat _i nterva l
5. , , .
, mai nl () screen:
games.screen.mainloop()
.
, , ,
games.
, l i vewi res
, .
- , ,
353
, . . 12.7
( , ) .
. 12.7.
~~~~~~~~~~~~~~~~~~~~~~~~
f!:f .
, , 1.f .
, .
- (www.courseptr.com/
downloads) Chapter 12. sound_and_music . .
,
W -. W V ,
, .
:
#
#
from livewires import games
games.init(screen_width = 640. screen_height = 480 . fps = 50)
load_sound() games WV-.
#
missile_sound = games. load_sound("missile .wav")
- ,
. mi ss i l . wav epee
o mi ssi l e sound.
354 12. , , .
~~~~~~~~~~~~~~~~~~~~~~~~~
WV- load_sound().
#
games. musi . l oad( "theme .mid")
,
, .
,
5:
choice = None
while choice !="":
print(
-
1 -
2-
3 -
4 -
5 -
6-
)
choice = input( " : ")
pri nt ()
#
if choi == "":
pri nt (" .")
, .
1:
#
1 if choi == "1" :
missile_sound.play()
rint(" .")
, l ()
.
. , ,
. ,
pl () .
play() ,
,
, .
355
, 1 ) - ,
. , , 1 )
3,
( ). -1.
:
#
elif choice == "2":
1 = i ntC i nput( " ? ( -1 =
): "))
missile_sound.play(loop)
rint(" .")
,
,
pl () .
r
, ero
stop( ). ,
. stop() ,
, 1i vewi res .
, 3 ,
:
#
elif choice == "":
missile_sound.stop()
rint(" .")
1
1i vewi res , .
, -
. , ,
: , W AV,
, OGG MIDI. , , ,
.
, ,
.
, ,
. music games.
music ,
.
356 12. , , .
:1 :
#
elif choice == "4":
games.music.play()
rint(" .")
theme. mi d. games. mus i . l () ,
.
, l ()
. , , games. mu-
s i . l ( ) 3, (
). -1.
:
#
1if choi == "5" :
loop = int(input("Coo ? (-1 =
): "))
games.music.play(loop)
rint("~ :. ")
,
,
play( ).
r
6,
:
# ~
elif choice == "6":
games.music.stop()
rint(" .")
, games. mu-
s i . s top (), . ,
, l i vewi res
.
357
#
else:
rint(". ". choice)
input("\n\nHae Enter. .")
r
, , - ~.
,
. ,
- : ,
.
r
,
( - ),
, .
,
.
-
, .
, ,
, ~ ,
.
- , ,
.
- , ,
.
, .
, -
, .
, , .
, .
.
358 12. , , .
,
, .~: .
,
.
, , ,
:
Shi - ;
Missile- ;
Asteroid - ;
l os i on - .
- . , Shi , Mi ss i l Asteroi d
games. Sprite, l os i on - games. Ani mat i on.
, ,
.
, , , ,
, ,
. :
- ;
- ;
;
, ;
, ;
;
, -;
.
, ,
. , ,
-. , , .
, , -
,
. , ,
, .
359
- 1
,
, ,
. ,
.
. 12.8.
. 12.8.
J - (www.courseptr.com/
downloads)" Chapter 12. astrocrashOl . .
r
:
# -1
#
import random
from livewires import games
games.init(screen_width = 640. screen_height = 480. fps = 50)
random ,
.
360 12. , , .
Asteroid
Asteroi d , :
class Asteroid(games.Sprite):
'""' . . '""'
SMALL = 1
MEDIUM = 2
LARGE = 3
images = {SMALL : games. load_image("asteroid_small .bmp").
MEDIUM: games.load imageC"asteroid med.bmp").
LARGE : games. load_image("asteroid_big.bmp") }
SPEED = 2
, , - , SMALL, MEDIUM LARGE,
.
, -
. , ,
. ,
SPEED,
.
_init()_
-:
. Asteroid
s i ze.
update()
, ,
, :
361
main()
, ma i n( )
:
def main():
#
nebul _image = games. l oad_image( "nebul . jpg")
games.screen.background = nebula image
# 8 -
for i in range(8):
= random.randrange(games.screen.width)
= random.randrange(games.screen.height)
size = random.choice([Asteroid.SMALL. Asteroid.MEDIUM. Asteroid.LARGEJ)
new_asteroid = Asteroid(x = . =, size = size)
games.screen.add(new_asteroid)
games.screen.mainloop()
# !
mai n()
- .
,
.
.
- 2
~ - 2 ~ - 1~.
,
. --+
, +- - .
. 12.9.
- (www.courseptr.com/
downloads) Chapter 12. astrocrash02. .
362 12. , , .
.12.9.
Ship
, , - Shi , :
Ship
, , -
Shi .
main( ):
363
#
the ship = Ship(image = Ship.image.
- = games.screen.width/2.
= games.screen.height/2 )
games.screen .add(the_ship)
.
j ,
, .
, ,
.
r -
~ - 3 ,
, ,
. . 12.10.
. 12.1.
- (www.courseptr.com/
downloads) Chapter 12. astrocrashO. .
364 12. , , .
math
:
Ship
VELOCIY_
STEP Shi :
VELOCITY STEP = .03
,
; , , , .
sound,
- :
sound = games.load_sound("thrust.wav")
update() Ship
update() Ship ,
. :
t. , :
#
if games.keyboard.is_pressedCgames.K_UP):
Ship.sound.playC)
, , j, -
- dx dy Ship. ,
, ,
?
( , ,
). ,
, .
, :
#
- , , . Python math ,
( l i vewi res - , ),
, , ,
pi math, ~:~>.
365
~~~~~~~~~~~~~~~~~~~~~~~~~~
.
, ,
. , r
r r r ,
.
, .
,
. ,
; , ,
.
,
. - . .
, ,
, . - . .
366 12. , , .
- 4
- 41> , ,
. , , : ,
, 50 _r . ,
- , -
. - 4i.,
. 12.11.
- (www.courseptr.com/
downloads) Chapter 12. astrocrash04. .
. 12.11.
update() Ship
update() Shi , ,
. , :
367
# . ;:J
if games.keyboard.is pressed(games.K SPACE):
new_missile = Missile(self.x. self.y. self.angle)
games.screen.add(new_missile)
Mi ss i 1eCself. . self .. self. angl )
-, Mi ss i 1.
Missile
Mi ss i 1 , .
, :
class Missile(games.Sprite):
""" . .
image = games.load_image("missile.bmp")
sound = games.load sound("missile.wav")
BUFFER = 40 -
VELOCITY FACTOR = 7
LIFEIME = 40
i mage - ,
. sound ,
. BUFFER
( ,
, ). VELOCIY_FACTOR
. , LIFEIME -
(
, , ).
_init_()
:
,
: ship_x,
ship_y ship_angle. : , -,
, -,
.
, - .
- :
Missile.sound.play()
, , ,
:
#
angle = shio_angle * math.pi / 180
368 12. , , .
#
buffer_x = Missile.BUFFER * math.sin(angle)
buffer_y = Missile.BUFFER * -math.cosCangle)
= ship_x + buffer_x
= ship_y + buffer_y
.
;
Mi ssi l . BUFFER.
.
-
- , Shi :
#
dx = Missile.VELOCITY_FACTOR * math.sin(angle)
dy = Missile.VELOCITY_FACTOR * -math.cos(angle)
Spri te :
#
superCMissile. self) ._init_Cimage = Missile. image.
=.=,
dx = dx. dy = dy)
( Mi ssi l )
l i fetime, .
self.lifetime = Missile.LIFETIME
update()
update( ). :
def update( se lf):
""" .
# " " .
self.lifetime -= 1
if self. lifetime ==:
self.destroy()
- , l i fet i
. , Mi ssi 1 .
updateC)
:
#
if self.top > games.screen.height:
self.bottom =
if self.bottom < :
self.top = games.screen.height
if self.left > games.screen.width:
self.rignt =
if self.right < :
self.left = games.screen.width
369
. ,
- .
,
50 . ,
, .
.
- 5
~ - 5i> :
, ,
. . 12:12.
.12.12.
- (www.courseptr.com/
downloads) Chapter 12. astrocrash05. .
370 12. , , .
Ship
,
Shi :
MISSILE DELAY = 25
MISSILE_DELAY - .
,
. ,
, .
- Ship
-:
def _init_(self. . ):
"'"' .
super(Ship. selfJ._init_(image = Ship.image. = . = )
self.missile wait =
,
- games . Spri te.
mi ssi l e_wait. mi ssi l e_wait
, .
update() Ship
Shi update() -
missi le_wait .
# . 1
if self.missile_wait > :
self.missile wait -= 1
, ,
:
# .
if games.keyboard.is_pressed(games.K_SPACE) and self.missile_wait ==:
new_missile = Missile(self.x. self.y. self.angle)
games.screen.add(new_missile)
self.missile_wait = Ship.MISSILE_DELAY
, , , missile_wait
,
. mi ssi le_wait
MISSILE_DELAY, .
371
r
,
.
. , - , ,
.
. : ,
, , .
r - 6
~ - ~
overl appi ng_spri tes, .
, :
, ,
.
~~~~~~~~~~~~~~~~~~~~~~~~~
, ,
, ,
, . ,
.
. 12.13.
(www.courseptr.com/downloads) Chapter 12.
astrocrash06.py.
update() Missile
upda te ( ) Mi s s i l :
#
if self.overlapping_sprites:
for sprite in self.overlapping_sprites:
sprite.die()
self.die()
-
( ), ,
die( ). , Asteroid, Ship
Mi ss i 1.
die() Missile
Missile die() ,
. :
372 12. , , .
. 12.13. , , .
:
update() Ship
update() Shi :
#
if self.overlapping_sprites:
for sprite in self .overlapping_sprites:
sprite .die()
self.die()
-
, , die( ). ,
update() Mi ssi 1.
, , .
.
373
die() Ship
, Mi s s i 1:
def die(self):
"'"' . '"'"
se 1f. destroy()
Ship die( ),
.
Asteroid
Asteroid :
SPAWN = 2
SPAWN - ,
.
die() Asteroid
di () Asteroi d :
def die(self):
""" . """
# .
if self.size != Asteroid.SMALL:
for i in range(Asteroid.SPAWN):
new asteroid = Asteroid(x = self.x.
- = self.y.
size = self.size - 1)
games.screen.add(new_asteroid)
self .destroy()
, , , Asteroi d.
SPAWN Asteroi d.
.
, -
. , ,
.
,
- . .
374 12. , , .
- 7
- 7 games. Ani mat i on,
. ,
, .
, , , - .
. 12.14.
. 12.14.
- (www.courseptr.com/
downloads) Chapter 12. astrocrash07. .
Wrapper
, : games . Spri te
Wrapper.
update()
Wrapper update( ),
, :
375
class Wrapper(games.Sprite):
""" . . . . .
def update(self):
""" .
if self.top > games.screen.height:
self.bottom =
if self.bottom < :
self.top = games.screen.height
1 f se lf. 1eft > games. screen. wi dth:
self. right =
if self.right <:
self.left = games.screen.width
, . ,
, Wrapper,
update( ), .
di()
die( ), :
def di se lf):
""" .
self. destroy()
Collider
. ,
Shi Mi ssi l . Wrapper
Col l ider, ,
, ,
- .
update()
update( ), :
class ColliderCWrapper):
""" n. . -
. 111111
def updateCself):
""". . . """
super(Collider. self).update()
if self.overlapping sprites:
for sprite in self.overlapping sprites:
sprite.die() -
self.die()
update() 11 i der update()
, Wrapper, .
.
376 12. , , .
- ,
die( ), .
di()
di (), 11 i der
- :
def die(self):
. """
new explosion = Explosion(x = self .x. = self .y)
games.screen.add(new explosion)
self .destroy()
, , Explosion.
1os i on, , -
.
Asteroid
Asteroi d Wrapper:
class Asteroid(Wrapper):
Asteroid Wrapper update(),
update() . !
, die()
As teroi d se1f. di ( ) :
super(Asteroid. self).die()
, di () Wrapper , Asteroi d
.
Ship
Shi 11 i der:
class Ship(Collider):
update() :
super(Ship. self).update()
, .
update() Collider ,
Shi . ,
update() , , update() ,
, Shi ,
. di ( ):
, Col l ider.
377
Missile
Mi s si l , l l i der:
class MissileCCollider):
update() :
super(Missile. self).update()
Shi , . update()
l l i der ,
updateC) Mi ss i l .
,
( Wrapper), die() (
Collider).
~~~~~~~~~~~~~~~~~~~~~~~~
, ,
, - www.courseptr.com/
downloads.
Explosion
, Explosion ga-
mes. Ani mat i on.
class Explosion(games.Animation):
""" . ""
sound = games. l oad_soundC " l osi on. wav")
images = ["explosionl.bmp".
"explosion2.bmp".
"explosion.bmp".
"expl os ion4. bmp".
"expl osi on5. bmp".
"explosion.bmp".
"explosion7.bmp".
"explosion8.bmp".
"explosion9.bmp"J
sound .
- i mages - - ,
.
- - l os i on.
def _; nit_Cself. . ):
super(Explosion. self)._init_Cimages = Explosion.images.
= . =,
,
. ( games . Ani ma t i on ),
,
, . , . i mages
. - l os i on. i mages.
n_repeats 1,
. repeat_ i nterva l,
, 4. , i s_
collideae False, , ,
<t ,
. - Explosion.so-
und.play().
~~~~~~~~~~~~~~~~~~~~~~~~~
, games.Aimation
, -.
, ,
,
- . , ,
,
. ,
.
- 8
, ,
, ,
. ,
, . 12.15.
- (www.courseptr.com/
downloads) Chapter 12. astrocrash08. .
color
. games l i vewi res
l or:
Q p~g~ window
. 12.1 S. , ,
Gm
Game - ,
. , ,
, . - ,
: , l () - , advance() -
, end ( ) - .
, game
. ,
, , ,
, game ,
. , , game
.
Game, ,
ma i n( ) .
_init_()
Game :
class Game(object) :
""" . """
380 12. , , .
def ~init~<self):
""" Game.
#
self. level =
# .
self.soud = games. load sound("level .wav")
# .
self.score = games.Text(value =.
size = 30.
color = color.white.
top = 5.
right = games.screen.width - 10.
is collideae = False)
games.screen.add(self.scorJ
# .
self.ship = Ship(game = self.
= games.screen.width/2.
= games.screen.height/2)
games.screen.add(self.ship)
1eve l . sound
, .
score ,
. i s_col l idea
F l se, ,
~ . , shi - ,
.
play()
play( ), .
def play(self):
""" . """
#
games. mus i . l oad( "theme. mi d")
games.music.play(-1)
#
nebula_image = games. load_image( "nebula .jpg")
games.screen.background = nebula image
# 1 -
se l f. advance()
#
games.screen.mainloop()
,
. ,
.
Game - advance( ),
, ( , ).
, games. screen. ma i nl ( ).
, , 381
advance()
advance() .
l evel, ~~ ,
.
-
:
def advanceCself):
'""' .
self. level += 1
. ?
,
. , , ,
- . . ; ,
. , , .
#
BUFFER = 150
#
for i i range(self. level):
# . BUFFER -
#
x_min = random.randrange(BUFFER)
min = BUFFER - min
# .
distance = random.randrange(x min. games.screen.width - min)
y-distance = random.randrange(y-min. games.screen.height - min)
#- . -
= self.ship.x + x_distance
= self.ship.y + distance
# .
%= games.screen.width
%= games.screen.height
#
new_asteroid = Asteroid(game = self.
=.=,
size = Asteroid.LARGE)
games.screen.add(new asteroid)
BUFFER
. ,
. _mi n
, ; _mi n -
.
random, x_min y_min BUFFER.
382 12. , , .
x_di stance -
. , , :
, x_mi n.
, y_di stance - .
, ,
_mi n .
,
x_distance. ,
:
.
: y_di stance.
,
.
.
, Asteroi d game.
Game, ,
Game. sel f.
advance()
:
#
level_message = games.Message(value =""+ str(self.level).
size = 40.
color = color.yellow.
= games.screen.width/2.
= games.screen.width/10.
lifetime = 3 * games.screen.fps.
is collideae = False)
games.screen.add(level message) -
# ( 1- )
if se 1f. 1eve l > 1 :
self.sound.play()
nd()
end () Game
Over, . 5
. .
def end(self):
'""' . """
# 5- 'Game Over'
end_message = games.Message(value = "Game Over".
size = 90.
color = color.red.
= games.screen.width/2.
= games.screen.height/2.
lifetime = 5 * games.screen.fps.
, , 383
Asteroid
Asteroi d ,
. , , POINTS:
POINTS = 30
- ,
.
, .
,
, .
,
- tota l, , :
total =
- Asteroid
- , Asteroi d. tota 1
:
Asteroid.total += 1
Game,
.
Asteroi d:
def ~init~(self. game. . . size):
game , Game.
Asteroi d:
self.game = game
, Asteroi d
game - . As teroi d
Game, advance( ).
die() Asteroid
di () Asteroi d . -, ,
Asteroi d. tota 1 :
Asteroid.total -= 1
384 12. , , .
Asteroid.POINTS
, (
, ).
- . ri ght score
1 .
di () Asteroi d. tota 1
: ? ,
advance() Game,
.
# .
if Asteroid.total == :
self.game.advance()
Ship
Ship . -,
VELOCIY_MAX, :
VELOC = 3
- Ship
Asteroid, Ship Game,
. - Asteroi d
Shi :
def _init_(self. game. . ):
game Game,
Shi :
self.game = game
, Shi game -
. Shi
Game, end( ).
update() Ship
update() Shi :
, dx dy, _VELOC I,
:
385
#
self.dx = min(max(self.dx. -Ship.VELOCITY ). Ship.VELOCITY )
self.dy = min(max(self.dy. -Ship.VELOCITY-AX).
- Ship.VELOCITY-MAX)
-
, dx dy -Sh i . VELOC I_
Sh i . VELOC I_.
min() max( ). min() ,
max() - . , , ,
, , ,
.
die() Ship
, .
Ship die( ), , , end()
Game, .
def die(self):
."". . """
self.game.end()
super(Ship. self).die()
main()
, Game, ma i n() .
, Game l (),
.
def main():
astrocrash = Game()
astrocrash.play()
# !
main()
,
, . , ,
,
. ,
, ,
. , ,
, .
,
- ,
.
386 12. , , .
, -
. , - <
: , J\
.
( - (Simo Says).
11 ,
.
- , n
.
. : -
.
-
- www.courseptr.com/downloads.
r, ,
.
. :
pye_source. zi - ,
, ;
pye _softwa re- ,
, Python 3.1.1 Windows.
. .1 pye_source.zip, . .2 -
pye_software.zip.
n8 .1. pye_source.zip
chapterOl 1
chapter02 2
chapter03 3
chapter04 4
chapterOS 5
chapterO
chapter07 7
chapter08 8
chapter09 9
chapterlO 10
chapterll 11, ,
chapter12 12, ,
n8 .2. pye_software.zip
pytho Pytho 3.1.1 Windows
pygame pygame 1.9.1, Python 3.1. Windows
livewires ( ) livewires
~~~~~~~~~~~~~~~~~~~~~~~~~~
livewires
1i vewi res - ,
, , . . .1.
l ivewi res, ,
pygame.
8.1. livewires
n
games ,
color
games
games ,
. . .2.
8.2. games
n
Scree ,
Sprite
Text r -
. Text - Sprite
Message , -
.
Message - Text
games 389
n
Animatio , -
. Aimatio -
Sprite
Mouse
d
Music
Screen
Screen . games. i ni t )
screen Screen; ,
. . .3
Screen, . .4 - .
8.3. Screen
:n n
width
height
fps
ackgroud
all objects ,
evet_grab , , -
. , True, - False
8.4. Screen
n
get_width()
get_height()
get_fps()
get_ackgroud()
set_ackgroud ew_ackgroud
(ew_ackgroud)
get_all_objects() 01 ,
get_evet_grab() , . ,
True, - False
set_evet_grab
(ew_status) ew_status. rue - , False -
add(sprite) - Sprite
remove(sprite) - Sprite
clear()
mailoop()
quit()
390 . livewlres
Sprite
Spri te
. . .5 Spri te, . .6 -
.
.5. Sprite
Coiicro
image - -
width
height
angle
position . (, )
top
ottom
left
right
dx
dy
velodty . (dx, dy)
overtapping_sprites ,
is_collideable , ,
. True, -
, False -
interval tick()
.6. Sprite
_init_(image [, agle] . image
[, ] [,] [, top] , .
[, ottom] [, left] [, right] angle, , , dx dy . top, ottom,
[, dx] [, dy] [, interval] left: right N.
[, is_collideable]) , -
. interval
1, is_collideable - True
get_image() -,
set_image{new_image) ew_image
get_height()
get_width()
get_angle()
set_angle{new_angle) new_angle
geLx()
set_x(new_x) new_x
get_y()
games 391
set_y(new_y) new_y
get_position() n
set__position , -
(new__position) new_position
get_top()
set_top(new_top) new_top
get_bottom()
set_ottom(new_bottom) new_ottom
get_left()
set_left(ew_left) new_left
get_right()
set_right( new_right) new_right
get_dx()
set_dx(new_dx) new_dx
get_dy()
set_dy(new_dy) new_dy
get_velocity()
set_velocity <0
(new_velocity) new_velocity
get_over1apping_sprites() ,
overlaps(other) True, other,
False . False,
is_collideae False
get_is_collideae() , . True ,
, False -
set_is_collideae new_status.
(new_status) True,
, False -
get_interval() tick()
set_interval tick()
(new_interval) new_interval
update() . ;
mainloop(). , Sprite,
tick() interval mainloop(). -
. , Sprite,
destroy()
t
Text -
Spri te. Text
. ,Text , Sprite. . .7
Text, . .8 - .
392 . livewires
n .7. Text
value ,
size
color . , -
color
8.8. Text
get_va/ue() ,
set_value(new_value) new_value
get_size()
set_size(new_size) new_size
get_color()
set_color(new_color) new_color .
, color
Message
Message - Text. Message ,
. Message
,
.
Message , Text.
Message after _death.
(, ),
. - None.
ssg init (): init (value. size. color [. angle]
[. ] [.][. top] [. bottom] [. left] [~right] [.dx] [. dy] [. lifetime] [. is
col l ideaeJ [. after_death]). .
value - , , size - , color - .
angle, ,, dx dy . top, bottom, left right
None. ,
.
1i fet i me -
games 393
mai nl () , .
, .
l i fetime , i s_col l ideab le - True. after_death
None.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
lifetime Message , ,
lifetime, interval.
Animation
Ani mat i on -
Ani mat i on
Spri te.
, . Ani mat i on
, Spri te
, . .9.
8.9. Animation
images -
n_repeats , ,
. ,
. -
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
repeat_iterval Animation , ,
repeat_interval, interval.
Mouse
Mouse . games. init()
mouse Mouse,
. ,
. Mouse . .1 ,
- . .11.
394 . livewires
6n .10. Mouse
~
position . (, )
is_visile , ,
. True - , False - . True
n .11. Mouse
get_x()
set_x(new_x) new_x
get_y()
set_y(new_y) new_y
get_positio()
set_position , -
(new_position) new_position
set_is_visie . new_viSibllity
(new_visibllity) True, , False -
is_pressed , . True,
(button_numer) button_umber , False
Keyboard
rd . games. i ni t ()
keyboard Keyboard, .
,
.
i s _pressed ( key),
True, , Fa l se -
. ,
games.
, . .15.
Music
Music ,
,
. ,
. :
, WAV, , OGG MIDI. Music
. .12.
games 395
.12. Music
load(filename) filename . -
,
fadeout(millisec) , millisec
stop()
games
games .
. .13.
.13. games
ilt([scree_width,] screen_width
[screen_height,] [fps]) screen_height, fps .
screen - games.Screen,
. mouse - . games.Mouse, -
r . kd - .
games.Keyoard, . ,
music, games.Music, -
load_image(filename -, filename.
[, trasparent]) transparet True ( ),
scale_lmage(image, -,
x_scale [, y_scale]) image, x_scale ,
y_scale . y_scale
, x_scale
.
.14. Sound
fadeout(millisec) , millisec
stop()
396 . livewires
games
l or ,
. . .15.
.15. games
nw
K_REURN Retum
K_PAUSE Pause
K_ESCAPE Esc
K_SPACE
K_EXCLAIM
K_QUOEDBL
.
!
K_HASH #
K_OOLLAR $
K_AMPERSAND
K_QUOE
.
&
K_LEFPAREN (
K_RIGHPAREN )
K_ASERISK *
K_PLUS +
_ 1
K_MINUS -
K_PERIOD
K_SLASH /
_
K_l 1
_2 2
_
_4 4
_s 5
_ 6
_7 7
_8 8
_9 9
K_COLON :
K_SEMICOLON ;
K_LESS <
K_EQUALS =
K_GREAER >
K_QUESION ?
_ @
K_LEFBRACKE [
K_ACKSLASH \
games 397
w
_RIGR ]
_R
K_UNDERSCORE -
_
_
d D
f F
K_g G
K_h
K_i 1
K_j J
k
KI L
Km
K_n N
_
_
q Q
r R
s s
t
K_u u
K_v v
K_w w
_
_
z z
DELEE Delete
Keypad 1 0
_l Keypad 1
_2 d 2
_ d 3
_4 d 4
5 d 5
Keypad 6
7 d 7
_8 d 8
_9 d 9
. - . .
398 . livewlres
n 8.15 ()
nw
__PERIOD d Period
__DIVIDE Keypad Divide
K_KP_MULIPLY d Multiply
K_KP_MINUS d Mius
K_KP_PLUS d Plus
K_KP_ENTER Keypad Enter
__EQUALS Keypad Equals
K_UP Up Arrow
K_DOWN Down Arrow
K_RIG Right Arrow
K_LEF Left Arrow
K_INSERT Insert
_ Home
K_END End
K_PAGEUP Page Up
K_PAGEDOWN Page Down
K_Fl Fl
K_F2 F2
_F F
K_F4 F4
K_FS FS
_F F
K_F7 F7
K_F8 F8
K_F9 F9
K_F10 F10
K_F11 F11
K_F12 F12
K_NUMLOCK Num Lock
K_CAPSLOCK Caps Lock
K_SCROLLOCK Scroll Lock
K_RSHIF Shift
K_LSIF Shift
K_RCRL tl
K_LCRL Ctrl
K_RALT Alt
K_LALT Alt
K_LSUPER Windows
K_RSUPER Windows
K_HELP Help
K_PRIN Print Screen
K_BREAK Break
color 399
color
col or , 11-r
:
red - ;
green - ;
1ue - ;
ack - ;
white - ;
da rk_red - ;
dark_green - -;
dark_ue - -;
dark_gray - -;
gray - ;
l ight_gray - -;
yel l ow - ;
brown - ;
pi nk - ;
purp l - .
colun, 293 50
comand, 291 49
computer_ve(), 184, 188 r 49
402
49 Music, 394
50 Screen, 389
48 Sprite, 390
event_grab, 313, 389 Text, 391
except, 210, 212 269, 311
Explosion, 377 396
388
F 395
G, 379
fadeout(), 395
False, 89 advance(), 381
flip_first_card(), 273 end(), 382
t1oat(), 68 _init_(), 379
fps, screen 313, 389 play(), 380
geon1etry(), 283
get_all_objects(), screen 389
G get_angle(), 390
G Over 2.0,
get_background(), screen 389
44
get_bottorn(), 391
Garne Over,
get_color(), 392
35
get_dx(), 391
print(), 36
37 get_dy(), 391
36 get_event_grab(), screen 389
38 get_fps(), sc.reen 389
37 get_height(), 390
38 get_image(), 390
39
get_interval(), 391
r 38
get_is_collideale(), 391
38
get_left(), 391
42
get_overlapping_sprites(), 391
41
get_position(), 391, 394
30
get_right(), 391
42
41
get_size(), 392
gaes.init(), 336
get_top(), 391
garnes.init(), 312 get_value(), 392
games.load_image(), 314 get_ velocity(), 391
games, get_width(), 389
Animation, 393 get_x(), 390, 394
Keyboard, 394 get_y(), 390, 394
Message, 392 get(), 155, 158, 295
s, 393 give_me_five(),y 171
403
give(), 251 ]
grid(), 285, 293
Java32
handle_caught(), 339
Keyboard, 389, 394
handle_collide(), 335
keyboard, 312
nd,
KeyError, 210
Card 252
keys(), 158
height, 313, 390
Hello World, 30
L
human_move(), 184, 188
left, 320, 390
legal_oves(), 184, 186
1 \ifetie, 325
IDLE35
livewires,
color, 399
print(), 36
gaes, 388
35
308, 388
38
load_iage(), 314
37
37 load_sound(), 395
load(), 395
39 load, 206
38 lose(), 272
38 lower(), 62, 63
images, 393
image, 320, 390
import, 265 mainloop(), 283, 306
IndexError, 210 ,
index(), 144 313
init(), 395 math, 364
input(), 280 _ VELOCIY, 384
insert(), 144, 296 Message, 312
instruction(), 168 325
interval, 390 388, 392
IOError, 210 324
is_busted(), BJ_Hand 271 Missile,
is_collideale, 320, 390 die(), 371
. is_hitting(), 272 _init_(), 367
is_pressed(), 346, 394 update(), 368, 371
is_visile, 333, 394 372
33
next_ock(), 215, 217
next_line(), 215
32
next_turn(), 184, 191 31
not. 96 33
n_repeats, 352, 393
Windows33
34
odds_change, 340 Python Tuto, 33
open_file(), 214
open(), 197 Q
or, 97 quit(), screen 313
overlapping_sprites, 320, 390
overlaps(), 391 R
randint(), 74, 101
99
UML ( 350
) 248
349
update_count(), 291
~ Animation 352
update_text(), 299
351
update(),
212
320, 391
upper(), 62, 63
37
v
387
W V, 353 231
wb205 229
231
wb+ 205
231
welcome(), 216
226
width, 313, 389
221
winner(), 184, 187
233
Wrapper, 374
die(), 375
239
update(), 374
238
writelines(),
202, 203
write(),
354
201, 203
353
z 355
50
ZeroDivisionError, 210 355
407
355 332
356 67
355
380 147
356
149
356
145
352
149
147
& 148
146
283, 285, 287 37
283 ,
tkinter 282 171
281 , 37
70
260 , 37, 55
255
259
258 72
11 178
91 182
break 93
continue 93
180
86
88
181
, r
182
88
177
178
78
180
101
86, 93
327
update() 329
Sprite 328
332 (GUI) 277
330
312
332 games 311
331 12
126 31
75 332
408
46
44
232
45
55
47
55
55
47
,
168
350
347
239
265
239
253
222
3
221
198
233
202
152
201
200
154
352, 353, 355, 357
in 154
152
46 287
176 285
101 286
, 37
174, 176
( fps) 312
41
204
, 115 30
r 175
, 111
color 399
games 396
172 117
232 159
172 378
167, 168, 169
, 106 224
225
225
if
50 77
409
77 55
79 Gid
78 grid(), 285
77 291
break 293
93 .'I
Entry 294
93 Text 295
continue 295
93
93 .'I
from 311 285
try 208, 212 284
285
149 284
125
144 235
233
129
235
126
223
104
221
126
258
in 128
223
123
124
125 263
128 262
129 74
265
and 96
261
not96
, 346
or97
93
, 65
298
260
, 178
261
258
62 259
126 258
410
252 113
253 , 78
252 37
, 115 , 144, 149
178 282
86 170
171
else 212 .~ - ~
211 156
208 157
212 157
try/except 208 65
209
303
290 300
280 301
291 200
291
- 57
() 162
57
258 56
32 56
262 57
246 - 108
249 214, 215, 295
50 210
in
49
128
137 69
111 125
154 46
49
228
109
in 111 47
len() 110 312
77 173
411
365
38 280
121
175 199
174 198
262, 27 4 315
112
()96
58
, 105
153
,
152
111
<1< - 156
, 99
156
,
152
57
158
Tkinter 281
-
,
280
318
281
255
280
256, 261
221, 223, 362
255
246
268
323
98
248
99
249
68
, 284 138
206 351
149 138
205 135
, 285 108
in 137
len() 137
137
Python 34 138
58 183
139
239
238 142
412
144
140
194
144
,
141
Text 322
142
color 321
320
347
Text 322
325
Python 36
319
74, 265
r 318
r 88
316
315
328
318
86
85
119
86
122
139
r 91
232
r 88
229
89
232
77
93
335
77
335
94
333
Python
Windows 34
42
201
115
53
67
200
41
202
62 201
52 197
47, 169
, 37 204
203
61 206
62 205
413
t'or
194 106
197 106
198 200
200
107
200
107
296 108
299 109
298 109
while
313 84
315
313 85
86
168 86
265
games 395
169
165
55
168
53
169
37
randint(), 7 4
randrange(), 75
169 random 74
183 72
206 55
345
, 150 346
36
55
221
67
147
355
125
356
125
200
126
, 102 139
414
140
126 290
291
291
Button () 280
289
Chcckbutton () 280
284
Entry ( ) 280
Frae () 279
Grid 293
Label () 279
Radiobutto () 280
Text ( ) 280
295 32
.
Python
.
. 11
.
. r
.
.
.
, 192!02, -, . (. r), 3, , n. 7.
- 005-93, 2; 95 3005 - .