2017-03-28 4 views
0

현재 프로젝트 용 게임을 만들어야하는 A 레벨 컴퓨터 과학 과정을 수강하고 있습니다. 나는이 코드가 아마도 효율적이지는 않지만 내 작업에 그것을 유지하려고 노력하고 혼란스러워하는 한 비트의 손을 원할 것이다.파이 게임 스크롤

오른쪽 방향으로 화면을 스크롤하려합니다. 화면의 모든 객체를 관련 방향으로 움직여서 수행됩니다. 로봇이 그 안에있을 때 화면이 움직이기 시작해야하는 경계를 만들었습니다. 그러나 내가 작성한 코드는 화면에서 업데이트되지 않고 플랫폼이 이동하고 로봇이 경계 내에있을 때 로봇의 속도가 변합니다.

모든 아이디어 나 도움을 주시면 감사하겠습니다.

import pygame as pg 
import time 
import random 


pg.init()#initiates pygame 

display_height = 690#Creates width and height of screen 
display_width = 1024 
#Colours 
white = (255,255,255) 
black = (0,0,0) 
red = (255,0,0) 
green = (0,255,0) 
blue = (0,0,255) 
sky = (73,71,65) # grey 

Robot_height = 99#Height of robot 
Robot_width = 112#Width of robot 
lives = 3 #Robot Lives 
Bullet_Fired = False 
PowerUp_Active = False 
Robot_acc = 0.3 #Robot Acceleration 
vec = pg.math.Vector2 

gameDisplay = pg.display.set_mode((display_width,display_height)) #Sets display properties of window 
pg.display.set_caption ("Game") #Title on window 
clock = pg.time.Clock() 
robotImg = pg.image.load("robot1.png") #Loads robots image 

#Class for platforms 
class Platform(pg.sprite.Sprite): 
    def __init__(self, x,y,w,h): 
     pg.sprite.Sprite.__init__(self) 
     self.image = pg.Surface((w,h)) 
     self.image.fill(blue) 
     self.rect = self.image.get_rect() 
     self.rect.x = x 
     self.rect.y = y 

#List of platforms 
PLATFORM_LIST = [(0,display_height - 40,display_width,40), 
       (display_width /2 - 50,display_height * 3/4,100,20)] 
#Platform group 
platforms = pg.sprite.Group() 


#class for robot 
class RobotClass(pg.sprite.Sprite): 
    def __init__(self): 
     pg.sprite.Sprite.__init__(self) 
     self.image = pg.Surface((Robot_width,Robot_height)) 
     self.rect = self.image.get_rect() 
     self.rect.center = (display_width/2, display_height/2) 
     self.RobotPos = vec(display_width/2, display_height/2) 
     self.bottom = (0,0) 
     self.vel = vec(0, 0) 
     self.acc = vec(0, 0.3) 

#Creates Robot 
Robot = RobotClass() 
for plat in PLATFORM_LIST: 
    p = Platform(*plat) 
    platforms.add(p) 
def draw(): 
    for plat in PLATFORM_LIST: 
      p = Platform(*plat) 
      pg.draw.rect(gameDisplay, blue, (p)) 

#Jump function 
def jump(): 
    #Checks pixel below robot to see if there is a collision 
    Robot.rect.x = Robot.rect.x +1 
    hits = pg.sprite.spritecollide(Robot , platforms, False) 
    Robot.rect.x = Robot.rect.x -1 
    if hits: 
     #Gives robot velocity of 5 upwards 
     Robot.vel.y = -10 

#game loop 
def game_loop(): 
    pg.draw.rect(gameDisplay, red, Robot.rect, 2) 
    Robot_friction = -0.3 #Friction value 
    vec = pg.math.Vector2 #Setting vec as vector quantity 
    while True: 
     for event in pg.event.get(): 
      if event.type == pg.QUIT: 
       pg.quit 
       quit() 
      #Starts acceleration when key is pressed 
      if event.type == pg.KEYDOWN: 
       if event.key == pg.K_LEFT: 
        Robot.acc.x = -Robot_acc 
       elif event.key == pg.K_RIGHT: 
        Robot.acc.x = Robot_acc 
       elif event.key == pg.K_UP: 
        jump() 
      #Adds friction to accleration to slow robot down when key is not being pressed 
      if event.type == pg.KEYUP: 
       if event.key == pg.K_LEFT or event.key == pg.K_RIGHT: 
        Robot.acc.x = Robot.acc.x * Robot_friction 

     #Adjusts velocity of robot by adding the acceleration on each cycle 
     Robot.vel = Robot.vel+ Robot.acc 
     #Fills background 
     gameDisplay.fill(sky) 
     #Draws the platforms to the screen and adds them to platform group 
     draw() 
     #Changes Robot position according to its velocity,acceleration and the friction 
     Robot.RobotPos = Robot.RobotPos + Robot.vel + 0.5 * Robot.acc 
     #Loads robot onto screen 
     gameDisplay.blit(robotImg,(Robot.rect)) 
     pg.draw.rect(gameDisplay, red, Robot.rect, 2) 
     #Updates display 
     pg.display.update() 
     clock.tick(60) 

     #Sets bottom of robot to its position 
     Robot.rect.midbottom = Robot.RobotPos 

     #Collision detection 
     if Robot.vel.y > 0: 
      hits = pg.sprite.spritecollide(Robot , platforms, False) 
      if hits: 
       #Puts Robot on top of platform 
       Robot.RobotPos.y = hits[0].rect.top + 1 
       Robot.vel.y = 0 

     #Scrolling 

     if Robot.rect.left < display_width/4: 
      print("left") 
      Robot.RobotPos.x = Robot.RobotPos.x - abs(Robot.vel.x) 
      print(Robot.vel) 
      for plat in platforms: 
       plat.rect.x = plat.rect.x + abs(Robot.vel.x) 
       pg.draw.rect(gameDisplay, blue, (PLATFORM_LIST[0])) 
     if Robot.rect.right > (display_width-display_width/4): 
      print("right") 
      Robot.RobotPos.x = Robot.RobotPos.x + abs(Robot.vel.x) 
      print(Robot.vel) 
      for plat in platforms: 
       plat.rect.x = plat.rect.x - abs(Robot.vel.x) 

     #Sets top velocity of robot  
     if Robot.vel.x > 6: 
      Robot.vel.x = 6 
     if Robot.vel.x < -6: 
      Robot.vel.x = -6 
     #Makes robot velocity = 0 when it is close to 0 
     if Robot.vel.x < 0.05 and Robot.vel.x > -0.05: 
      Robot.acc.x = 0 
      Robot.vel.x = 0 


