谁来告诉我python pygame的rect问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了谁来告诉我python pygame的rect问题相关的知识,希望对你有一定的参考价值。

# -*- coding: cp936 -*-
import sys,pygame
from pygame.locals import *
from random import randrange

class weight(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image=weight_image
self.rect=self.image.get_rect()
self.reset()

def reset(self):
"""
把秤砣移动到屏幕顶端的随机位置。
"""
self.rect.top = -self.rect.height【①这句是什么意思?】
self.rect.centerx = randrange(screen_size[0])【②这句是什么意思?】

def update(self):
"""
更新秤砣,显示下一帧
"""
self.rect.top += 1【③这句是什么意思?】
if self.rect.top > screen_size[1]:【④这句是什么意思?】
self.reset()

#初始化
pygame.init()
screen_size=800,600
pygame.display.set_mode(screen_size)
#pygame.mouse.set_visible(0)

#载入秤砣的图像
weight_image=pygame.image.load("weight.png")
weight_image=weight_image.convert()

#创建一个子图形组
sprites=pygame.sprite.RenderPlain()
sprites.add(weight())

#获取屏幕表面,并且填充
screen=pygame.display.get_surface()
bg=(255,255,255)
screen.fill(bg)
pygame.display.flip()

#用于清除子图形
def clear_callback(surf,rect):
surf.fill(bg,rect)

while True:
for event in pygame.event.get():
if event.type==QUIT:
sys.exit()
if event.type==KEYDOWN and event.key==K_ESCAPE:
sys.exit()

#清除前面位置
sprites.clear(screen,clear_callback)
#更新所有子图形
sprites.update()
#绘制所有子图形
updates=sprites.draw(screen)
#更新所需的显示部分
pygame.display.update(updates)

问题我都用【】标记上了,就四句看不懂……

屏幕坐标系大概是这个样子的:

其中,screen 的那个矩形就是窗口了,screen 的左上角坐标是 (0 ,0)


self.rect.top = -self.rect.height

这句的意思是,将 rect 向上移动出屏幕边缘

结合上面的图,大概就是那个位置


self.rect.centerx = randrange(screen_size[0])

screen_size 是指屏幕的大小, screen_size[0] 就是屏幕的宽度啦

centerx 是指矩形中心的 X 坐标(就是宽度一半的位置)

randrange 是返回一个 0 到 参数 之间的随机数

综合起来,就是将矩形的横坐标设置成屏幕宽度范围内的随机位置


self.rect.top += 1

这句的意思是将矩形向下移动一个像素

因为在 update 函数中,所以综合意思就是,矩形以每帧1像素的速度向下移动


self.rect.top > screen_size[1]

这句的意思是,当矩形的上边缘在屏幕的下边缘之下的时候。


希望能帮到你啦~

参考技术A

最近正好在学习pygame,楼主的问题已经有人回答清楚啦,我就说一下Rect对象的各个属性吧。

Rect对象有以下属性:

--返回一个坐标数字

x,y,top, left, bottom, right, centerx, centerysize, width, heightw,h;

--返回一个(X,Y)坐标数组

topleft(左上), bottomleft(左下), topright(右上), bottomright(右下),midtop(中上), midleft(左中), midbottom(底中), midright(右中),center(中心点坐标)

直接上图,灰色矩形大小(900,450),中央蓝色矩形(400,510),大家自己体会一下

Python制作小游戏(十九)

pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(imagepath) self.image = pygame.transform.scale(self.image, (blocksize, blocksize)) self.rect = self.image.get_rect() self.rect.left, self.rect.top = coordinate[ self.coordinate = coordinate self.blocksize = blocksize screen.blit(self.image, self.rect) pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(imagepath) self.image = pygame.transform.scale(self.image, (blocksize, blocksize)) self.rect = self.image.get_rect() self.rect.left, self.rect.top = coordinate[ self.coordinate = coordinate self.blocksize = blocksize screen.blit(self.image, self.rect) pygame.sprite.Sprite.__init_ elif raise ValueError(% screen.blit( True

pygame.sprite.Sprite.__init_ direction == < [ False elif direction == >= [ False elif direction == < [ False elif direction == >= [ False raise ValueError(% direction) True action = random.choice([ flag = False action [ flag = True elif action [ flag = True action, flag Bomb(imagepath=imagepath, coordinate=copy.deepcopy( screen.blit( True eaten_fruit = pygame.sprite.spritecollide( fruit directions = [ idx = directions.index(direction) pygame.sprite.Sprite.__init_ * - * screen.blit( text = rect = text.get_rect(center=( screen.blit(text, rect) False False explode_area = each image = pygame.image.load( image = pygame.transform.scale(image, ( rect = image.get_rect() rect.left, rect.top = each[ screen.blit(image, rect) explode_area explode_area = [] ymin range( ymin < instances_list[ymin][[ explode_area.append([ ymax range( ymax >= len(instances_list) instances_list[ymax][[ explode_area.append([ xmin range( xmin < instances_list[[ explode_area.append([xmin, xmax range( xmax >= len(instances_list[instances_list[[ explode_area.append([xmax, explode_area

self.instances_list = self.__parse(mapfilepath) self.bg_paths = bg_paths self.wall_paths = wall_paths self.blocksize = blocksize self.height = len(self.instances_list) self.width = len(self.instances_list[ self.screen_size = (blocksize * self.width, blocksize * self.height) j range(self.height): i range(self.width): instance = self.instances_list[j][i] instance == elem = Wall(self.wall_paths[ instance == elem = Wall(self.wall_paths[ instance == elem = Wall(self.wall_paths[ instance == elem = Background(self.bg_paths[ instance == elem = Background(self.bg_paths[ instance == elem = Background(self.bg_paths[ ValueError( elem.draw(screen) i = random.randint( j = random.randint( coordinate = [i, j] used_spaces coordinate used_spaces: instance = self.instances_list[j][i] instance [ coordinate self.instances_list[coordinate[ instances_list = [] open(mapfilepath) f: line f.readlines(): instances_line_list = [] c line: c [ instances_line_list.append(c) instances_list.append(instances_line_list) instances_list

pygame.init() pygame.mixer.init() pygame.mixer.music.load(cfg.BGMPATH) pygame.mixer.music.play( screen = pygame.display.set_mode(cfg.SCREENSIZE) pygame.display.set_caption( Interface(screen, cfg, mode= font = pygame.font.SysFont( gamemap_path cfg.GAMEMAPPATHS: map_parser = mapParser(gamemap_path, bg_paths=cfg.BACKGROUNDPATHS, wall_paths=cfg.WALLPATHS, blocksize=cfg.BLOCKSIZE) fruit_sprite_group = pygame.sprite.Group() used_spaces = [] i range( coordinate = map_parser.randomGetSpace(used_spaces) used_spaces.append(coordinate) fruit_sprite_group.add(Fruit(random.choice(cfg.FRUITPATHS), coordinate=coordinate, blocksize=cfg.BLOCKSIZE)) coordinate = map_parser.randomGetSpace(used_spaces) used_spaces.append(coordinate) ourhero = Hero(imagepaths=cfg.HEROZELDAPATHS, coordinate=coordinate, blocksize=cfg.BLOCKSIZE, map_parser=map_parser, hero_name= aihero_sprite_group = pygame.sprite.Group() coordinate = map_parser.randomGetSpace(used_spaces) aihero_sprite_group.add(Hero(imagepaths=cfg.HEROBATMANPATHS, coordinate=coordinate, blocksize=cfg.BLOCKSIZE, map_parser=map_parser, hero_name= used_spaces.append(coordinate) coordinate = map_parser.randomGetSpace(used_spaces) aihero_sprite_group.add(Hero(imagepaths=cfg.HERODKPATHS, coordinate=coordinate, blocksize=cfg.BLOCKSIZE, map_parser=map_parser, hero_name= used_spaces.append(coordinate) bomb_sprite_group = pygame.sprite.Group() is_win_flag = screen = pygame.display.set_mode(map_parser.screen_size) clock = pygame.time.Clock() dt = clock.tick(cfg.FPS) event pygame.event.get(): event.type == pygame.QUIT: pygame.quit() sys.exit( event.type == pygame.KEYDOWN: event.key == pygame.K_UP: ourhero.move( event.key == pygame.K_DOWN: ourhero.move( event.key == pygame.K_LEFT: ourhero.move( event.key == pygame.K_RIGHT: ourhero.move( event.key == pygame.K_SPACE: ourhero.bomb_cooling_count <= bomb_sprite_group.add(ourhero.generateBomb(imagepath=cfg.BOMBPATH, digitalcolor=cfg.YELLOW, explode_imagepath=cfg.FIREPATH)) screen.fill(cfg.WHITE) hero aihero_sprite_group: action, flag = hero.randomAction(dt) flag action == bomb_sprite_group.add(hero.generateBomb(imagepath=cfg.BOMBPATH, digitalcolor=cfg.YELLOW, explode_imagepath=cfg.FIREPATH)) ourhero.eatFruit(fruit_sprite_group) hero aihero_sprite_group: hero.eatFruit(fruit_sprite_group) map_parser.draw(screen) bomb bomb_sprite_group: bomb.is_being: bomb_sprite_group.remove(bomb) explode_area = bomb.draw(screen, dt, map_parser) explode_area: ourhero.coordinate explode_area: ourhero.health_value -= bomb.harm_value hero aihero_sprite_group: hero.coordinate explode_area: hero.health_value -= bomb.harm_value fruit_sprite_group.draw(screen) hero aihero_sprite_group: hero.draw(screen, dt) ourhero.draw(screen, dt) pos_x = showText(screen, font, text=ourhero.hero_name+ hero aihero_sprite_group: pos_x, pos_y = pos_x+ pos_x = showText(screen, font, text=hero.hero_name+ ourhero.health_value <= is_win_flag = hero aihero_sprite_group: hero.health_value <= aihero_sprite_group.remove(hero) len(aihero_sprite_group) == is_win_flag = pygame.display.update() clock.tick(cfg.FPS) is_win_flag: Interface(screen, cfg, mode= break  Interface(screen, cfg, mode=\'game_end\')

逻辑很简单,就是初始化之后导入关卡地图开始游戏,结束一关之后,判断是游戏胜利还是游戏失败,游戏胜利的话就进入下一关,否则就退出主循环,让玩家选择是否重新开始游戏。具体细节自己看下代码就能懂了,必要的注释我都加过了。

All done~完整源代码详见相关文件~

更多

代码截止2019-08-28测试无误。

T_T小游戏系列的代码都会上传到Github上,欢迎大家stars呀:

https://github.com/CharlesPikachu/Games

 

微信公众号:

Charles的皮卡丘


哈哈哈哈哈

长按二维码关注

以上是关于谁来告诉我python pygame的rect问题的主要内容,如果未能解决你的问题,请参考以下文章

Python碰撞使用pygame检测图像(图像类型:png)

如何在Pygame中给pygame.sprite.rect矩形分配一个 "rect "属性?

Pygame错误:self.spritedict [spr] = surface_blit(spr.image,spr.rect)

Python制作小游戏(十九)

python,外星人入侵游戏,Pycharm,pygame,写完了,但是有bug,希望帮我找一下原因

使用Rect函数参数的Pygame类型错误