本代码来源于 《python和pygame游戏开发指南》中的 star pusher 游戏,供大家参考,具体内容如下
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
|
# star pusher (a sokoban clone) # by al sweigart al@inventwithpython.com # http://inventwithpython.com/pygame # released under a "simplified bsd" license import random, sys, copy, os, pygame from pygame. locals import * fps = 30 # frames per second to update the screen winwidth = 800 # width of the program's window, in pixels winheight = 600 # height in pixels half_winwidth = int (winwidth / 2 ) half_winheight = int (winheight / 2 ) # the total width and height of each tile in pixels. tilewidth = 50 tileheight = 85 tilefloorheight = 40 cam_move_speed = 5 # how many pixels per frame the camera moves # the percentage of outdoor tiles that have additional # decoration on them, such as a tree or rock. outside_decoration_pct = 20 brightblue = ( 0 , 170 , 255 ) white = ( 255 , 255 , 255 ) bgcolor = brightblue textcolor = white up = 'up' down = 'down' left = 'left' right = 'right' def main(): global fpsclock, displaysurf, imagesdict, tilemapping, outsidedecomapping, basicfont, playerimages, currentimage # pygame initialization and basic set up of the global variables. pygame.init() fpsclock = pygame.time.clock() # because the surface object stored in displaysurf was returned # from the pygame.display.set_mode() function, this is the # surface object that is drawn to the actual computer screen # when pygame.display.update() is called. displaysurf = pygame.display.set_mode((winwidth, winheight)) pygame.display.set_caption( 'star pusher' ) basicfont = pygame.font.font( 'freesansbold.ttf' , 18 ) # a global dict value that will contain all the pygame # surface objects returned by pygame.image.load(). imagesdict = { 'uncovered goal' : pygame.image.load( 'redselector.png' ), 'covered goal' : pygame.image.load( 'selector.png' ), 'star' : pygame.image.load( 'star.png' ), 'corner' : pygame.image.load( 'wall_block_tall.png' ), 'wall' : pygame.image.load( 'wood_block_tall.png' ), 'inside floor' : pygame.image.load( 'plain_block.png' ), 'outside floor' : pygame.image.load( 'grass_block.png' ), 'title' : pygame.image.load( 'star_title.png' ), 'solved' : pygame.image.load( 'star_solved.png' ), 'princess' : pygame.image.load( 'princess.png' ), 'boy' : pygame.image.load( 'boy.png' ), 'catgirl' : pygame.image.load( 'catgirl.png' ), 'horngirl' : pygame.image.load( 'horngirl.png' ), 'pinkgirl' : pygame.image.load( 'pinkgirl.png' ), 'rock' : pygame.image.load( 'rock.png' ), 'short tree' : pygame.image.load( 'tree_short.png' ), 'tall tree' : pygame.image.load( 'tree_tall.png' ), 'ugly tree' : pygame.image.load( 'tree_ugly.png' )} # these dict values are global, and map the character that appears # in the level file to the surface object it represents. tilemapping = { 'x' : imagesdict[ 'corner' ], '#' : imagesdict[ 'wall' ], 'o' : imagesdict[ 'inside floor' ], ' ' : imagesdict[ 'outside floor' ]} outsidedecomapping = { '1' : imagesdict[ 'rock' ], '2' : imagesdict[ 'short tree' ], '3' : imagesdict[ 'tall tree' ], '4' : imagesdict[ 'ugly tree' ]} # playerimages is a list of all possible characters the player can be. # currentimage is the index of the player's current player image. currentimage = 0 playerimages = [imagesdict[ 'princess' ], imagesdict[ 'boy' ], imagesdict[ 'catgirl' ], imagesdict[ 'horngirl' ], imagesdict[ 'pinkgirl' ]] startscreen() # show the title screen until the user presses a key # read in the levels from the text file. see the readlevelsfile() for # details on the format of this file and how to make your own levels. levels = readlevelsfile( 'starpusherlevels.txt' ) currentlevelindex = 0 # the main game loop. this loop runs a single level, when the user # finishes that level, the next/previous level is loaded. while true: # main game loop # run the level to actually start playing the game: result = runlevel(levels, currentlevelindex) if result in ( 'solved' , 'next' ): # go to the next level. currentlevelindex + = 1 if currentlevelindex > = len (levels): # if there are no more levels, go back to the first one. currentlevelindex = 0 elif result = = 'back' : # go to the previous level. currentlevelindex - = 1 if currentlevelindex < 0 : # if there are no previous levels, go to the last one. currentlevelindex = len (levels) - 1 elif result = = 'reset' : pass # do nothing. loop re-calls runlevel() to reset the level def runlevel(levels, levelnum): global currentimage levelobj = levels[levelnum] mapobj = decoratemap(levelobj[ 'mapobj' ], levelobj[ 'startstate' ][ 'player' ]) gamestateobj = copy.deepcopy(levelobj[ 'startstate' ]) mapneedsredraw = true # set to true to call drawmap() levelsurf = basicfont.render( 'level %s of %s' % (levelnum + 1 , len (levels)), 1 , textcolor) levelrect = levelsurf.get_rect() levelrect.bottomleft = ( 20 , winheight - 35 ) mapwidth = len (mapobj) * tilewidth mapheight = ( len (mapobj[ 0 ]) - 1 ) * tilefloorheight + tileheight max_cam_x_pan = abs (half_winheight - int (mapheight / 2 )) + tilewidth max_cam_y_pan = abs (half_winwidth - int (mapwidth / 2 )) + tileheight leveliscomplete = false # track how much the camera has moved: cameraoffsetx = 0 cameraoffsety = 0 # track if the keys to move the camera are being held down: cameraup = false cameradown = false cameraleft = false cameraright = false while true: # main game loop # reset these variables: playermoveto = none keypressed = false for event in pygame.event.get(): # event handling loop if event. type = = quit: # player clicked the "x" at the corner of the window. terminate() elif event. type = = keydown: # handle key presses keypressed = true if event.key = = k_left: playermoveto = left elif event.key = = k_right: playermoveto = right elif event.key = = k_up: playermoveto = up elif event.key = = k_down: playermoveto = down # set the camera move mode. elif event.key = = k_a: cameraleft = true elif event.key = = k_d: cameraright = true elif event.key = = k_w: cameraup = true elif event.key = = k_s: cameradown = true elif event.key = = k_n: return 'next' elif event.key = = k_b: return 'back' elif event.key = = k_escape: terminate() # esc key quits. elif event.key = = k_backspace: return 'reset' # reset the level. elif event.key = = k_p: # change the player image to the next one. currentimage + = 1 if currentimage > = len (playerimages): # after the last player image, use the first one. currentimage = 0 mapneedsredraw = true elif event. type = = keyup: # unset the camera move mode. if event.key = = k_a: cameraleft = false elif event.key = = k_d: cameraright = false elif event.key = = k_w: cameraup = false elif event.key = = k_s: cameradown = false if playermoveto ! = none and not leveliscomplete: # if the player pushed a key to move, make the move # (if possible) and push any stars that are pushable. moved = makemove(mapobj, gamestateobj, playermoveto) if moved: # increment the step counter. gamestateobj[ 'stepcounter' ] + = 1 mapneedsredraw = true if islevelfinished(levelobj, gamestateobj): # level is solved, we should show the "solved!" image. leveliscomplete = true keypressed = false displaysurf.fill(bgcolor) if mapneedsredraw: mapsurf = drawmap(mapobj, gamestateobj, levelobj[ 'goals' ]) mapneedsredraw = false if cameraup and cameraoffsety < max_cam_x_pan: cameraoffsety + = cam_move_speed elif cameradown and cameraoffsety > - max_cam_x_pan: cameraoffsety - = cam_move_speed if cameraleft and cameraoffsetx < max_cam_y_pan: cameraoffsetx + = cam_move_speed elif cameraright and cameraoffsetx > - max_cam_y_pan: cameraoffsetx - = cam_move_speed # adjust mapsurf's rect object based on the camera offset. mapsurfrect = mapsurf.get_rect() mapsurfrect.center = (half_winwidth + cameraoffsetx, half_winheight + cameraoffsety) # draw mapsurf to the displaysurf surface object. displaysurf.blit(mapsurf, mapsurfrect) displaysurf.blit(levelsurf, levelrect) stepsurf = basicfont.render( 'steps: %s' % (gamestateobj[ 'stepcounter' ]), 1 , textcolor) steprect = stepsurf.get_rect() steprect.bottomleft = ( 20 , winheight - 10 ) displaysurf.blit(stepsurf, steprect) if leveliscomplete: # is solved, show the "solved!" image until the player # has pressed a key. solvedrect = imagesdict[ 'solved' ].get_rect() solvedrect.center = (half_winwidth, half_winheight) displaysurf.blit(imagesdict[ 'solved' ], solvedrect) if keypressed: return 'solved' pygame.display.update() # draw displaysurf to the screen. fpsclock.tick() def iswall(mapobj, x, y): """returns true if the (x, y) position on the map is a wall, otherwise return false.""" if x < 0 or x > = len (mapobj) or y < 0 or y > = len (mapobj[x]): return false # x and y aren't actually on the map. elif mapobj[x][y] in ( '#' , 'x' ): return true # wall is blocking return false def decoratemap(mapobj, startxy): """makes a copy of the given map object and modifies it. here is what is done to it: * walls that are corners are turned into corner pieces. * the outside/inside floor tile distinction is made. * tree/rock decorations are randomly added to the outside tiles. returns the decorated map object.""" startx, starty = startxy # syntactic sugar # copy the map object so we don't modify the original passed mapobjcopy = copy.deepcopy(mapobj) # remove the non-wall characters from the map data for x in range ( len (mapobjcopy)): for y in range ( len (mapobjcopy[ 0 ])): if mapobjcopy[x][y] in ( '$' , '.' , '@' , '+' , '*' ): mapobjcopy[x][y] = ' ' # flood fill to determine inside/outside floor tiles. floodfill(mapobjcopy, startx, starty, ' ' , 'o' ) # convert the adjoined walls into corner tiles. for x in range ( len (mapobjcopy)): for y in range ( len (mapobjcopy[ 0 ])): if mapobjcopy[x][y] = = '#' : if (iswall(mapobjcopy, x, y - 1 ) and iswall(mapobjcopy, x + 1 , y)) or \ (iswall(mapobjcopy, x + 1 , y) and iswall(mapobjcopy, x, y + 1 )) or \ (iswall(mapobjcopy, x, y + 1 ) and iswall(mapobjcopy, x - 1 , y)) or \ (iswall(mapobjcopy, x - 1 , y) and iswall(mapobjcopy, x, y - 1 )): mapobjcopy[x][y] = 'x' elif mapobjcopy[x][y] = = ' ' and random.randint( 0 , 99 ) < outside_decoration_pct: mapobjcopy[x][y] = random.choice( list (outsidedecomapping.keys())) return mapobjcopy def isblocked(mapobj, gamestateobj, x, y): """returns true if the (x, y) position on the map is blocked by a wall or star, otherwise return false.""" if iswall(mapobj, x, y): return true elif x < 0 or x > = len (mapobj) or y < 0 or y > = len (mapobj[x]): return true # x and y aren't actually on the map. elif (x, y) in gamestateobj[ 'stars' ]: return true # a star is blocking return false def makemove(mapobj, gamestateobj, playermoveto): """given a map and game state object, see if it is possible for the player to make the given move. if it is, then change the player's position (and the position of any pushed star). if not, do nothing. returns true if the player moved, otherwise false.""" # make sure the player can move in the direction they want. playerx, playery = gamestateobj[ 'player' ] # this variable is "syntactic sugar". typing "stars" is more # readable than typing "gamestateobj['stars']" in our code. stars = gamestateobj[ 'stars' ] # the code for handling each of the directions is so similar aside # from adding or subtracting 1 to the x/y coordinates. we can # simplify it by using the xoffset and yoffset variables. if playermoveto = = up: xoffset = 0 yoffset = - 1 elif playermoveto = = right: xoffset = 1 yoffset = 0 elif playermoveto = = down: xoffset = 0 yoffset = 1 elif playermoveto = = left: xoffset = - 1 yoffset = 0 # see if the player can move in that direction. if iswall(mapobj, playerx + xoffset, playery + yoffset): return false else : if (playerx + xoffset, playery + yoffset) in stars: # there is a star in the way, see if the player can push it. if not isblocked(mapobj, gamestateobj, playerx + (xoffset * 2 ), playery + (yoffset * 2 )): # move the star. ind = stars.index((playerx + xoffset, playery + yoffset)) stars[ind] = (stars[ind][ 0 ] + xoffset, stars[ind][ 1 ] + yoffset) else : return false # move the player upwards. gamestateobj[ 'player' ] = (playerx + xoffset, playery + yoffset) return true def startscreen(): """display the start screen (which has the title and instructions) until the player presses a key. returns none.""" # position the title image. titlerect = imagesdict[ 'title' ].get_rect() topcoord = 50 # topcoord tracks where to position the top of the text titlerect.top = topcoord titlerect.centerx = half_winwidth topcoord + = titlerect.height # unfortunately, pygame's font & text system only shows one line at # a time, so we can't use strings with \n newline characters in them. # so we will use a list with each line in it. instructiontext = [ 'push the stars over the marks.' , 'arrow keys to move, wasd for camera control, p to change character.' , 'backspace to reset level, esc to quit.' , 'n for next level, b to go back a level.' ] # start with drawing a blank color to the entire window: displaysurf.fill(bgcolor) # draw the title image to the window: displaysurf.blit(imagesdict[ 'title' ], titlerect) # position and draw the text. for i in range ( len (instructiontext)): instsurf = basicfont.render(instructiontext[i], 1 , textcolor) instrect = instsurf.get_rect() topcoord + = 10 # 10 pixels will go in between each line of text. instrect.top = topcoord instrect.centerx = half_winwidth topcoord + = instrect.height # adjust for the height of the line. displaysurf.blit(instsurf, instrect) while true: # main loop for the start screen. for event in pygame.event.get(): if event. type = = quit: terminate() elif event. type = = keydown: if event.key = = k_escape: terminate() return # user has pressed a key, so return. # display the displaysurf contents to the actual screen. pygame.display.update() fpsclock.tick() def readlevelsfile(filename): assert os.path.exists(filename), 'cannot find the level file: %s' % (filename) mapfile = open (filename, 'r' ) # each level must end with a blank line content = mapfile.readlines() + [ '\r\n' ] mapfile.close() levels = [] # will contain a list of level objects. levelnum = 0 maptextlines = [] # contains the lines for a single level's map. mapobj = [] # the map object made from the data in maptextlines for linenum in range ( len (content)): # process each line that was in the level file. line = content[linenum].rstrip( '\r\n' ) if ';' in line: # ignore the ; lines, they're comments in the level file. line = line[:line.find( ';' )] if line ! = '': # this line is part of the map. maptextlines.append(line) elif line = = '' and len (maptextlines) > 0 : # a blank line indicates the end of a level's map in the file. # convert the text in maptextlines into a level object. # find the longest row in the map. maxwidth = - 1 for i in range ( len (maptextlines)): if len (maptextlines[i]) > maxwidth: maxwidth = len (maptextlines[i]) # add spaces to the ends of the shorter rows. this # ensures the map will be rectangular. for i in range ( len (maptextlines)): maptextlines[i] + = ' ' * (maxwidth - len (maptextlines[i])) # convert maptextlines to a map object. for x in range ( len (maptextlines[ 0 ])): mapobj.append([]) for y in range ( len (maptextlines)): for x in range (maxwidth): mapobj[x].append(maptextlines[y][x]) # loop through the spaces in the map and find the @, ., and $ # characters for the starting game state. startx = none # the x and y for the player's starting position starty = none goals = [] # list of (x, y) tuples for each goal. stars = [] # list of (x, y) for each star's starting position. for x in range (maxwidth): for y in range ( len (mapobj[x])): if mapobj[x][y] in ( '@' , '+' ): # '@' is player, '+' is player & goal startx = x starty = y if mapobj[x][y] in ( '.' , '+' , '*' ): # '.' is goal, '*' is star & goal goals.append((x, y)) if mapobj[x][y] in ( '$' , '*' ): # '$' is star stars.append((x, y)) # basic level design sanity checks: assert startx ! = none and starty ! = none, 'level %s (around line %s) in %s is missing a "@" or "+" to mark the start point.' % (levelnum + 1 , linenum, filename) assert len (goals) > 0 , 'level %s (around line %s) in %s must have at least one goal.' % (levelnum + 1 , linenum, filename) assert len (stars) > = len (goals), 'level %s (around line %s) in %s is impossible to solve. it has %s goals but only %s stars.' % (levelnum + 1 , linenum, filename, len (goals), len (stars)) # create level object and starting game state object. gamestateobj = { 'player' : (startx, starty), 'stepcounter' : 0 , 'stars' : stars} levelobj = { 'width' : maxwidth, 'height' : len (mapobj), 'mapobj' : mapobj, 'goals' : goals, 'startstate' : gamestateobj} levels.append(levelobj) # reset the variables for reading the next map. maptextlines = [] mapobj = [] gamestateobj = {} levelnum + = 1 return levels def floodfill(mapobj, x, y, oldcharacter, newcharacter): """changes any values matching oldcharacter on the map object to newcharacter at the (x, y) position, and does the same for the positions to the left, right, down, and up of (x, y), recursively.""" # in this game, the flood fill algorithm creates the inside/outside # floor distinction. this is a "recursive" function. # for more info on the flood fill algorithm, see: # http://en.wikipedia.org/wiki/flood_fill if mapobj[x][y] = = oldcharacter: mapobj[x][y] = newcharacter if x < len (mapobj) - 1 and mapobj[x + 1 ][y] = = oldcharacter: floodfill(mapobj, x + 1 , y, oldcharacter, newcharacter) # call right if x > 0 and mapobj[x - 1 ][y] = = oldcharacter: floodfill(mapobj, x - 1 , y, oldcharacter, newcharacter) # call left if y < len (mapobj[x]) - 1 and mapobj[x][y + 1 ] = = oldcharacter: floodfill(mapobj, x, y + 1 , oldcharacter, newcharacter) # call down if y > 0 and mapobj[x][y - 1 ] = = oldcharacter: floodfill(mapobj, x, y - 1 , oldcharacter, newcharacter) # call up def drawmap(mapobj, gamestateobj, goals): """draws the map to a surface object, including the player and stars. this function does not call pygame.display.update(), nor does it draw the "level" and "steps" text in the corner.""" # mapsurf will be the single surface object that the tiles are drawn # on, so that it is easy to position the entire map on the displaysurf # surface object. first, the width and height must be calculated. mapsurfwidth = len (mapobj) * tilewidth mapsurfheight = ( len (mapobj[ 0 ]) - 1 ) * tilefloorheight + tileheight mapsurf = pygame.surface((mapsurfwidth, mapsurfheight)) mapsurf.fill(bgcolor) # start with a blank color on the surface. # draw the tile sprites onto this surface. for x in range ( len (mapobj)): for y in range ( len (mapobj[x])): spacerect = pygame.rect((x * tilewidth, y * tilefloorheight, tilewidth, tileheight)) if mapobj[x][y] in tilemapping: basetile = tilemapping[mapobj[x][y]] elif mapobj[x][y] in outsidedecomapping: basetile = tilemapping[ ' ' ] # first draw the base ground/wall tile. mapsurf.blit(basetile, spacerect) if mapobj[x][y] in outsidedecomapping: # draw any tree/rock decorations that are on this tile. mapsurf.blit(outsidedecomapping[mapobj[x][y]], spacerect) elif (x, y) in gamestateobj[ 'stars' ]: if (x, y) in goals: # a goal and star are on this space, draw goal first. mapsurf.blit(imagesdict[ 'covered goal' ], spacerect) # then draw the star sprite. mapsurf.blit(imagesdict[ 'star' ], spacerect) elif (x, y) in goals: # draw a goal without a star on it. mapsurf.blit(imagesdict[ 'uncovered goal' ], spacerect) # last draw the player on the board. if (x, y) = = gamestateobj[ 'player' ]: # note: the value "currentimage" refers # to a key in "playerimages" which has the # specific player image we want to show. mapsurf.blit(playerimages[currentimage], spacerect) return mapsurf def islevelfinished(levelobj, gamestateobj): """returns true if all the goals have stars in them.""" for goal in levelobj[ 'goals' ]: if goal not in gamestateobj[ 'stars' ]: # found a space with a goal but no star on it. return false return true def terminate(): pygame.quit() sys.exit() if __name__ = = '__main__' : main() |
配套资源下载
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/Ibelievesunshine/article/details/83546789