game_loop() 
pg.quit() 
quit() 
+0

나는이와 함께 놀아 오전 플랫폼이 전혀 움직이지 않는다 . 가장자리에 가까워지면 로봇이 바닥을 통과합니다. 확실히 몇 가지 문제. 더 자세히 살펴볼 것입니다. – The4thIceman

+1

누군가 다른 질문에 댓글을 달았으므로 일반적인 이름 지정 규칙을 따르십시오. 'lowercase_with_underscore'라는 이름의 함수, 변수, 인스턴스 및 속성,'CamelCase' 클래스 및'UPPERCASE_WITH_UNDERSCORE'가있는 상수. 이렇게하면 코드를 더 쉽게 읽고 변수가 무엇인지 이해할 수 있으므로 예를 들어 클래스가 클래스인지 여부를 조회 할 필요가 없습니다. –

답변

1

그래서 여기에 우리가 간다. 로봇이 한계에 도달 할 경우 여기에서 플랫폼을 업데이트 :

for plat in platforms: 
    plat.rect.x = plat.rect.x - abs(Robot.vel.x) 

을하지만 원래 PLATFORM_LIST 목록에서 그리 플랫폼을 그릴 때

def draw(): 
    for plat in PLATFORM_LIST: 
     p = Platform(*plat) 
     pg.draw.rect(gameDisplay, blue, (p)) 

그래서 무슨 일이 끝나는 것은 심지어 비록입니다 플랫폼을 제대로 업데이트하고 있으므로 원래 목록에서 그리기 때문에 업데이트 된 목록을 그리지 않습니다. 당신은 당신이 업데이트하는 플랫폼 목록에서 그리해야합니다

def draw(): 
    for plat in platforms: 
     pg.draw.rect(gameDisplay, blue, plat) 

둘째, 내가 다시 올바른 방향으로, 왼쪽 스크롤 한도에 도달 한 번 움직임을 발견 로봇에게 잘못된 방향으로 움직였다. 이 대체 :이와

if Robot.rect.left < display_width/4: 
    Robot.RobotPos.x = Robot.RobotPos.x - abs(Robot.vel.x) 

을 (빼기 기호는 더하기 기호로 전환) : 게임에 주위를 재생하는 동안 내가 찾은

if Robot.rect.left < display_width/4: 
    Robot.RobotPos.x = Robot.RobotPos.x + abs(Robot.vel.x) 

그냥 몇 가지.

업데이트

또한 라운딩에 문제가 있습니다. 파이 게임 직사각형은 정수를 취합니다. 속도 귀하의 계산은 float를 산출하고 여기에 사각형의 x에 저를 추가하려는 :

for plat in platforms: 
    plat.rect.x = plat.rect.x - abs(Robot.vel.x) 

이 독특한 방식으로 이동하는 표시 (플랫폼)에 표시 반올림 문제가 발생합니다. 당신은 그들에게 int 치의 할 수있다 : 그렇지 않으면 당신은 당신이 VEC()에서 로봇과 거래를하는 것처럼 플랫폼을해야 할 것이다

for plat in platforms: 
    plat.rect.x = plat.rect.x - int(abs(Robot.vel.x)) 

+0

플랫폼을 좌우로 움직이는 위의 코드와 플레이어가 경계 내에서 가속하는 방법은 "[display_width + 50, display_height * 3/4,100,20]"에서 다른 플랫폼을 추가하는 방법을 포함했습니다. 이 플랫폼은 오른쪽으로 스크롤 할 때 다른 플랫폼에 더 가깝게 이동합니다. 어떤 아이디어? –

+0

@AshleyKelly 문제를 해결하기 위해 답변을 업데이트합니다. 스포일러, 그것은 반올림과 관련이 있습니다. – The4thIceman

+0

아 맞습니다. 다시 한 번 감사드립니다. –