Make Games with Python & Pygame (4)

本文介绍了如何使用Python的Pygame库制作贪吃蛇游戏,详细阐述了游戏的程序设计思路,包括初始化、游戏循环、蛇与苹果的状态管理、碰撞检测等关键部分。同时,强调了Python字典数据结构在简化程序中的作用,以及旋转图像可能带来的问题。此外,还提到了Sublime Text 2这款文本编辑器。
摘要由CSDN通过智能技术生成

从现在开始,就是具体游戏的制作了。作者是每章一个游戏,有些游戏我不是很感兴趣,只对其中有兴趣,所以就只讲这一些。

第一个游戏就是贪吃蛇游戏,说起这个游戏,这可能是我玩的最早的游戏之一了,记得那时彩屏手机没有出来时,所有单色手机上面几乎都有这个游戏,简直风靡一时啊。以前在单片机的液晶屏上实现过贪吃蛇,不过太简陋了。

看完讲贪吃蛇游戏这章,越来越感觉到python有意思了,字典这个数据结构的应用让整个程序一下子简单了很多。而且作者写的很仔细,整个程序设计的思路通过代码就能一目了然,关于旋转图像的坏处也有说明。而且在这章最后关于变量是否要复用这点也给了看法,很好很强大。每段代码为什么这样写,也解释的很清楚。而且它的代码风格值得我学习。

下面是贪吃蛇程序的代码,把代码敲一遍加深理解。

import pygame, sys, random
from pygame.locals import*

FPS = 15
WINDOWWIDTH =640
WINDOWHEIGHT = 480
CELLSIZE = 20
assert WINDOWWIDTH % CELLSIZE == 0, "Window width must be a multiple of cell size"
assert WINDOWHEIGHT % CELLSIZE == 0, "Window height muset be multiple of cell size"
CELLWIDTH = WINDOWWIDTH / CELLSIZE
CELLHEIGHT = WINDOWHEIGHT / CELLSIZE

