Welcome, guest | Sign In | My Account | Store | Cart

Part of a tutorial of programming Load Runner in Python, this code shows the evolution to creating a simple game in the language that should be able to run on Windows. The original code was supposed to run on Linux, but this recipe takes the idea in another direction and shows that programs can be created incrementally. Please note the various file divisions: load1, load2, load3, load4, load5, and Extended Demo (Sound).

Python, 610 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
##########
# load1.py
##########

import boards
import util
import time

def main():
    screen = util.Screen(boards.boards[0])
    screen.update()
    time.sleep(2)
    row, col = 1, 9
    while True:
        character = screen.read(row, col)
        if character == '_' or character == '*':
            col += 1
        elif character == '|':
            row -= 1
        elif character == ' ':
            if screen.read(row + 1, col) == '|':
                col += 1
            else:
                row += 1
        else:
            break
        screen.write(row, col, '^')
        screen.update()
        time.sleep(.1)
    screen.update()
    time.sleep(2)

if __name__ == '__main__':
    main()

##########
# load2.py
##########

import boards
import util
import time
import ttyWindows

################################################################################

class Player:

    def __init__(self, screen, row=0, column=9, face='^'):
        self.screen = screen
        self.row = row
        self.column = column
        self.face = face[0]
        self.direction = 0, 0

    def setDirection(self, key):
        if key == '\xE0H':
            self.direction = 0, -1
        elif key == '\xE0P':
            self.direction = 0, +1
        elif key == '\xE0K':
            self.direction = -1, 0
        elif key == '\xE0M':
            self.direction = +1, 0

    def move(self):
        character = self.screen.read(self.row, self.column)
        x, y = self.direction
        if character == '_' or character == '*':
            self.column += x
        elif character == '|':
            self.row += y
        elif character == ' ':
            if self.screen.read(self.row + 1, self.column) != '|' or y == 1:
                self.row += 1
            else:
                self.column += x
        self.screen.write(self.row, self.column, self.face)

################################################################################

def main():
    screen = util.Screen(boards.boards[0])
    screen.update()
    player = Player(screen)
    while screen.read(player.row, player.column):
        time.sleep(.1)
        key = ttyWindows.readLookAhead()
        player.setDirection(key)
        player.move()
        screen.update()
    time.sleep(2)

if __name__ == '__main__':
    main()

##########
# load3.py
##########

import boards
import util
import time
import ttyWindows

################################################################################

class Player:

    def __init__(self, screen, face, row=1, column=10):
        self.screen = screen
        self.face = face
        self.row = row
        self.column = column
        self.vector = 0, 0

    def move(self):
        global playing, you
        string = self.screen.read(self.row, self.column)
        left = self.screen.read(self.row, self.column - 1)
        right = self.screen.read(self.row, self.column + 1)
        x, y = self.vector
        x_move = False
        if string == '_':
            self.column += x
            x_move = True
        elif string == '|':
            self.row += y
        elif string == ' ':
            if self.screen.read(self.row + 1, self.column) != '|' or y == 1:
                self.row += 1
            else:
                self.column += x
        if not x_move:
            if left == '_' and x == -1:
                self.column -= 1
            elif right == '_' and x == 1:
                self.column += 1
        self.screen.write(self.row, self.column, self.face)
        if self is you and self.screen.read(self.row, self.column) is None:
            playing = False

################################################################################

class You(Player):

    def setDirection(self, key):
        if key == '\xE0H':
            self.vector = 0, -1
        elif key == '\xE0P':
            self.vector = 0, +1
        elif key == '\xE0K':
            self.vector = -1, 0
        elif key == '\xE0M':
            self.vector = +1, 0

class Robot(Player):

    def setDirection(self, key):
        global playing, you
        if you.row == self.row and you.column == self.column:
            playing = False
        if self.row == you.row:
            if self.column > you.column:
                self.vector = -1, 0
            else:
                self.vector = +1, 0
        else:
            context = self.screen.read(self.row, self.column)
            if context == '|':
                if self.row > you.row:
                    self.vector = 0, -1
                elif self.row < you.row:
                    self.vector = 0, +1

################################################################################

def main():
    global playing, you
    screen = util.Screen(boards.boards[0])
    you = You(screen, '^')
    screen.update()
    players = [you]
    clock = 0
    playing = True
    time.sleep(2)
    while playing:
        clock += 1
        if clock == 40:
            players.append(Robot(screen, '&'))
        time.sleep(.1)
        key = ttyWindows.readLookAhead()
        for player in players:
            player.setDirection(key)
            player.move()
        screen.update()
    screen.update()
    time.sleep(2)

if __name__ == '__main__':
    main()

