如何在 Pygame 中滚动我的背景图像? [英] How Do I Scroll My BackGround Image In Pygame?

查看:88
本文介绍了如何在 Pygame 中滚动我的背景图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在 pygame 中滚动我的背景图像

我有一个移动的对象,我希望它在该对象移动时滚动这是现在背景图片的视频视频现在我只是将背景图像 blitting

<预><代码>定义重绘窗口():window.blit(bg,(0,0))

这是我的完整代码

导入pygame随机导入pygame.init()#这是尖叫高度窗口 = pygame.display.set_mode((500,500))#知道我们输入了screem名称pygame.display.set_caption(菜鸟飞扬的小鸟游戏")#玩家等级类鸟:def __init__(self,x,y,height,width,color):自我.x = xself.y = yself.bright = [pygame.image.load("killers50.png"),pygame.image.load("killers51.png"),pygame.image.load("killers52.png"),pygame.image.load("killers53.png"),]self.bleft = [pygame.image.load("ms1.png"),pygame.image.load("ms2.png"),pygame.image.load("ms3.png"),pygame.image.load("ms4.png"),]self.bright = [pygame.transform.scale(image,(image.get_width()//15,image.get_height()//15)) 用于 self.bright 中的图像]self.bleft = [pygame.transform.scale(image,(image.get_width()//15,image.get_height()//15)) 用于 self.bleft 中的图像]self.height = 高度self.width = 宽度self.isJump = Falseself.JumpCount = 10self.fall = 0self.speed = 5self.Walking = 0self.vel = 5self.color = 颜色self.rect = pygame.Rect(x,y,height,width)self.direction = 向下"# 这使敌人左右移动定义绘制(自我):self.rect.topleft = (self.x,self.y)如果 self.Walking + 1 >= 33:self.Walking = 0如果 self.vel >0:# 左window.blit(self.bright[self.Walking % 3], (self.x,self.y))self.Walking += 1其他:#对window.blit(self.bleft[self.Walking % 3], (self.x,self.y))self.Walking += 1班级平台:def __init__(self,x,y,height,width,color):自我.x = x自我.y = yself.height = 高度self.width = 宽度self.color = 颜色self.pipis = pygame.image.load("pip.png")self.pipis = pygame.transform.scale(self.pipis,(self.pipis.get_width()//3,self.pipis.get_height()//3))self.rect = pygame.Rect(x,y,height,width)定义绘制(自我):self.rect.topleft=(self.x,self.y)window.blit(self.pipis,self.rect)类点:def __init__(self,x,y,height,width,color):自我.x = x自我.y = yself.height = 高度self.width = 宽度self.color = 颜色self.pipis = pygame.image.load("pipo.png")self.pipis = pygame.transform.scale(self.pipis,(self.pipis.get_width()//3,self.pipis.get_height()//3))self.rect = pygame.Rect(x,y,height,width)定义绘制(自我):self.rect.topleft=(self.x,self.y)window.blit(self.pipis,self.rect)#玩家和敌人白色 = (255,255,255)鸟 1 = 鸟(0,400,50,50,白色)红色 = (255,48,48)平台 1 = 平台(600,300,150,50,白色)平台 2 = 平台(800,200,150,50,white)platform3 = 平台(1100,300,150,50,white)平台4 =平台(1300,400,150,50,白色)platform5 = 平台(1500,300,150,50,white)platform6 = 平台(1800,200,150,50,white)# 第 2 轮platform7 = 平台(2200,300,150,50,white)platform8 = 平台(2400,200,150,50,white)platform9 = 平台(2600,300,150,50,white)platform10 = 平台(2700,400,150,50,white)platform11 = 平台(2900,300,150,50,white)platform12 = 平台(3200,200,150,50,white)# 第 3 轮platform13 = 平台(3400,300,150,50,white)platform14 = 平台(3600,200,150,50,white)platform15 = 平台(3800,300,150,50,white)platform16 = 平台(4000,400,150,50,white)platform17 = 平台(4200,300,150,50,white)platform18 = 平台(4400,200,150,50,white)# 第 4 轮platform19 = 平台(600,300,150,50,white)platform20 = 平台(800,200,150,50,white)platform21 = 平台(1100,300,150,50,white)platform22 = 平台(1300,400,150,50,white)platform23 = 平台(1500,300,150,50,white)platform24 = 平台(1800,200,150,50,white)平台= [平台1,平台2,平台3,平台4,平台5,平台6,平台7,平台8,平台9,平台10,平台11,平台12,平台13,平台14,平台15,平台16,平台17,平台18,平台19,平台20,平台21,平台22,平台23,平台24]#第二点pip1 = pip(600,-160,150,50,white)pip2 = pip(800,-270,150,50,white)pip3 = pip(1100,-170,150,50,white)pip4 = pip(1300,-170,150,50,white)pip5 = pip(1500,-170,150,50,white)pip6 = pip(1800,-270,150,50,white)# 第 2 轮pip7 = pip(2200,-160,150,50,white)pip8 = pip(2400,-270,150,50,white)pip9 = pip(2600,-170,150,50,white)pip10 = pip(2700,-170,150,50,white)pip11 = pip(2900,-170,150,50,white)pip12 = pip(3200,-270,150,50,white)# 第 3 轮# 第 3 轮pip13 = pip(3400,-160,150,50,white)pip14 = pip(3600,-270,150,50,white)pip15 = pip(3800,-170,150,50,white)pip16 = pip(4000,-170,150,50,white)pip17 = pip(4200,-170,150,50,white)pip18 = pip(4400,-270,150,50,white)# 第 4 轮pip19 = pip(600,-160,150,50,white)pip20 = pip(800,-270,150,50,white)pip21 = pip(1100,-170,150,50,white)pip22 = pip(1300,-170,150,50,white)pip23 = pip(1500,-170,150,50,white)pip24 = pip(1800,-270,150,50,white)pips = [pip1,pip2,pip3,pip4,pip5,pip6,pip7,pip8,pip9,pip10,pip11,pip12,pip13,pip14,pip15,pip16,pip17,pip18,pip19,pip20,pip21,pip22,pip23,pip24]#窗户类宝珠:def __init__(self,x,y,height,width,color):自我.x = x自我.y = yself.height = 高度self.width = 宽度self.color = 颜色self.rect = pygame.Rect(x,y,height,width)定义绘制(自我):self.rect.topleft = (self.x,self.y)类粒子和点:def __init__(self,x,y,height,width,color):自我.x = xself.y = yself.height = 高度self.width = 宽度self.color = 颜色self.rect = pygame.Rect(x,y,height,width)定义绘制(自我):self.rect.topleft = (self.x,self.y)粒子与点 = []#这是球体orb1 = orb(1500,100,50,550,white)orb2 = orb(2600,100,50,550,white)orbes = [orb1,orb2]platformGroup = pygame.sprite.Group平台列表 = []级别 = ["","","","","p p p p p p p p p p p p p p p p","","","","","","",]对于 iy,枚举(级别)中的行:对于 ix, col in enumerate(row):如果 col == p":new_platforms =particleAndPoint(ix*10, iy*0, 10,1010,(255,255,255))particleAndPoints.append(new_platforms)# 分数文本font = pygame.font.Font('Candarai.ttf',60)分数 = 0loltext = font.render("" + str(score), True, (255,255,255))lolrect = loltext.get_rect()lolrect.center = ((130,60))#哇声动漫wowsound = pygame.mixer.Sound("wows.wav")爆炸声 = pygame.mixer.Sound(partexplode.wav")类粒子:def __init__(self,x,y):自我.x = x自我.y = yself.x_vel = random.randrange(-10,13)*1self.y_vel = random.randrange(-10,-1)*1self.lifetime = 0def draw(self,window):self.lifetime += 1如果 self.lifetime <30:self.x -= self.x_velself.y -= self.y_velpygame.draw.rect(窗口,(232,255,24),(self.x,self.y,16,16))# 绘制屏幕的东西定义重绘窗口():bg = pygame.image.load("bgs.png")window.blit(bg,(0,0))#玩家抽奖鸟1.draw()对于平台中的平台:平台.draw()对于 pip 中的 pip:pip.draw()对于particleAndPoints中的particleAndPoint:particleAndPoint.draw()window.blit(loltext,lolrect)对于球体中的球体:orb.draw()对于粒子中的粒子:粒子绘制(窗口)fps = (30)时钟 = pygame.time.Clock()粒子 = []运行 = 真运行时:时钟滴答(fps)对于 pygame.event.get() 中的事件:如果 event.type == pygame.QUIT:运行 = 错误# 如果玩家与障碍物相撞,则为玩家加 1 并删除障碍物对于范围内的一个(len(particleAndPoints)-1,-1,-1):如果bird1.rect.colliderect(particleAndPoints[one].rect):得分 += 1鸟1.速度+= 0.2delparticleAndPoints[一]爆炸声.播放()loltext = font.render("" + str(score), True, (255,255,255))lolrect.center = ((130,60))对于范围内的 x(60):x, y =bird1.rect.center粒子.附加(粒子(x,y))# 如果球与玩家 1 碰撞显示粒子# 如果球与玩家 1 碰撞显示粒子如果bird1.rect.colliderect( orb1.rect ):对于范围内的 x(60):wowsound.play()爆炸声.播放()x, y =bird1.rect.center粒子.附加(粒子(x,y))如果bird1.rect.colliderect( orb2.rect ):对于范围内的 x(60):wowsound.play()爆炸声.播放()x, y =bird1.rect.center粒子.附加(粒子(x,y))键 = pygame.key.get_pressed()# 鸟动鸟1.x +=鸟1.速度如果不是bird1.isJump:鸟1.y +=鸟1.速度Bird1.isJump = False如果键[pygame.K_SPACE]:Bird1.isJump = 真# 这部分让你跳上平台碰撞 = 假对于平台中的平台:如果bird1.rect.colliderect(platform.rect):碰撞 = 假# 这会让玩家跌倒如果bird1.rect.bottom >= 500:碰撞 = 真Bird1.isJump = FalseBird1.JumpCount = 10鸟1.y = 500 - 鸟1.高度如果碰撞:如果键[pygame.K_SPACE]:Bird1.isJump = 真Bird1.fall = 0别的:如果bird1.JumpCount >0:Bird1.y -= (bird1.JumpCount*abs(bird1.JumpCount)) * 0.2Bird1.JumpCount -= 1别的:Bird1.JumpCount = 10Bird1.isJump = False# 这会向右滚动我的屏幕如果bird1.x >300:鸟1.x -=鸟1.速度对于平台中的平台:平台.x -=bird1.speed对于 pip 中的 pip:pip.x -=bird1.speed对于particleAndPoints中的particleAndPoint:particleAndPoint.x -=bird1.speed对于球体中的球体:orb.x -=bird1.speed重绘窗口()pygame.display.update()pygame.quit()

