Make Games with Python & Pygame (2)

本文介绍了Pygame的一些基本绘图函数,如画矩形、圆、线等,并展示了如何创建动画。通过填充颜色、画多边形、线段和使用PixelArray对象设置独立像素点来绘制图形。同时,文章提到了更新屏幕和控制帧率的重要方法pygame.display.update()以及pygame.time.Clock对象在限制游戏速度中的应用。
摘要由CSDN通过智能技术生成

接着上次的继续。

 

简单的画图函数

Pygame给我们提供了几个简单的画图函数,比如画矩形,圆,椭圆,线,独立的像素点。

下面这个程序就实现了一些简单画图的操作

import pygame, sys
from pygame.locals import *

pygame.init()

DISPLAYSURF = pygame.display.set_mode((500,400),0,32)

BLACK = (0, 0 , 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

DISPLAYSURF.fill(WHITE)
pygame.draw.polygon(DISPLAYSURF, GREEN, ((146,0),(291,106),(236,277),(56,277),(0,106)))
pygame.draw.line(DISPLAYSURF, BLUE, (60, 60), (120,60), 4)
pygame.draw.line(DISPLAYSURF, BLUE, (20, 60), (60,20))
pygame.draw.line(DISPLAYSURF, BLUE, (60, 120), (120,120), 4)
pygame.draw.circle(DISPLAYSURF,BLUE, (300,50), 20, 0)
pygame.draw.ellipse(DISPLAYSURF,RED,(300,250,40,80),1)
pygame.draw.rect(DISPLAYSURF,RED,(200,150,100,50))

pixObj = pygame.PixelArray(DISPLAYSURF)
pixObj[480][380] = BLACK
pixObj[482][382] = BLACK
pixObj[484][384] = BLACK
pixObj[486][386] = BLACK
pixObj[488][388] = BLACK

del pixObj

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()


执行后的效果如图


这里面有多一些新的Pygame的东西

fill(color)是Surface对象的一种方法,将surface对象的窗口全部填充一种颜色,就是背景色。

pygame.draw.polygon(surface, color, pointlist, width)画个多边形,其中surface和color参数告诉画在哪个对象里和使用的颜色,pointlist参数是由多个点构成的元组或列表,然后就会从第一个点开始,依次连接后面的点从而构成多边形,width参数是可选的,如果没有,则多边形会被color参数的颜色填充,如果有,而不会填充,多边形轮廓宽度就由width参数决定。传递0给width参数跟没有width参数是一样的。

需要注意的是,所有pygame.draw画图函数都有一个选择项参数width在最后,它们和pygame.draw,polygon函数中的width参数工作方式相同。

pygame.draw.line(surface, color, start_point, end_point, width) 画线函数

pygame.draw.lines(surface, color, closed, pointlist, width) 画多个相连的线,从起点到终点,与pygame.draw.polygon类似,唯一不同的是,如果closed参数为False,终点不会与起点相连接,传递True的话,终点会与起点想连接。

pygame.draw.circle(surface, color, center_point, radius, width) 画圆

pygame.draw.ellipse(surface, color, bounding_rectange, width) 画椭圆

pygame.draw.rect(surface, color, rectangle_tuple, width) 画矩形


pygame,PixelArray对象

pygame没有单独的画点函数。而方法就是创建pygame.PixelArray对象然后设置独立的像素点。创建一个关于Surface的PixelArray对象会‘锁住’Surface对象。一旦Surface对象被锁住,画图函数仍然可以使用,但是类似PNG或JPG的图片就不能作用在Surface对象上了,如果你想查看一个Surface对象是否锁住了,可以调用Surface对象get_locked()方法,如果锁住了会返回True,反之False。

设置这些独立像素点的方法是用两个索引值访问,比如pixObj[480][380] = BLACK ,这样就会将X坐标值的480和Y坐标的380这两个点设为黑色。

为了告诉pygame你完成了画完独立像素点,你需要通过一个del语句删除PixArray对象。删除PixArray对象会‘解锁’Surface对象,那样你就可以继续在上面加载图片了。如果忘了删除,则下次你想在Surface对象上加载图片的话就会报错。

pygame.display.update()函数

当你完成所有画图函数后,你必须调用pygame.display.update()函数让起显示在显示器上。

需要记住的一点是pygame.display.update()函数只会让显示对象(即通过调用pygame.display.set_mode()返回的对象)显示在屏幕上。如果你想让图片显示在屏幕上,你必须“blit”它们(复制它们的意思)到显示对象上通过blit()方法。

Animation

让图像动起来其实很简单,就是将图像从一个地方移动到另一个地方,就是清除掉图像原来所在地方的图像,然后在另一个地方加载这个图像,这样看上去图像就像动起来了一样。在计算机看来,其实就是一群像素的移动。下图就是一个例子


下面是一段示例代码

import pygame, sys
from pygame.locals import *

pygame.init()

FPS = 30 # frames per second setting
fpsClock = pygame.time.Clock()

# set up the window
DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)
pygame.display.set_caption('Animation')

WHITE = (255, 255, 255)
catImg = pygame.image.load('cat.png')
catx = 10
caty = 10
direction = 'right'

while True: # the main game loop
    DISPLAYSURF.fill(WHITE)

    if direction == 'right':
        catx += 5
        if catx == 280:
            direction = 'down'
    elif direction == 'down':
        caty += 5
        if caty == 220:
            direction = 'left'
    elif direction == 'left':
        catx -= 5
        if catx == 10:
            direction = 'up'
    elif direction == 'up':
        caty -= 5
        if caty == 10:
            direction = 'right'

    DISPLAYSURF.blit(catImg, (catx, caty))

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()
    fpsClock.tick(FPS)

其中cat.png的下载地址PDF上面已经给出了。下载后必须与源文件放在一个文件夹里面。执行效果就是一只猫儿在一个窗口里面移动。先右,再下,再左,再上,如此循环。

上面这段代码里面又出现了一些新的东西。

帧率和pygame.time.Clock对象

帧率与刷新率指的是程序一秒钟能显示图片的数目,用FPS和帧每秒来表示。(在其它电脑显示器上,FPS有个大众名字叫做赫兹,许多显示器都有60赫兹的帧速率,或者叫做每秒60帧)低的帧率出现在一些图像游戏里就会导致游戏看起来是跳跃和抖动的,如果程序有太多的代码而经常刷新屏幕的话,就会导致FPS下降。但是在这本书里面的游戏因为足够简单所以即使在一些老的电脑上也不会出现问题。

pygame.time.Clock对象能够帮助我们确认程序能跑到的一个最大的确定的FPS值。Clock对象将在游戏主循环中插入小小的暂停以确保我们的游戏程序不会跑的太快。如果我们没有这些暂停的话,我们的游戏就会跑得跟电脑一样快。对玩游戏的人来说它确实太快了。在游戏循环中调用Clock对象的tick()方法能保证我们的游戏跑到一个确定的速度不管电脑跑得有多么快。创建Clock对象如下语句

fpsClock = pygame.time.Clock()

tick方法应该在游戏循环的最末尾调用,也就是在pygame.display.update之后,调用语句如下

fpsClock.tick(FPS)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值