##########
# load4.py
##########

import boards
import util
import time
import ttyWindows

################################################################################

class Player:

    def __init__(self, screen, face, row=1, column=10):
        self.screen = screen
        self.face = face
        self.row = row
        self.column = column
        self.vector = 0, 0

    def move(self):
        global playing, you
        context = self.screen.read(self.row, self.column)
        left = self.screen.read(self.row, self.column - 1)
        right = self.screen.read(self.row, self.column + 1)
        x, y = self.vector
        x_move = False
        if context == '_':
            self.column += x
            x_move = True
        elif context == '|':
            self.row += y
        elif context == ' ':
            if self.screen.read(self.row + 1, self.column) != '|' or y == 1:
                self.row += 1
            else:
                self.column += x
        if not x_move and context != ' ':
            if left == '_' and x == -1:
                self.column -= 1
            elif right == '_' and x == 1:
                self.column += 1
        self.screen.write(self.row, self.column, self.face)
        if self is you and self.screen.read(self.row, self.column) is None:
            playing = False

################################################################################

class You(Player):

    def __init__(self, screen, face, row=1, column=10):
        Player.__init__(self, screen, face, row, column)
        self.score = 0

    def setDirection(self, key):
        context = self.screen.read(self.row, self.column)
        if context == '*':
            self.score += 10
            self.screen.cache_write(self.row, self.column, '_')
        if key == '\xE0H':
            self.vector = 0, -1
        elif key == '\xE0P':
            self.vector = 0, +1
        elif key == '\xE0K':
            self.vector = -1, 0
        elif key == '\xE0M':
            self.vector = +1, 0
        elif key == 'a':
            self.screen.cache_write(self.row, self.column - 1, ' ')
        elif key == 'd':
            self.screen.cache_write(self.row, self.column + 1, ' ')

class Robot(Player):

    def setDirection(self, key):
        global playing, you
        if you.row == self.row and you.column == self.column:
            playing = False
        if self.row == you.row:
            if self.column > you.column:
                self.vector = -1, 0
            else:
                self.vector = +1, 0
        else:
            context = self.screen.read(self.row, self.column)
            if context == '|':
                if self.row > you.row:
                    self.vector = 0, -1
                elif self.row < you.row:
                    self.vector = 0, +1

################################################################################

def main():
    global playing, you
    screen = util.Screen2(boards.boards[0])
    you = You(screen, '^')
    screen.update()
    players = [you]
    clock = 0
    playing = True
    time.sleep(2)
    while playing:
        clock += 1
        if clock == 90:
            players.append(Robot(screen, '&'))
        time.sleep(.1)
        key = ttyWindows.readLookAhead()
        for player in players:
            player.setDirection(key)
            player.move()
        screen.update()
        print 'Score: %s' % you.score
    screen.update()
    print 'Score: %s' % you.score
    time.sleep(2)

if __name__ == '__main__':
    main()

##########
# load5.py
##########

import boards
import random
import time
import ttyWindows
import util

################################################################################

class Player:

    def __init__(self, screen, face, row=1, column=10):
        self.screen = screen
        self.face = face
        self.row = row
        self.column = column
        self.vector = 0, 0

    def move(self):
        global playing, you, players
        context = self.screen.read(self.row, self.column)
        left = self.screen.read(self.row, self.column - 1)
        right = self.screen.read(self.row, self.column + 1)
        x, y = self.vector
        x_move = False
        if context == '_':
            self.column += x
            x_move = True
        elif context == '|':
            self.row += y
        elif context == ' ':
            if self.screen.read(self.row + 1, self.column) != '|' or y == 1:
                self.row += 1
            else:
                self.column += x
        if not x_move and context != ' ':
            if left == '_' and x == -1:
                self.column -= 1
            elif right == '_' and x == 1:
                self.column += 1
        self.screen.write(self.row, self.column, self.face)
        if self.screen.read(self.row, self.column) is None:
            if self is you:
                playing = False
            else:
                players.remove(self)

################################################################################

class You(Player):

    def __init__(self, screen, face, row=1, column=10):
        Player.__init__(self, screen, face, row, column)
        self.score = 0

    def setDirection(self, key):
        context = self.screen.read(self.row, self.column)
        if context == '*':
            self.score += 10
            self.screen.cache_write(self.row, self.column, '_')
        if key == '\xE0H':
            self.vector = 0, -1
        elif key == '\xE0P':
            self.vector = 0, +1
        elif key == '\xE0K':
            self.vector = -1, 0
        elif key == '\xE0M':
            self.vector = +1, 0
        elif key == 'a':
            self.screen.cache_write(self.row, self.column - 1, ' ')
        elif key == 'd':
            self.screen.cache_write(self.row, self.column + 1, ' ')

