下面是创建和管理游戏管道的基本代码:
import pygame as pg
import sys,os,math,time,random
# colours
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
# general stuff
WIDTH = 1024
HEIGHT = 576
FPS = 60
# other
all_events = [pg.QUIT, pg.ACTIVEEVENT, pg.KEYDOWN, pg.KEYUP, pg.MOUSEMOTION,
pg.MOUSEBUTTONUP, pg.MOUSEBUTTONDOWN, pg.VIDEORESIZE,
pg.VIDEOEXPOSE, pg.USEREVENT]
pg.init()
screen = pg.display.set_mode((WIDTH, HEIGHT))
clock = pg.time.Clock()
# Class to manage Pipes
class Pipe_Manager:
def __init__(self):
self.pipe_width = 50
self.pipes = []
self.pipe_speed = 5
self.max_tick = 75
self.spawn_tick = self.max_tick
def manage_pipes(self):
self.spawner()
self.manage()
self.display()
def make_pipe(self):
height = random.randint(100,326)
gap = random.randint(100,250)
surf1 = pg.Surface((self.pipe_width, height))
surf1.fill(green)
surf2 = pg.Surface((self.pipe_width, HEIGHT - (height + gap)))
surf2.fill(green)
# surface, (x,y) and vertical height
pipe = [surf1, [WIDTH, 0], height]
pipe2 = [surf2, [WIDTH, height + gap], HEIGHT - (height + gap)]
self.pipes.append(pipe)
self.pipes.append(pipe2)
def spawner(self):
if self.spawn_tick == self.max_tick:
self.make_pipe()
self.spawn_tick = 0
self.spawn_tick += 1
def manage(self):
for pipe in self.pipes:
# move the pipe
pipe[1][0] -= self.pipe_speed
# check if it's off screen
if pipe[1][0] + self.pipe_width < 0:
self.pipes.remove(pipe)
def display(self):
for pipe in self.pipes:
screen.blit(pipe[0], (pipe[1][0], pipe[1][1]))
################################################################################
pg.event.set_blocked(all_events)
pg.event.set_allowed([pg.QUIT, pg.KEYDOWN])
pipe_manager = Pipe_Manager()
loop = True
while loop:
screen.fill(white)
pipe_manager.manage_pipes()
pg.display.update()
clock.tick(FPS)
管道在水平移动时似乎会摇晃,有时顶部管道与底部管道不一致。
我希望这不是我的计算机特有的问题,因为我已经抽象出大量的 flappy-bird-clone 代码,并且这个管道滞后问题的根源一定在这里的某个地方。