#RGB
WHITE = (255, 255, 255)
BLACK = (0, 0 , 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
DARKGREEN = (0, 155, 0)
DARKGRAY = (40, 40, 40)
BGCOLOR = BLACK

UP = 'up'
DOWN = 'down'
LEFT = 'left'
RIGHT = 'right'

HEAD = 0 #很巧妙的运用

#main function
def main():
	global FPSCLOCK, DISPLAYSURF, BASICFONT
	
	pygame.init()
	FPSCLOCK = pygame.time.Clock()
	DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
	BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
	pygame.display.set_caption('Wormy')
	
	showStartScreen()  #显示起始画面
	while True:
		runGame()	#运行游戏主体
		showGameOverScreen()	#显示游戏结束画面
	
def runGame():
	#设置蛇身开始在随机位置
	startx = random.randint(5, CELLWIDTH-6)
	starty = random.randint(5, CELLHEIGHT-6)
	wormCoods = [{'x': startx, 'y': starty},
				 {'x': startx-1, 'y': starty},
				 {'x': startx-2, 'y': starty}]
	direction = RIGHT	#蛇初始方向向右
	
	#得到一个随机苹果的位置
	apple = getRandomLocation()

	while True:
		for event in pygame.event.get():
			if event.type == QUIT:
				terminate()
			elif event.type == KEYDOWN:		#处理蛇的移动方向
				if (event.key == K_LEFT or event.key == K_a) and direction != RIGHT:
					direction = LEFT
				elif (event.key == K_RIGHT or event.key == K_d) and direction != LEFT:
					direction = RIGHT
				elif (event.key == K_UP or event.key == K_w) and direction != DOWN:
					direction = UP
				elif (event.key == K_DOWN or event.key == K_s) and direction != UP:
					direction = DOWN
				elif event.key == K_ESCAPE:
					terminate()
		#看蛇身是否撞击到自己或四周墙壁
		if wormCoods[HEAD]['x'] == -1 or wormCoods[HEAD]['x'] == CELLWIDTH or wormCoods[HEAD]['y'] == -1 or wormCoods[HEAD]['y'] == CELLHEIGHT:
			return #game over
		for wormBody in wormCoods[1:]:
			if wormBody['x'] == wormCoods[HEAD]['x'] and wormBody['y'] == wormCoods[HEAD]['y']:
				return #game over
		#蛇是否迟到苹果
		if wormCoods[HEAD]['x'] == apple['x'] and wormCoods[HEAD]['y'] == apple['y']:
			#不删除蛇身尾段
			apple = getRandomLocation() #设置一个新的苹果
		else:
			del wormCoods[-1] #删除蛇身尾段
		#添加蛇身头段
		if direction == UP:
			newHead = {'x': wormCoods[HEAD]['x'], 'y': wormCoods[HEAD]['y']-1}
		elif direction == DOWN:
			newHead = {'x': wormCoods[HEAD]['x'], 'y': wormCoods[HEAD]['y']+1}
		elif direction == LEFT:
			newHead = {'x': wormCoods[HEAD]['x']-1, 'y': wormCoods[HEAD]['y']}
		elif direction == RIGHT:
			newHead = {'x': wormCoods[HEAD]['x']+1, 'y': wormCoods[HEAD]['y']}
		wormCoods.insert(0,newHead)
		DISPLAYSURF.fill(BGCOLOR)
		drawGrid() #画格子
		drawWorm(wormCoods) #画蛇身
		drawApple(apple) #画苹果
		drawScore(len(wormCoods) - 3)#显示得到分数
		pygame.display.update()
		FPSCLOCK.tick(FPS)
		
#提示按键消息		
def drawPressKeyMsg():
	pressKeySurf = BASICFONT.render('Press a key to play.', True, DARKGRAY)
	pressKeyRect = pressKeySurf.get_rect()
	pressKeyRect.topleft = (WINDOWWIDTH - 200, WINDOWHEIGHT-30)
	DISPLAYSURF.blit(pressKeySurf, pressKeyRect)

#检测按键	
def checkForKeyPress():
	if len(pygame.event.get(QUIT)) > 0:
		terminate()
	keyUpEvents = pygame.event.get(KEYUP)
	if len(keyUpEvents) == 0:
		return None
	if keyUpEvents[0].key == K_ESCAPE:
		terminate()
	return keyUpEvents[0].key

#显示开始界面
def showStartScreen():
        titleFont = pygame.font.Font('freesansbold.ttf', 100)
        titleSurf1 = titleFont.render('Wormy!', True, WHITE, DARKGREEN)
        titleSurf2 = titleFont.render('Wormy!', True, GREEN)

        degrees1 = 0
        degrees2 = 0
        while True:
                DISPLAYSURF.fill(BGCOLOR)
                rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
                rotatedRect1 = rotatedSurf1.get_rect()
                rotatedRect1.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
                DISPLAYSURF.blit(rotatedSurf1,rotatedRect1)

                rotatedSurf2 = pygame.transform.rotate(titleSurf2, degrees2)
                rotatedRect2 = rotatedSurf2.get_rect()
                rotatedRect2.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
                DISPLAYSURF.blit(rotatedSurf2,rotatedRect2)		

                drawPressKeyMsg()

                if checkForKeyPress():
                                                pygame.event.get()
                                                return
                pygame.display.update()
                FPSCLOCK.tick(FPS)
                degrees1 += 3
                degrees2 += 7

#游戏结束
def terminate():
	pygame.quit()
	sys.exit()

#得到随机苹果位置
def getRandomLocation():
	return  {'x': random.randint(0, CELLWIDTH - 1), 'y': random.randint(0, CELLHEIGHT - 1)}

#显示游戏结束画面
def showGameOverScreen():
	gameOverFont = pygame.font.Font('freesansbold.ttf', 150)
	gameSurf = gameOverFont.render('GAME', True, WHITE)
	overSurf = gameOverFont.render('OVER', True, WHITE)
	gameRect = gameSurf.get_rect()
	overRect = overSurf.get_rect()
	gameRect.midtop = (WINDOWWIDTH / 2, 10)
	overRect.midtop = (WINDOWWIDTH / 2, gameRect.height + 10 + 25)

	DISPLAYSURF.blit(gameSurf, gameRect)
	DISPLAYSURF.blit(overSurf, overRect)
	drawPressKeyMsg()
	pygame.display.update()
	pygame.time.wait(500)
	checkForKeyPress()

	while True:
		if checkForKeyPress():
			pygame.event.get()
			return

def drawScore(score):
	scoreSurf = BASICFONT.render('Score: %s' %(score), True, WHITE)
	scoreRect = scoreSurf.get_rect()
	scoreRect.topleft = (WINDOWWIDTH - 120, 10)
	DISPLAYSURF.blit(scoreSurf, scoreRect)

def drawWorm(wormCoods):
	for coord in wormCoods:
		x = coord['x'] * CELLSIZE
		y = coord['y'] * CELLSIZE
		wormSegmentRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
		pygame.draw.rect(DISPLAYSURF, DARKGREEN, wormSegmentRect)
		wormInnerSegmentRect = pygame.Rect(x+4, y+4, CELLSIZE-8, CELLSIZE-8)
		pygame.draw.rect(DISPLAYSURF, GREEN, wormInnerSegmentRect)

def drawApple(coord):
	x = coord['x'] * CELLSIZE
	y = coord['y'] * CELLSIZE
	appleRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
	pygame.draw.rect(DISPLAYSURF, RED, appleRect)

def drawGrid():
	for x in range(0, WINDOWWIDTH, CELLSIZE):
		pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, WINDOWHEIGHT))
	for y in range(0, WINDOWHEIGHT, CELLSIZE):
		pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (WINDOWWIDTH, y))

