我正在制作跑步者,我添加了一个功能,让我的背景能够“移动”。它工作但不是很顺利,当pygame刷新背景时,我的敌人似乎传送,这有点难以解释。
我已经尝试过convert_alpha()
或convert()
。
这是我的游戏的最小代码应该可以工作,让你看到什么是错的,这是我用于背景的图片:background。
from pygame import *
import random
import sys
import pygame
WIDTH = 600
HEIGHT = 750
FPS = 60
SPEEDX = 5
SPEEDY = 3
# define colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# initialize pygame and create window
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
background = image.load("background.png").convert_alpha()
x,y = 0, 0
x1, y1 = 0, -HEIGHT
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((40, 40))
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.rect.centerx = WIDTH / 2
self.rect.y = HEIGHT
def update(self):
self.SPEEDX = 0
keystate = pygame.key.get_pressed()
#Move right
if keystate[pygame.K_d]:
self.SPEEDX = SPEEDX
#Move left
if keystate[pygame.K_a]:
self.SPEEDX = - SPEEDX
#Close the game
if keystate[pygame.K_LCTRL] and keystate[pygame.K_z]:
sys.exit()
#Make the character moving
self.rect.x += self.SPEEDX
#Do not cross screen border
#Left side
if self.rect.left < 0:
self.rect.left = 0
#Right side
if self.rect.right > WIDTH:
self.rect.right = WIDTH
#Bottom side
if self.rect.bottom > HEIGHT:
self.rect.bottom = HEIGHT
class Enemy(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((30, 40))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
self.speedx = random.randrange(-3, 3)
def update(self):
self.rect.x += self.speedx
self.rect.y += self.speedy
if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20:
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
def Death():
player.rect.centerx = WIDTH / 2
player.rect.y = HEIGHT
all_sprites.remove(all_enemies)
all_enemies.empty()
for i in range(10):
enemies = Enemy()
all_sprites.add(enemies)
all_enemies.add(enemies)
def Scrolling():
global x,y,x1,y1
y1 += 5
y += 5
screen.blit(background,(x,y))
screen.blit(background,(x1,y1))
if y > HEIGHT:
y = -HEIGHT
if y1 > HEIGHT:
y1 = -HEIGHT
player = Player()
enemy = Enemy()
all_sprites = pygame.sprite.Group()
all_enemies = pygame.sprite.Group()
all_sprites.add(player)
for i in range(10):
enemies = Enemy()
all_sprites.add(enemies)
all_enemies.add(enemies)
# Game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if sprite.spritecollide(player, all_enemies, True):
Death()
# Update
all_sprites.update()
# Draw / render
Scrolling()
all_sprites.draw(screen)
pygame.display.flip()
clock.tick(FPS)
pygame.quit()
答案 0 :(得分:0)
可能是vSync感谢skrx的回答和当时的每个人。