class Robot(Player):

    def __init__(self, screen, face, row=1, column=10):
        Player.__init__(self, screen, face, row, column)
        self.move_count = 0

    def move(self):
        if self.screen.read(self.row, self.column) == ' ':
            Player.move(self)
        else:
            self.move_count += 1
            if self.move_count % 2:
                Player.move(self)
            else:
                self.screen.write(self.row, self.column, self.face)

    def setDirection(self, key):
        global playing, you
        if you.row == self.row and you.column == self.column:
            playing = False
        if self.column > you.column:
            self.vector = -1, 0
        elif self.column < you.column:
            self.vector = +1, 0
        if self.row != you.row:
            context = self.screen.read(self.row, self.column)
            if context == '|':
                if self.row > you.row:
                    self.vector = 0, -1
                elif self.row < you.row:
                    self.vector = 0, +1

################################################################################

SELECT = 1

def main():
    global playing, you, players
    screen = util.Screen2(boards.boards[SELECT])
    you = You(screen, '^')
    screen.update()
    players = [you]
    clock = 0
    playing = True
    time.sleep(2)
    while playing:
        clock += 1
        if clock > 40 and len(players) < 3:
            players.append(Robot(screen, '&', column=random.randrange(len(boards.boards[SELECT].board().splitlines()[1]))))
        time.sleep(.1)
        key = ttyWindows.readLookAhead()
        for player in players:
            player.setDirection(key)
            player.move()
        screen.update()
        print 'Score: %s' % you.score
    screen.update()
    print 'Score: %s' % you.score
    time.sleep(2)

if __name__ == '__main__':
    main()

##########################
# Extended Demo (Sound).py
##########################

import boards
import random
import time
import ttyWindows
import util
import winsound

################################################################################

class Player:

    def __init__(self, screen, face, row=1, column=10):
        self.screen = screen
        self.face = face
        self.row = row
        self.column = column
        self.vector = 0, 0

    def move(self):
        global playing, you, players
        context = self.screen.read(self.row, self.column)
        left = self.screen.read(self.row, self.column - 1)
        right = self.screen.read(self.row, self.column + 1)
        x, y = self.vector
        x_move = False
        if context == '_':
            self.column += x
            x_move = True
        elif context == '|':
            self.row += y
        elif context == ' ':
            if self.screen.read(self.row + 1, self.column) != '|' or y == 1:
                self.row += 1
            else:
                self.column += x
        if not x_move and context != ' ':
            if left == '_' and x == -1:
                self.column -= 1
            elif right == '_' and x == 1:
                self.column += 1
        self.screen.write(self.row, self.column, self.face)
        if self.screen.read(self.row, self.column) is None:
            if self is you:
                playing = False
            else:
                players.remove(self)
                winsound.Beep(400, 25)
                winsound.Beep(500, 25)

################################################################################

class You(Player):

    def __init__(self, screen, face, row=1, column=10):
        Player.__init__(self, screen, face, row, column)
        self.score = 0

    def setDirection(self, key):
        context = self.screen.read(self.row, self.column)
        if context == '*':
            self.score += 10
            self.screen.cache_write(self.row, self.column, '_')
            winsound.Beep(300, 50)
        if key == '\xE0H':
            self.vector = 0, -1
        elif key == '\xE0P':
            self.vector = 0, +1
        elif key == '\xE0K':
            self.vector = -1, 0
        elif key == '\xE0M':
            self.vector = +1, 0
        elif key == 'a':
            self.screen.cache_write(self.row, self.column - 1, ' ')
        elif key == 'd':
            self.screen.cache_write(self.row, self.column + 1, ' ')

class Robot(Player):

    def __init__(self, screen, face, row=1, column=10):
        Player.__init__(self, screen, face, row, column)
        self.move_count = 0

    def move(self):
        if self.screen.read(self.row, self.column) == ' ':
            Player.move(self)
        else:
            self.move_count += 1
            if self.move_count % 2:
                Player.move(self)
            else:
                self.screen.write(self.row, self.column, self.face)

    def setDirection(self, key):
        global playing, you
        if you.row == self.row and you.column == self.column:
            playing = False
        if self.column > you.column:
            self.vector = -1, 0
        elif self.column < you.column:
            self.vector = +1, 0
        if self.row != you.row:
            context = self.screen.read(self.row, self.column)
            if context == '|':
                if self.row > you.row:
                    self.vector = 0, -1
                elif self.row < you.row:
                    self.vector = 0, +1

################################################################################

SELECT = 1
ROBOTS = 3