if __name__ == '__main__':
	main()

		
		

然后就来说说上面的这段代码。先说明下整个程序流程

一个main()函数里面就是这个程序的大概流程,首先相关pygame的初始化,显示游戏启动画面,接着进入死循环,runGame()就是游戏主体部分了,是程序核心。而如果游戏失败,就会只执行显示结束画面showGameOverScreen(),然后再次进行游戏。

先看看程序开始初始化的部分有哪些东西。

我们把蛇身看成是一段一段组成的,CELLSIZE这个常量就是蛇身每段的大小。我们要确保蛇身与整个显示屏幕的大小是成整数倍的关系,不然显示就有问题,所以在开始加了异常处理。assert 语句检测我们给定的屏幕大小是否与蛇身段大小成整数倍。

我们可以通过蛇身来与屏幕具体像素联系起来,简化编程,所以有了CELLWIDTH 和 CELLHEIGHT两个变量。然后我们把定义我们游戏会用到的颜色和把方向也定义成大写的变量,这样增强代码可读性。最后有个HEAD这个变量是在后面很有用的。下面会介绍。

main()函数开始的一部分代码含义

首先我们定义了三个全局变量,因为它们会在其它的一些函数中出现。分别是帧率,游戏显示窗口,基本字体,用global关键字修饰。

然后Pygame进行初始化,设置一些数据,比如帧率,加载基本字体,设置窗口标题,窗口大小。

然后显示游戏启动画面,接着进入游戏循环体,运行游戏。游戏启动画面放在后面说,先说循环体里面的东西。

看看runGame()这个游戏核心部分是怎么实现的。

首先蛇刚开始出来时因显示在屏幕的随机的一个位置,所以我们需要产生随机数,产生随机数要在程序开始出加载python的random模块。为了防止蛇身一出来就离墙太近,导致游戏失败,所以我们的蛇身会离墙有一段距离。产生的随机数范围为(5,CELLWIDTH-6)。然后我们用字典这种数据结构将坐标存放起来(字典真是好用),因为开始蛇身只有三段,所以有3个字典元素。用列表把这三个字典元素包容在一起。蛇的初始方向设为像右。

设置完蛇身的初始状态,我们就要设置初始苹果的状态,getRandomLocation()函数产生一个随机位置用于放置苹果。蛇的头部元素是wormCoords[0],为了代码可读性,因为后面对蛇身头部的操作比较多,所以我们用wormCoods[HEAD]代替wormCoods[0]。这就是为什么前面开始我们要设置一个HEAD全局变量的原因了。

接着是游戏循环了,所以跟游戏相关的关键操作都在这里面了,比如显示,按键交互等。循环体中主要处理按键消息,for event in pygame.event.get()得到所有的消息,然后对消息进行判断处理,如果是消息是退出,则终止游戏。接着处理通过按键处理蛇身的移动,看看这里的if里面的条件有个and,所以条件都满足才执行代码。条件是这样来的,比如我们蛇身开始方向向右,如果我们按左键的蛇身就向左移动的话,那么蛇身就会自己相撞,游戏马上失败,这游戏就不合理了。所以我们要按下左键的时候要保证蛇身移动方向不向右,其它方向按键的处理也是一个道理。代码如下:

		for event in pygame.event.get():
			if event.type == QUIT:
				terminate()
			elif event.type == KEYDOWN:		#处理蛇的移动方向
				if (event.key == K_LEFT or event.key == K_a) and direction != RIGHT:
					direction = LEFT
				elif (event.key == K_RIGHT or event.key == K_d) and direction != LEFT:
					direction = RIGHT
				elif (event.key == K_UP or event.key == K_w) and direction != DOWN:
					direction = UP
				elif (event.key == K_DOWN or event.key == K_s) and direction != UP:
					direction = DOWN
				elif event.key == K_ESCAPE:
					terminate()


