pygame surface.blit()方法的问题

潘女士 2018-08-03 10:13:49
image就是一张图片
self.rect=self.image.get_rect()

self.screen.blit(self.image, self.rect)
众所周知,第二个参数用于指定绘制的位置,所以上面这种写法的第二个参数是rect,实际有4个值,于是我尝试了下面这么写也行
self.screen.blit(self.image, (self.rect.x, self.rect.y))

而经我测试,就算指定四个值也完全没有任何影响
self.screen.blit(self.image, (self.rect.x, self.rect.y, 400, 500))
self.screen.blit(self.image, (self.rect.x, self.rect.y, 400, 600))
绘制结果完全一样,说明后两个值根本没用

我的问题是,在我添加了一行self.rect.width = 100后,发现image在绘制时不能绘制到屏幕最右边的宽度为100的区域,这是为什么呢。。。

源码如下,一个打飞机小游戏
//ship.py
import pygame

class Ship():
def __init__(self, ai_settings, screen):
"""Initialize the ship, and set its starting position."""
self.screen = screen
self.ai_settings = ai_settings

# Load the ship image, and get its rect.
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()

# Start each new ship at the bottom center of the screen.
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom

# Store a decimal value for the ship's center.
self.center = float(self.rect.centerx)

# Movement flags.
self.moving_right = False
self.moving_left = False

def update(self):
"""Update the ship's position, based on movement flags."""
# Update the ship's center value, not the rect.
if self.moving_right and self.rect.right < self.screen_rect.right:
self.center += self.ai_settings.ship_speed_factor
if self.moving_left and self.rect.left > 0:
self.center -= self.ai_settings.ship_speed_factor

# Update rect object from self.center.
self.rect.centerx = self.center

def blitme(self):
"""Draw the ship at its current location."""
self.rect.w = 100
self.screen.blit(self.image, self.rect)

//game_function.py
import sys
import pygame
from bullet import Bullet
def check_keydown_events(event, ai_settings, screen, ship, bullets):
"""Respond to keypresses."""
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.key == pygame.K_SPACE:
fire_bullet(ai_settings, screen, ship, bullets)

def check_keyup_events(event, ship):
"""Respond to key releases."""
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False

def check_events(ai_settings, screen, ship, bullets):
"""Respond to keypresses and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_events(event, ai_settings, screen, ship, bullets)
elif event.type == pygame.KEYUP:
check_keyup_events(event, ship)

def fire_bullet(ai_settings, screen, ship, bullets):
"""Fire a bullet, if limit not reached yet."""
# Create a new bullet, add to bullets group.
if len(bullets) < ai_settings.bullets_allowed:
new_bullet = Bullet(ai_settings, screen, ship)
bullets.add(new_bullet)

def update_screen(ai_settings, screen, ship, bullets):
"""Update images on the screen, and flip to the new screen."""
# Redraw the screen, each pass through the loop.
screen.fill(ai_settings.bg_color)

# Redraw all bullets, behind ship and aliens.
for bullet in bullets.sprites():
bullet.draw_bullet()
ship.blitme()

# Make the most recently drawn screen visible.
pygame.display.flip()

def update_bullets(bullets):
"""Update position of bullets, and get rid of old bullets."""
# Update bullet positions.
bullets.update()

# Get rid of bullets that have disappeared.
for bullet in bullets.copy():
if bullet.rect.bottom <= 0:
bullets.remove(bullet)
//主程序
import pygame
from pygame.sprite import Group

from settings import Settings
from ship import Ship
import game_functions as gf

def run_game():
# Initialize pygame, settings, and screen object.
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode(
(ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("Alien Invasion")

# Set the background color.
bg_color = (230, 230, 230)

# Make a ship.
ship = Ship(ai_settings, screen)
# Make a group to store bullets in.
bullets = Group()

# Start the main loop for the game.
while True:
gf.check_events(ai_settings, screen, ship, bullets)
ship.update()
gf.update_bullets(bullets)
gf.update_screen(ai_settings, screen, ship, bullets)

run_game()

添加了self.rect.w = 100,飞机就不能移动到最右边了,这是为什么呢。。。
...全文
2161 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Andy(chao) 2020-05-28
  • 打赏
  • 举报
回复
image原本就带有参数,是不是原本的image不对称导致不能移动到最右边。
print_5 2020-03-02
  • 打赏
  • 举报
回复
经过测试发现:.screen.blit(self.image,(10,10),self.rect2)
图片 x坐标y坐标矩形
for_grasp 2018-08-04
  • 打赏
  • 举报
回复 1
你好!
self.rect 引用了 self.image图片的长和宽,即self.rect.width == self.image.width(矩形大小等于图片初始化的),
对self.rect.width改变之后,这个绘图矩形也变了,可能是由于图像是从右边开始缩减或增大的,而它的边界没有在界面上体现出来。
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

37,719

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