def main():
    global playing, you, players
    screen = util.Screen2(boards.boards[SELECT])
    you = You(screen, '^')
    screen.update()
    players = [you]
    clock = 0
    playing = True
    time.sleep(2)
    note = False
    while playing:
        clock += 1
        if clock > 40 and len(players) - 1 < ROBOTS:
            players.append(Robot(screen, '&', column=random.randrange(len(boards.boards[SELECT].board().splitlines()[1]))))
        time.sleep(0.1)
        key = ttyWindows.readLookAhead()
        for player in players:
            player.setDirection(key)
            player.move()
        screen.update()
        print 'Score: %s' % you.score
        winsound.Beep(100 + 100 * note, 25)
        note = not note
    screen.update()
    print 'Score: %s' % you.score
    for x in range(4):
        time.sleep(0.1)
        winsound.Beep(700 - 100 * x, 25)
    time.sleep(2)

if __name__ == '__main__':
    main()

The following files are also required for running the code up above.

boards.py

class Board:

    TABLE = ''.join([chr(i) for i in range(256)])
    NAME = ''.join([chr(i) for i in range(256) if len(repr(chr(i))) == 3 or i == ord('\\')])
    BOARD = '\n *_|'

    def __init__(self, name, board):
        self.__name = name
        self.__board = board
        self.__check()

    def name(self):
        return self.__name

    def board(self):
        return self.__board

    def __check(self):
        name_error = self.__name.translate(self.TABLE, self.NAME)
        board_error = self.__board.translate(self.TABLE, self.BOARD)
        assert self.__name and not name_error
        assert self.__board and not board_error
        self.__logic()

    def __logic(self):
        board = self.__board.splitlines()
        assert not board[0]
        columns = len(board[1])
        assert columns
        for row in board[2:]:
            assert len(row) == columns

################################################################################

first_try = Board('First Try', '''



                                __*___|_             
                          |           |              
                          |           |              
                         _|__*________|______*___    
                          |           |              
                  ___*____|___________|_             
                          |           |              
                          |           |              
                          |           |              
    ____*_________________|___________|______*____   ''')

################################################################################

second_try = Board('Second Try', '''



                                __*___|_             
    _|________*_____|_*___|___        |              
     |     |        |     |           |              
    _|_*_  |   __*__|_   _|__*________|______*_|_    
           |              |           |        |     
           |      ___*____|________|__|_   _*__|_    
           |              |        |  |              
           |     _|__*_   |   __*__|_ |              
           |      |       |           |              
    ____*__|______|_______|___________|______*____   ''')

################################################################################

boards = first_try, second_try

ttyWindows.py

import msvcrt

def readLookAhead():
    string = str()
    while msvcrt.kbhit():
        string += msvcrt.getch()
    return string

util.py

import os

################################################################################

class Screen:

    def __init__(self, board):
        self.__cache = [tuple(row) for row in board.board().splitlines()[1:]]
        self.__board()

    def write(self, row, column, character):
        try:
            self.__temp[row][column] = character[0]
        except:
            pass

    def read(self, row, column):
        try:
            return self.__temp[row][column]
        except:
            pass

    def update(self):
        self.__clear()
        self.__print()
        self.__board()

    def __clear(self):
        if os.name == 'nt':
            os.system('cls')
        elif os.name == 'posix' or os.name == 'mac':
            os.system('clear')
        else:
            raise OSError, 'not supported'

    def __print(self):
        print '\n'.join([''.join(row) for row in self.__temp])

    def __board(self):
        self.__temp = [list(row) for row in self.__cache]

################################################################################

class Screen2:

    def __init__(self, board):
        self.__cache = [list(row) for row in board.board().splitlines()[1:]]
        self.__board()

    def cache_write(self, row, column, character):
        try:
            self.__cache[row][column] = character[0]
            self.write(row, column, character)
        except:
            pass

    def write(self, row, column, character):
        try:
            self.__temp[row][column] = character[0]
        except:
            pass

    def read(self, row, column):
        try:
            return self.__temp[row][column]
        except:
            pass

    def update(self):
        self.__clear()
        self.__print()
        self.__board()

    def __clear(self):
        if os.name == 'nt':
            os.system('cls')
        elif os.name == 'posix' or os.name == 'mac':
            os.system('clear')
        else:
            raise OSError, 'not supported'

    def __print(self):
        print '\n'.join([''.join(row) for row in self.__temp])

    def __board(self):
        self.__temp = [list(row) for row in self.__cache]
Created by Stephen Chappell on Fri, 7 Dec 2012 (MIT)
Python recipes (4591)
Stephen Chappell's recipes (233)

Required Modules

  • (none specified)

Other Information and Tasks