蛇身移动一个距离完我们就要判断它是否撞到墙壁或自身。代码如下:

		#看蛇身是否撞击到自己或四周墙壁
		if wormCoods[HEAD]['x'] == -1 or wormCoods[HEAD]['x'] == CELLWIDTH or wormCoods[HEAD]['y'] == -1 or wormCoods[HEAD]['y'] == CELLHEIGHT:
			return #game over
		for wormBody in wormCoods[1:]:
			if wormBody['x'] == wormCoods[HEAD]['x'] and wormBody['y'] == wormCoods[HEAD]['y']:
				return #game over

第一个if是判断是否撞到墙壁,拿X方向上来说,最左边左边是-1,左右边则是CELLWIDTH,因为坐标从0开始,到CELLWIDTH-1结束。Y方向上同理。

然后是检测蛇身是否撞到自己,这里用一个循环,依次检查从头部后面的第二段蛇身开始,所以范围是wormCoods[1:] 看 蛇身是否与蛇的头部相撞,只需判断两个坐标是不是相等就是了。

接着就判断蛇是否吃到苹果。代码如下:

		#蛇是否迟到苹果
		if wormCoods[HEAD]['x'] == apple['x'] and wormCoods[HEAD]['y'] == apple['y']:
			#不删除蛇身尾段
			apple = getRandomLocation() #设置一个新的苹果
		else:
			del wormCoods[-1] #删除蛇身尾段

这里跟判断蛇身是否自己相撞是一个道理,只要判断蛇头的坐标是否与苹果的坐标相等。需要注意的是,当吃到苹果的话,蛇的尾段还是保留的,然后得到一个新的放置苹果的随机位置。如果没有吃到的话,我们就要删除尾段,蛇身前进一格,这个想一想就明白了。

删除掉蛇身尾段的话,接着就要把丢失的尾段补起来,也就是要添加蛇身的头段。代码如下:

		#添加蛇身头段
		if direction == UP:
			newHead = {'x': wormCoods[HEAD]['x'], 'y': wormCoods[HEAD]['y']-1}
		elif direction == DOWN:
			newHead = {'x': wormCoods[HEAD]['x'], 'y': wormCoods[HEAD]['y']+1}
		elif direction == LEFT:
			newHead = {'x': wormCoods[HEAD]['x']-1, 'y': wormCoods[HEAD]['y']}
		elif direction == RIGHT:
			newHead = {'x': wormCoods[HEAD]['x']+1, 'y': wormCoods[HEAD]['y']}
		wormCoods.insert(0,newHead)

添加蛇身头段的位置就要根据蛇身的移动方向来决定了。最后我们嗲用列表的插入方法,把新的蛇头插入到列表开始位置。wormCoods.insert(0,newHead)。

这就是整个游戏的核心部分了。下面就是根据我们上面对蛇的状态的修改做出的一些显示更新操作了。代码如下:

		DISPLAYSURF.fill(BGCOLOR)
		drawGrid() #画格子
		drawWorm(wormCoods) #画蛇身
		drawApple(apple) #画苹果
		drawScore(len(wormCoods) - 3)#显示得到分数
		pygame.display.update()
		FPSCLOCK.tick(FPS)

这几个函数都比较简单(略)

现在来说说游戏启动画面函数。showStartScreen().代码如下

def showStartScreen():
        titleFont = pygame.font.Font('freesansbold.ttf', 100)
        titleSurf1 = titleFont.render('Wormy!', True, WHITE, DARKGREEN)
        titleSurf2 = titleFont.render('Wormy!', True, GREEN)

        degrees1 = 0
        degrees2 = 0
        while True:
                DISPLAYSURF.fill(BGCOLOR)
                rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
                rotatedRect1 = rotatedSurf1.get_rect()
                rotatedRect1.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
                DISPLAYSURF.blit(rotatedSurf1,rotatedRect1)

                rotatedSurf2 = pygame.transform.rotate(titleSurf2, degrees2)
                rotatedRect2 = rotatedSurf2.get_rect()
                rotatedRect2.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
                DISPLAYSURF.blit(rotatedSurf2,rotatedRect2)		

                drawPressKeyMsg()

                if checkForKeyPress():
                                                pygame.event.get()
                                                return
                pygame.display.update()
                FPSCLOCK.tick(FPS)
                degrees1 += 3
                degrees2 += 7