我希望背景继续向右滚动,因为我的播放器总是向右移动,谢谢!

解决方案

您必须在平铺模式下绘制背景两次.添加一个变量来定义背景 bg_shift 的偏移量.通过 %(模)运算符计算与背景宽度相关的偏移量(参见 二进制算术运算).最后blit背景两次:

bg_shift = 0定义重绘窗口():bg_width = gb.get_widht()bg_offset = bg_shift % bg_widthwindow.blit(bg, (-bg_offset, 0))window.blit(bg, (bg_width - bg_offset, 0))

您必须根据鸟的运动在主应用程序循环中更改变量 bg_shift.

bg_shift +=bird1.speed

您甚至可以尝试以不同的速度移动背景,从而获得不错的透视效果.例如:

bg_shift += round(bird1.speed/2)

I was Wonder How I Could Scroll mY background image in pygame

I have a moving object I want it to scroll when that object is moving here is a video of the background image right now video right now I am just blitting the background image


def redrawwindow():
    window.blit(bg,(0,0))

here is my full code

import pygame
import random
pygame.init()

#this is screem height
window = pygame.display.set_mode((500,500))

#know we put screem name
pygame.display.set_caption("Noobs Flappy Bird Game")

#player class
class bird:
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y =y
        self.bright = [
            pygame.image.load("killers50.png"),
            pygame.image.load("killers51.png"),
            pygame.image.load("killers52.png"),
            pygame.image.load("killers53.png"),
 
                           
                              ]
        self.bleft = [
            pygame.image.load("ms1.png"),
            pygame.image.load("ms2.png"),
            pygame.image.load("ms3.png"),
            pygame.image.load("ms4.png"),
 





                          
                              ]
        self.bright = [pygame.transform.scale(image,(image.get_width()//15,image.get_height()//15)) for image in self.bright]
        self.bleft = [pygame.transform.scale(image,(image.get_width()//15,image.get_height()//15)) for image in self.bleft]
        self.height = height
        self.width = width
        self.isJump = False
        self.JumpCount = 10
        self.fall = 0
        self.speed = 5
        self.Walking = 0
        self.vel = 5
        self.color  = color
        self.rect = pygame.Rect(x,y,height,width)
        self.direction = "down"

                # this makes the enemy move right and left
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        if self.Walking + 1 >= 33:
            self.Walking = 0

        if self.vel > 0:        # left
            window.blit(self.bright[self.Walking % 3], (self.x,self.y))
            self.Walking += 1
        else:                   # right
            window.blit(self.bleft[self.Walking % 3], (self.x,self.y))
            self.Walking += 1

class platform:
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.color = color
        self.pipis = pygame.image.load("pip.png")
        self.pipis = pygame.transform.scale(self.pipis,(self.pipis.get_width()//3,self.pipis.get_height()//3))
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.rect.topleft=(self.x,self.y)
        window.blit(self.pipis,self.rect)

class pip:
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.color = color
        self.pipis = pygame.image.load("pipo.png")
        self.pipis = pygame.transform.scale(self.pipis,(self.pipis.get_width()//3,self.pipis.get_height()//3))
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.rect.topleft=(self.x,self.y)
        window.blit(self.pipis,self.rect)


#player and enemy
white = (255,255,255)
bird1 = bird(0,400,50,50,white)

red = (255,48,48)
platform1 = platform(600,300,150,50,white)
platform2 = platform(800,200,150,50,white)
platform3 = platform(1100,300,150,50,white)
platform4 = platform(1300,400,150,50,white)
platform5 = platform(1500,300,150,50,white)
platform6 = platform(1800,200,150,50,white)

# ROUND 2
platform7 = platform(2200,300,150,50,white)
platform8 = platform(2400,200,150,50,white)
platform9 = platform(2600,300,150,50,white)
platform10 = platform(2700,400,150,50,white)
platform11 = platform(2900,300,150,50,white)
platform12 = platform(3200,200,150,50,white)

# rOUND 3
platform13 = platform(3400,300,150,50,white)
platform14 = platform(3600,200,150,50,white)
platform15 = platform(3800,300,150,50,white)
platform16 = platform(4000,400,150,50,white)
platform17 = platform(4200,300,150,50,white)
platform18 = platform(4400,200,150,50,white)

# ROUND 4
platform19 = platform(600,300,150,50,white)
platform20 = platform(800,200,150,50,white)
platform21 = platform(1100,300,150,50,white)
platform22 = platform(1300,400,150,50,white)
platform23 = platform(1500,300,150,50,white)
platform24 = platform(1800,200,150,50,white)

platforms = [platform1,platform2,platform3,platform4,platform5,platform6,platform7,platform8,platform9,platform10,platform11,platform12,platform13,platform14,platform15,platform16,platform17,platform18,platform19,platform20,platform21,platform22,platform23,platform24]

# sceond pip

pip1 = pip(600,-160,150,50,white)
pip2 = pip(800,-270,150,50,white)
pip3 = pip(1100,-170,150,50,white)
pip4 = pip(1300,-170,150,50,white)
pip5 = pip(1500,-170,150,50,white)
pip6 = pip(1800,-270,150,50,white)

# ROUND 2
pip7 = pip(2200,-160,150,50,white)
pip8 = pip(2400,-270,150,50,white)
pip9 = pip(2600,-170,150,50,white)
pip10 = pip(2700,-170,150,50,white)
pip11 = pip(2900,-170,150,50,white)
pip12 = pip(3200,-270,150,50,white)

# ROUND 3

# rOUND 3
pip13 = pip(3400,-160,150,50,white)
pip14 = pip(3600,-270,150,50,white)
pip15 = pip(3800,-170,150,50,white)
pip16 = pip(4000,-170,150,50,white)
pip17 = pip(4200,-170,150,50,white)
pip18 = pip(4400,-270,150,50,white)


# ROUND 4

pip19 = pip(600,-160,150,50,white)
pip20 = pip(800,-270,150,50,white)
pip21 = pip(1100,-170,150,50,white)
pip22 = pip(1300,-170,150,50,white)
pip23 = pip(1500,-170,150,50,white)
pip24 = pip(1800,-270,150,50,white)

pips = [pip1,pip2,pip3,pip4,pip5,pip6,pip7,pip8,pip9,pip10,pip11,pip12,pip13,pip14,pip15,pip16,pip17,pip18,pip19,pip20,pip21,pip22,pip23,pip24]#window




class orb: 
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.color = color
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.rect.topleft = (self.x,self.y)

        




class particleAndPoint:  
    def __init__(self,x,y,height,width,color):
        self.x = x
        self.y =y
        self.height = height
        self.width = width
        self.color = color
        self.rect = pygame.Rect(x,y,height,width)
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        
particleAndPoints = []
# this is the orbs
orb1 = orb(1500,100,50,550,white)
orb2 = orb(2600,100,50,550,white)

orbes = [orb1,orb2]
platformGroup = pygame.sprite.Group
platformList = []
level = [" ",
             "                                       ",
             "                                                      ",
             "                                                                                                                     ",
             "                                                                p                 p                              p                     p                p                               p                                      p                      p                  p         p                 p                            p                    p                   p                    p                 p                    p                    p",
             "                                                                                                                                                             ",
             "                                                                                                                                                            ",
             "                                                                                                                                                    ",
             "                                                                                                                                                               ",
             "                                                                                                                                                                  ",
             "                                                                                                  ",]
for iy, row in enumerate(level):
    for ix, col in enumerate(row):
        if col == "p":
            new_platforms = particleAndPoint(ix*10, iy*0, 10,1010,(255,255,255))
            particleAndPoints.append(new_platforms)





# the score text
font = pygame.font.Font('Candarai.ttf',60)
score = 0
loltext = font.render("" + str(score), True, (255,255,255))
lolrect = loltext.get_rect()
lolrect.center = ((130,60))

# wow sound anime
wowsound = pygame.mixer.Sound("wows.wav")
explodesound = pygame.mixer.Sound("partexplode.wav")

class particle:
    def __init__(self,x,y):
        self.x = x
        self.y = y
        self.x_vel = random.randrange(-10,13)*1
        self.y_vel = random.randrange(-10,-1)*1
        self.lifetime = 0
    def draw(self,window):
        self.lifetime += 1
        if self.lifetime <30:
            self.x -= self.x_vel
            self.y -= self.y_vel
            pygame.draw.rect(window,(232,255,24),(self.x,self.y, 16,16))
# draw the screen things
def redrawwindow():
    bg = pygame.image.load("bgs.png")
    window.blit(bg,(0,0))
 
#player draw
    bird1.draw()
    for platform in platforms:
        platform.draw()
    for pip in pips:
        pip.draw()
    for particleAndPoint in particleAndPoints:
        particleAndPoint.draw()
    window.blit(loltext,lolrect)
    for orb in orbes:
        orb.draw()
    for particle in particles:
        particle.draw(window)


fps = (30)
clock = pygame.time.Clock()
particles = []
run = True
while run:
    clock.tick(fps)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False



    # if player collides with the obsticles add 1 to the player and delete the obstacle
     
                

    for one in range(len(particleAndPoints)-1,-1,-1):
        if bird1.rect.colliderect(particleAndPoints[one].rect):
            score += 1
            bird1.speed += 0.2
            del particleAndPoints[one]
            explodesound.play()
            loltext = font.render("" + str(score), True, (255,255,255))
            lolrect.center = ((130,60))
            for x in range(60):
                x, y = bird1.rect.center
                particles.append( particle( x, y ) )

 



        # if ball collides with player1 show the particles
        # if ball collides with player1 show the particles
    if bird1.rect.colliderect( orb1.rect ):
        for x in range(60):
            wowsound.play()
            explodesound.play()
            x, y = bird1.rect.center
            particles.append( particle( x, y ) )

        
    if bird1.rect.colliderect( orb2.rect ):
        for x in range(60):
            wowsound.play()
            explodesound.play()
            x, y = bird1.rect.center
            particles.append( particle( x, y ) ) 
    
    keys = pygame.key.get_pressed()

    # bird moving
    bird1.x += bird1.speed
    if not bird1.isJump:
        bird1.y += bird1.speed
        bird1.isJump = False

        if keys[pygame.K_SPACE]:
            bird1.isJump = True


        
        # this part lets you jump on platform
        collide = False
        for platform in platforms:
            if bird1.rect.colliderect(platform.rect):
                collide = False

            
            # this makes the player fall down up to 
            if bird1.rect.bottom >= 500:
                collide = True
                bird1.isJump = False
                bird1.JumpCount = 10
                bird1.y = 500 - bird1.height

        if collide:
            if keys[pygame.K_SPACE]:
                bird1.isJump = True
            bird1.fall = 0


    else:
        if bird1.JumpCount > 0:
            bird1.y -= (bird1.JumpCount*abs(bird1.JumpCount)) * 0.2
            bird1.JumpCount -= 1
        else:
            bird1.JumpCount = 10
            bird1.isJump = False


    # this scrolls my screen right
    if bird1.x > 300:
        
        bird1.x -= bird1.speed
        for platform in platforms:
            platform.x -= bird1.speed
            
        for pip in pips:
            pip.x -=bird1.speed
        for particleAndPoint in particleAndPoints:
            particleAndPoint.x -= bird1.speed
        for orb in orbes:
            orb.x -= bird1.speed



            
    redrawwindow()
    pygame.display.update()
pygame.quit()

I want the background to keep scrolling right because my player is always moving right Thank YOu!

解决方案

You have to draw the background twice in a tiled mode. Add a variable which defines the offset of the background bg_shift. Compute the offset in relation to the width of the background by the % (modulo) operator (See Binary arithmetic operations). Finally blit the background twice:

bg_shift = 0

def redrawwindow():

    bg_width = gb.get_widht()
    bg_offset = bg_shift % bg_width 
    
    window.blit(bg, (-bg_offset, 0)) 
    window.blit(bg, (bg_width - bg_offset, 0)) 

You have to change the variabel bg_shift in the main application loop dependent on the movement of the bird.

bg_shift += bird1.speed

You can even try to move the background with a different speed, which gives a nice perspective effect. For instance:

bg_shift += round(bird1.speed / 2)

这篇关于如何在 Pygame 中滚动我的背景图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