如何使用pygame在python中创建滚动背景?

时间:2017-06-19 05:28:10

标签: python pygame

过去两天我一直试图制作太空射击游戏,我想让背景向下滚动,但我不知道怎么做。 继承我的代码:

import pygame
import time
pygame.init()

width = 800
height = 600

black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)

ship_width = 35
ship_height = 64

disp = pygame.display.set_mode((width,height))

pygame.display.set_caption("Space Jump")

clock = pygame.time.Clock()

background = pygame.image.load("Space.png").convert()

shipImg = pygame.image.load("Ship.png")

def ship(x,y):
    disp.blit(shipImg, (x,y))

def gameLoop():
    x = (width * 0.45)
    y = (height * 0.8)

x_ch = 0
y_ch = 0

gameExit = False

while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_ch = -5
            elif event.key == pygame.K_RIGHT:
                x_ch = 5
            elif event.key == pygame.K_UP:
                y_ch = -5
            elif event.key == pygame.K_DOWN:
                y_ch = 5


        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                x_ch = 0
            if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                y_ch = 0

    x += x_ch
    y += y_ch

    if x > width - ship_width or x < 0:
        x_ch = 0

    if y > height - ship_height or y < 0:
        y_ch = 0
    x_bg = 0
    while True:
        disp.blit(background, (0,x_bg)) # i tried this but when i launch
                                        #a black screen just appears without 
        x_bg -= 1                       #any image
    ship(x,y)

    pygame.display.update()
    clock.tick(60)

gameLoop()
pygame.quit()
quit()

我有一个背景,我想让它连续向下滚动你能帮帮我吗?

1 个答案:

答案 0 :(得分:1)

首先要做的事情是:

  • 修复您的缩进
  • 你的船只功能几乎无用
  • 使用Rect来处理移动
  • 你真正的问题是你的代码永远不会达到pygame.display.update()因为你的第二次循环

因此,要制作无休止的滚动背景,并且简单的方法是执行以下操作:

将您的背景图片两次,一次位于y位置,一次位于y + image_width(将y替换为您想要的x) 。然后,在主循环的每次迭代中,您都可以从y中减去以创建运动。图像移动整个高度后,将y重置为起始值

这是一个完整的示例,显示滚动背景(以及如何使用精灵,组,向量和rects):

import pygame
pygame.init()
SCREEN = pygame.display.set_mode((300, 300))

move_map = {pygame.K_w: pygame.math.Vector2( 0, -1),
            pygame.K_s: pygame.math.Vector2( 0,  1),
            pygame.K_a: pygame.math.Vector2(-1,  0),
            pygame.K_d: pygame.math.Vector2( 1,  0)}

class Actor(pygame.sprite.Sprite):
    def __init__(self, group, color, pos, size=(30, 30)):
        self.image = pygame.Surface(size)
        self.image.fill(color)
        self.rect = self.image.get_rect(center=pos)
        pygame.sprite.Sprite.__init__(self, group)

class Bullet(Actor):
    def __init__(self, *args):
        Actor.__init__(self, *args)
        self.speed = 10

    def update(self):
        self.rect.move_ip(self.speed, 0)
        if not SCREEN.get_rect().colliderect(self.rect):
            self.kill()

class Player(Actor):
    def __init__(self, *args):
        self._layer = 4
        Actor.__init__(self, *args)
        self.speed = 4
        self.timeout = 0

    def update(self):
        p = pygame.key.get_pressed()
        move_vector = pygame.math.Vector2(0, 0)
        for v in [move_map[key] for key in move_map if p[key]]:
            move_vector += v
        if move_vector:
            self.rect.move_ip(*move_vector.normalize() * self.speed)
            self.rect.clamp_ip(SCREEN.get_rect())

        if self.timeout :
            self.timeout -= 1
        if p[pygame.K_SPACE] and not self.timeout:
            Bullet(self.groups()[0], (130, 200, 77), self.rect.center, (10, 3))
            self.timeout = 5


class Background(pygame.sprite.Sprite):
    def __init__(self, number, *args):
        self.image = pygame.image.load('back.jpg').convert()
        self.rect = self.image.get_rect()
        self._layer = -10
        pygame.sprite.Sprite.__init__(self, *args)
        self.moved = 0
        self.number = number
        self.rect.x = self.rect.width * self.number

    def update(self):
        self.rect.move_ip(-1, 0)
        self.moved += 1

        if self.moved >= self.rect.width:
            self.rect.x = self.rect.width * self.number
            self.moved = 0

group = pygame.sprite.LayeredUpdates()
Player(group, (255, 255, 255), (100, 100))
Background(0, group)
Background(1, group)

clock = pygame.time.Clock()
run = True
while run:
    for e in pygame.event.get():
        if e.type ==pygame.QUIT:
            run = False
    SCREEN.fill((0,0,0))
    group.update()
    group.draw(SCREEN)
    pygame.display.flip()
    clock.tick(60)

为了测试它,您可以使用此图像(将其另存为back.jpg):

enter image description here