启动画面的显示效果为两个字符串不断的旋转。所以需要创建两个字体字体对象和两个旋转角度的变量。还需要提示显示按下按键开始游戏。所以还有一个显示按键消息的函数,drawPressKeyMsg()。不单独现在这里面的原因而封装成一个函数的原因是在游戏结束画面中也会用到这个函数。接着检查按键消息,如果有按键按下则进入游戏,最后在函数末尾更新显示及改变每次增加的角度值。其中旋转图像用到的是pygame.transform.rotate()函数。

文章里面还说到了旋转这个方式并不是很完美。因为图像的旋转会给图像带来失真,使图像扭曲。除非你每次旋转的角度是90的整数倍。

最后给出程序运行效果截图:



我越来越觉得python很有爱啊。最后还要介绍一款文本编辑器,也是昨天才发现的。名字就是Sublime Text 2。太舒服了这款文本编辑器,而且各种主题很炫。

这是它的下载地址也是官网地址:http://www.sublimetext.com/,最新版是2.0.1。



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
T ABLE OF C ONTENTS Who is this book for? ........................................................................................................................ i About This Book .............................................................................................................................. ii Chapter 1 – Installing Python and Pygame ...................................................................................... 1 What You Should Know Before You Begin ................................................................................ 1 Downloading and Installing Python ............................................................................................. 1 Windows Instructions .................................................................................................................. 1 Mac OS X Instructions ................................................................................................................. 2 Ubuntu and Linux Instructions .................................................................................................... 2 Starting Python............................................................................................................................. 2 Installing Pygame......................................................................................................................... 3 How to Use This Book ................................................................................................................. 4 The Featured Programs ................................................................................................................ 4 Downloading Graphics and Sound Files ...................................................................................... 4 Line Numbers and Spaces ............................................................................................................ 4 Text Wrapping in This Book ....................................................................................................... 5 Checking Your Code Online ........................................................................................................ 6 More Info Links on http://invpy.com ........................................................................................... 6 Chapter 2 – Pygame Basics .............................................................................................................. 7 GUI vs. CLI ................................................................................................................................. 7 Source Code for Hello World with Pygame ................................................................................ 7 Setting Up a Pygame Program ..................................................................................................... 8 Game Loops and Game States ................................................................................................... 10 pygame.event.Event Objects ........................................................................................... 11 The QUIT Event and pygame.quit() Function .................................................................. 12 Pixel Coordinates ....................................................................................................................... 13iv http://inventwithpython.com/pygame A Reminder About Functions, Methods, Constructor Functions, and Functions in Modules (and the Difference Between Them) .................................................................................................. 14 Surface Objects and The Window ............................................................................................. 15 Colors ......................................................................................................................................... 16 Transparent Colors ..................................................................................................................... 17 pygame.Color Objects .......................................................................................................... 18 Rect Objects ............................................................................................................................... 18 Primitive Drawing Functions ..................................................................................................... 20 pygame.PixelArray Objects .............................................................................................. 23 The pygame.display.update() Function ...................................................................... 24 Animation .................................................................................................................................. 24 Frames Per Second and pygame.time.Clock Objects ....................................................... 27 Drawing Images with pygame.image.load() and blit() ............................................ 28 Fonts ........................................................................................................................................... 28 Anti-Aliasing.............................................................................................................................. 30 Playing Sounds........................................................................................................................... 31 Summary .................................................................................................................................... 32 Chapter 3 – Memory Puzzle .......................................................................................................... 33 How to Play Memory Puzzle ..................................................................................................... 33 Nested for Loops ..................................................................................................................... 33 Source Code of Memory Puzzle ................................................................................................ 34 Credits and Imports .................................................................................................................... 42 Magic Numbers are Bad ............................................................................................................ 42 Sanity Checks with assert Statements ................................................................................... 43 Telling If a Number is Even or Odd .......................................................................................... 44 Crash Early and Crash Often! .................................................................................................... 44 Making the Source Code Look Pretty ........................................................................................ 45 Using Constant Variables Instead of Strings ............................................................................. 46 Making Sure We Have Enough Icons ........................................................................................ 47 Tuples vs. Lists, Immutable vs. Mutable ................................................................................... 47 Email questions to the author: al@inventwithpython.comAbout This Book v One Item Tuples Need a Trailing Comma ................................................................................. 48 Converting Between Lists and Tuples ....................................................................................... 49 The global statement, and Why Global Variables are Evil.................................................... 49 Data Structures and 2D Lists ..................................................................................................... 51 The ―Start Game‖ Animation ..................................................................................................... 52 The Game Loop ......................................................................................................................... 52 The Event Handling Loop .......................................................................................................... 53 Checking Which Box The Mouse Cursor is Over ..................................................................... 54 Handling the First Clicked Box ................................................................................................. 55 Handling a Mismatched Pair of Icons ........................................................................................ 56 Handling If the Player Won ....................................................................................................... 56 Drawing the Game State to the Screen ...................................................................................... 57 Creating the ―Revealed Boxes‖ Data Structure ......................................................................... 58 Creating the Board Data Structure: Step 1 – Get All Possible Icons ......................................... 58 Step 2 – Shuffling and Truncating the List of All Icons ............................................................ 59 Step 3 – Placing the Icons on the Board .................................................................................... 59 Splitting a List into a List of Lists.............................................................................................. 60 Different Coordinate Systems .................................................................................................... 61 Converting from Pixel Coordinates to Box Coordinates ........................................................... 62 Drawing the Icon, and Syntactic Sugar ...................................................................................... 63 Syntactic Sugar with Getting a Board Space’s Icon’s Shape and Color .................................... 64 Drawing the Box Cover ............................................................................................................. 64 Handling the Revealing and Covering Animation ..................................................................... 65 Drawing the Entire Board .......................................................................................................... 66 Drawing the Highlight ............................................................................................................... 67 The ―Start Game‖ Animation ..................................................................................................... 67 Revealing and Covering the Groups of Boxes ........................................................................... 68 The ―Game Won‖ Animation .................................................................................................... 68 Telling if the Player Has Won ................................................................................................... 69vi http://inventwithpython.com/pygame Why Bother Having a main() Function? ................................................................................ 69 Why Bother With Readability? .................................................................................................. 70 Summary, and a Hacking Suggestion ........................................................................................ 74 Chapter 4 – Slide Puzzle ................................................................................................................ 77 How to Play Slide Puzzle ........................................................................................................... 77 Source Code to Slide Puzzle ...................................................................................................... 77 Second Verse, Same as the First ................................................................................................ 85 Setting Up the Buttons ............................................................................................................... 86 Being Smart By Using Stupid Code .......................................................................................... 87 The Main Game Loop ................................................................................................................ 88 Clicking on the Buttons ............................................................................................................. 89 Sliding Tiles with the Mouse ..................................................................................................... 90 Sliding Tiles with the Keyboard ................................................................................................ 90 ―Equal To One Of‖ Trick with the in Operator ........................................................................ 91 WASD and Arrow Keys ............................................................................................................ 91 Actually Performing the Tile Slide ............................................................................................ 92 IDLE and Terminating Pygame Programs ................................................................................. 92 Checking for a Specific Event, and Posting Events to Pygame’s Event Queue ........................ 92 Creating the Board Data Structure ............................................................................................. 93 Not Tracking the Blank Position ................................................................................................ 94 Making a Move by Updating the Board Data Structure ............................................................ 94 When NOT to Use an Assertion ................................................................................................ 95 Getting a Not-So-Random Move ............................................................................................... 96 Converting Tile Coordinates to Pixel Coordinates .................................................................... 97 Converting from Pixel Coordinates to Board Coordinates ........................................................ 97 Drawing a Tile ........................................................................................................................... 97 The Making Text Appear on the Screen .................................................................................... 98 Drawing the Board ..................................................................................................................... 99 Drawing the Border of the Board ............................................................................................... 99 Email questions to the author: al@inventwithpython.comAbout This Book vii Drawing the Buttons ................................................................................................................ 100 Animating the Tile Slides ........................................................................................................ 100 The copy() Surface Method ................................................................................................. 101 Creating a New Puzzle ............................................................................................................. 103 Animating the Board Reset ...................................................................................................... 104 Time vs. Memory Tradeoffs .................................................................................................... 105 Nobody Cares About a Few Bytes ........................................................................................... 106 Nobody Cares About a Few Million Nanoseconds .................................................................. 107 Summary .................................................................................................................................. 107 Chapter 5 – Simulate .................................................................................................................... 108 How to Play Simulate .............................................................................................................. 108 Source Code to Simulate .......................................................................................................... 108 The Usual Starting Stuff .......................................................................................................... 114 Setting Up the Buttons ............................................................................................................. 115 The main() Function ............................................................................................................. 115 Some Local Variables Used in This Program .......................................................................... 116 Drawing the Board and Handling Input ................................................................................... 117 Checking for Mouse Clicks ..................................................................................................... 118 Checking for Keyboard Presses ............................................................................................... 118 The Two States of the Game Loop .......................................................................................... 119 Figuring Out if the Player Pressed the Right Buttons .............................................................. 119 Epoch Time .............................................................................................................................. 121 Drawing the Board to the Screen ............................................................................................. 122 Same Old terminate() Function ....................................................................................... 122 Reusing The Constant Variables .............................................................................................. 123 Animating the Button Flash ..................................................................................................... 123 Drawing the Buttons ................................................................................................................ 126 Animating the Background Change ......................................................................................... 126 The Game Over Animation ...................................................................................................... 127viii http://inventwithpython.com/pygame Converting from Pixel Coordinates to Buttons ........................................................................ 129 Explicit is Better Than Implicit ................................................................................................ 129 Chapter 6 – Wormy ...................................................................................................................... 131 How to Play Wormy ................................................................................................................ 131 Source Code to Wormy ............................................................................................................ 131 The Grid ................................................................................................................................... 137 The Setup Code ........................................................................................................................ 137 The main() Function ............................................................................................................. 138 A Separate runGame() Function .......................................................................................... 139 The Event Handling Loop ........................................................................................................ 139 Collision Detection .................................................................................................................. 140 Detecting Collisions with the Apple ........................................................................................ 141 Moving the Worm .................................................................................................................... 142 The insert() List Method................................................................................................... 142 Drawing the Screen .................................................................................................................. 143 Drawing ―Press a key‖ Text to the Screen ............................................................................... 143 The checkForKeyPress() Function ................................................................................ 143 The Start Screen ....................................................................................................................... 144 Rotating the Start Screen Text ................................................................................................. 145 Rotations Are Not Perfect ........................................................................................................ 146 Deciding Where the Apple Appears ........................................................................................ 147 Game Over Screens .................................................................................................................. 147 Drawing Functions ................................................................................................................... 148 Don’t Reuse Variable Names ................................................................................................... 151 Chapter 7 - Tetromino .................................................................................................................. 153 How to Play Tetromino ............................................................................................................ 153 Some Tetromino Nomenclature ............................................................................................... 153 Source Code to Tetromino ....................................................................................................... 154 The Usual Setup Code ............................................................................................................. 166 Email questions to the author: al@inventwithpython.comAbout This Book ix Setting up Timing Constants for Holding Down Keys ............................................................ 166 More Setup Code ..................................................................................................................... 166 Setting Up the Piece Templates ............................................................................................... 168 Splitting a ―Line of Code‖ Across Multiple Lines ................................................................... 171 The main() Function ............................................................................................................. 172 The Start of a New Game ......................................................................................................... 173 The Game Loop ....................................................................................................................... 174 The Event Handling Loop ........................................................................................................ 174 Pausing the Game .................................................................................................................... 174 Using Movement Variables to Handle User Input ................................................................... 175 Checking if a Slide or Rotation is Valid .................................................................................. 175 Finding the Bottom .................................................................................................................. 178 Moving by Holding Down the Key.......................................................................................... 179 Letting the Piece ―Naturally‖ Fall ............................................................................................ 182 Drawing Everything on the Screen .......................................................................................... 182 makeTextObjs() , A Shortcut Function for Making Text .................................................. 183 The Same Old terminate() Function ................................................................................ 183 Waiting for a Key Press Event with the checkForKeyPress() Function ........................ 183 showTextScreen() , A Generic Text Screen Function ..................................................... 184 The checkForQuit() Function .......................................................................................... 185 The calculateLevelAndFallFreq() Function .......................................................... 185 Generating Pieces with the getNewPiece() Function ....................................................... 188 Adding Pieces to the Board Data Structure ............................................................................. 189 Creating a New Board Data Structure ...................................................................................... 189 The isOnBoard() and isValidPosition() Functions ............................................... 190 Checking for, and Removing, Complete Lines ........................................................................ 192 Convert from Board Coordinates to Pixel Coordinates ........................................................... 195 Drawing a Box on the Board or Elsewhere on the Screen ....................................................... 195 Drawing Everything to the Screen ........................................................................................... 196x http://inventwithpython.com/pygame Drawing the Score and Level Text .......................................................................................... 196 Drawing a Piece on the Board or Elsewhere on the Screen ..................................................... 197 Drawing the ―Next‖ Piece ........................................................................................................ 197 Summary .................................................................................................................................. 198 Chapter 8 – Squirrel Eat Squirrel ................................................................................................. 200 How to Play Squirrel Eat Squirrel............................................................................................ 200 The Design of Squirrel Eat Squirrel ......................................................................................... 200 Source Code to Squirrel Eat Squirrel ....................................................................................... 201 The Usual Setup Code ............................................................................................................. 211 Describing the Data Structures ................................................................................................ 212 The main() Function ............................................................................................................. 213 The pygame.transform.flip() Function .................................................................... 214 A More Detailed Game State than Usual ................................................................................. 214 The Usual Text Creation Code................................................................................................. 215 Cameras ................................................................................................................................... 215 The ―Active Area‖ ................................................................................................................... 217 Keeping Track of the Location of Things in the Game World ................................................ 218 Starting Off with Some Grass .................................................................................................. 219 The Game Loop ....................................................................................................................... 219 Checking to Disable Invulnerability ........................................................................................ 219 Moving the Enemy Squirrels ................................................................................................... 219 Removing the Far Away Grass and Squirrel Objects .............................................................. 221 When Deleting Items in a List, Iterate Over the List in Reverse ............................................. 221 Adding New Grass and Squirrel Objects ................................................................................. 223 Camera Slack, and Moving the Camera View ......................................................................... 223 Drawing the Background, Grass, Squirrels, and Health Meter ................................................ 224 The Event Handling Loop ........................................................................................................ 226 Moving the Player, and Accounting for Bounce ...................................................................... 228 Collision Detection: Eat or Be Eaten ....................................................................................... 229 Email questions to the author: al@inventwithpython.comAbout This Book xi The Game Over Screen ............................................................................................................ 231 Winning ................................................................................................................................... 232 Drawing a Graphical Health Meter .......................................................................................... 232 The Same Old terminate() Function ................................................................................ 232 The Mathematics of the Sine Function .................................................................................... 233 Backwards Compatibility with Python Version 2 .................................................................... 236 The getRandomVelocity() Function .............................................................................. 237 Finding a Place to Add New Squirrels and Grass .................................................................... 237 Creating Enemy Squirrel Data Structures ................................................................................ 238 Flipping the Squirrel Image ..................................................................................................... 239 Creating Grass Data Structures ................................................................................................ 239 Checking if Outside the Active Area ....................................................................................... 240 Summary .................................................................................................................................. 241 Chapter 9 – Star Pusher ................................................................................................................ 242 How to Play Star Pusher .......................................................................................................... 242 Source Code to Star Pusher ...................................................................................................... 242 The Initial Setup ....................................................................................................................... 256 Data Structures in Star Pusher ................................................................................................. 271 The ―Game State‖ Data Structure ............................................................................................ 271 The ―Map‖ Data Structure ....................................................................................................... 271 The ―Levels‖ Data Structure .................................................................................................... 272 Reading and Writing Text Files ............................................................................................... 272 Text Files and Binary Files ...................................................................................................... 272 Writing to Files ........................................................................................................................ 273 Reading from Files ................................................................................................................... 274 About the Star Pusher Map File Format .................................................................................. 274 Recursive Functions ................................................................................................................. 280 Stack Overflows ....................................................................................................................... 281 Preventing Stack Overflows with a Base Case ........................................................................ 283xii http://inventwithpython.com/pygame The Flood Fill Algorithm ......................................................................................................... 284 Drawing the Map ..................................................................................................................... 285 Checking if the Level is Finished ............................................................................................ 287 Summary .................................................................................................................................. 288 Chapter 10 – Four Extra Games ................................................................................................... 289 Flippy, an ―Othello‖ Clone ...................................................................................................... 290 Source Code for Flippy ............................................................................................................ 292 Ink Spill, a ―Flood It‖ Clone .................................................................................................... 305 Source Code for Ink Spill ........................................................................................................ 305 Four-In-A-Row, a ―Connect Four‖ Clone ................................................................................ 317 Source Code for Four-In-A-Row ............................................................................................. 317 Gemgem, a ―Bejeweled‖ Clone ............................................................................................... 327 Source Code for Gemgem ........................................................................................................ 327 Summary .................................................................................................................................. 340 Glossary ....................................................................................................................................... 342 About the Author ......................................................................................................................... 347
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值