2014-12-09 5 views
3

좋아요, 일주일 전에 파이 게임을 사용하기 시작했는데 기본을 이해한다고 생각합니다. 내 게임은 정말 간단합니다. 풍선을 좌우로 움직여 들어오는 나사를 피하십시오. 풍선을 왼쪽이나 오른쪽으로 옮겨서 성공적으로 만들었지 만, 수업에 익숙하지 않고 화면에 여러 개의 나사를 빠르게 생성하는 다른 방법을 모른다. 어떤 도움이라도 대단히 감사하겠습니다.파이 게임에서 급속한 산란

Heres는 내 코드 : 모든

import pygame 
from pygame.locals import * 
import sys 
import time 
pygame.init() 

screen = pygame.display.set_mode((600,600)) 
pygame.display.set_caption('Baloon Pop') 


baloon_size = (70,70) 

white = (255,255,255) 
cyan = (0,255,255) 
red = (255,0,0) 

screen.fill(cyan) 

baloon = pygame.image.load('/users/Gaming/Desktop/rsz_baloon.png') 
screw = pygame.image.load('/users/Gaming/Desktop/rsz_screw_png3029.png') 



FPS = 30 
fps_time = pygame.time.Clock() 

baloonX = 280 
baloonY = 500 

import random 
screwX = random.randint(0,600) 
screwY = 20 

LEFT = "left" 
RIGHT = "right" 
movement = "down" 




while True: 
    screwY = screwY+10 
    screen.fill(cyan) 
    screen.blit(screw, (screwX,screwY)) 
    screen.blit(baloon, (baloonX,baloonY)) 

    for event in pygame.event.get(): 
     if event.type == QUIT: 
      pygame.quit() 
      sys.exit() 
     if event.type == KEYDOWN: 
      if event.key == K_RIGHT: 
       baloonX = baloonX+30 
       if baloonX >= 580: 
        baloonX = baloonX -30 
      elif event.key == K_LEFT: 
       baloonX = baloonX -30 
       if baloonX <=-30: 
        baloonX = baloonX+30 






    pygame.display.update() 
    fps_time.tick(FPS) 
+0

객체 지향 프로그래밍에 대한 자습서를 찾아보십시오. 너는 그런 넓은 (그리고 막연한) 질문에 여기에서 다량 도움을 얻게 확률이 낮다. – martineau

답변

1

첫째, 당신의 플레이어를 제어하는 ​​클래스를 사용하는 것이 좋습니다 것입니다. 이로 인해 충돌을 쉽게 파악하고 탐지 할 수 있습니다. 이 작업을 수행하는 간단한 방법은 다음과 같습니다 그런

class Player: 

    def __init__(self, x, speed): 
     self.x = x 
     self.speed = speed 
     self.moveright = 0 
     self.moveleft = 0 

    def update(self, time_passed): 
     if self.moveright: 
      self.x += self.speed * time_passed 
     if self.moveleft: 
      self.x -= self.speed * time_passed 

, 적을 제어 할 수 비슷한 클래스입니다. 여기

class Enemy: 

    def __init__(self, x, speed): 
     self.x = x 
     self.y = 0 
     self.speed = speed 

    def update(self, time_passed): 
     self.y += self.speed*time_passed 

는 time_passed은 당신의 시계() 객체의 틱 값입니다. screen은 pygame.display 표면입니다.

이제 적을 객체화 했으므로 적군 클래스의 인스턴스를 저장하는 목록을 만들 수 있습니다.

내가 제안한 것처럼이 메커니즘을 사용하면 게임을 부드럽게 할 수 있습니다. 각 KEYDOWN 이벤트에서 증가분을 사용하는 것은 권장되지 않습니다.

적 인스턴스를 저장하고 플레이어 인스턴스를 생성하는 목록을 만듭니다

Enemylist = [] 
Player1 = Player(<SomeXValue>,0.1) 

무작위 적 창조에 이동. N 루프마다 나사 (즉, Enemy())를 작성해야한다면 해당 간격으로 활성화되는 플래그를 생성 할 수 있습니다. 변수 'count'를 가질 수 있습니다.이 변수는이를 결정합니다. 초기 값은 0이 후 1 에 의해 모든 루프에 그것을 향상시킬 수 있습니다 (예 : 매 5 개 루프를 산란 적을를 원하는 경우, (5)에 의해 N 대체)

입니다
if count % n == 0:  
    Enemylist.append(Enemy(random.randint(0,<YourScreenSize>),0.1)) 
if count > 1000: 
    count = 0 

에서 적을 산란 화면의 임의의 장소, 그리고 그들이 아래로 이동합니다. 0.1은 샘플 속도입니다.

이제 루프 섹션으로 ... 이벤트 루프에는 단일 키 누르기를 위해 KEYDOWN 및 KEYUP 확인이 있어야합니다. 여기서 Player1은 Player 클래스 인스턴스의 이름입니다.

for event in pygame.event.get(): 

    if event.type == QUIT: 
     pygame.quit() 
     sys.exit() 
    if event.type == KEYDOWN: 
     if event.key == K_RIGHT: 
      Player1.moveright = 1 
     if event.key == K_LEFT: 
      Player1.moveleft = 1 
    if event.type == KEYUP: 
     if event.key == K_RIGHT: 
      Player1.moveright = 0 
     if event.key == K_LEFT: 
      Player1.moveleft = 0 

플레이어가 화면에서 벗어나지 않도록 확인을 추가합니다.

플레이어의 움직임이 이제 게임의 요구 사항에 맞게 완료되었습니다.

플레이어의 업데이트() 기능을 호출하여 적과 화면을 뒤집습니다.

Player1.update(time_passed) 
<blit background image or color here> 
screen.blit(<image_name>, (Player1.x, <PlayerYPosition>)) 
for enemy in Enemylist: 
    enemy.update(time_passed) 
    screen.blit(<image_name>, (enemy.x, enemy.y)) 
count += 1 
pygame.display.update() 

이제 충돌 체크를 추가하여 게임을 완료하십시오. 또한 화면을 벗어난 인스턴스를 제거하여 메모리를 절약 할 수 있습니다.

0

프로그램을 복잡하게 만들지 않으려면 풍선과 나사에 대한 수업이 필요합니다. 플레이어에 대한 것입니다 첫 번째 클래스는, 당신은 왼쪽에서 오른쪽으로 이동 가정, 다음과 같이 표시됩니다 코드의

class Player(pygame.sprite.Sprite): 
    def __init__(self, image_file, location): 
     pygame.sprite.Sprite.__init__(self) 
     self.image = pygame.image.load(image_file) 
     self.rect = pygame.image.get_rect() 
     self.rect.top, self.rect.left = location 

이 작품은 충돌 탐지를위한 준비, 당신의 풍선 스프라이트를 만들 것입니다. 귀하의 나사 '클래스는 클래스의 __init__ 부분에 추가 movelocation 기능과 speed로, 유사합니다

class Screws(pygame.sprite.Sprite): 
    def __init__(self, image_file, left, speed): 
     pygame.sprite.Sprite.__init__(self) 
     self.image = pygame.image.load(image_file) 
     self.rect = pygame.image.get_rect() 
     self.rect.top = 50 
     self.rect.left = left 
     self.speed = speed 

    def move(self): 
     self.rect = self.rect.move(self.speed) 

이 클래스는 나사도 스프라이트, 탐지를위한 준비를합니다. 클래스 섹션이 끝납니다. 이제이 스프라이트 그룹 등 :에

balloon = Player('/users/Gaming/Desktop/rsz_baloon.png', [a, b])  
screw = Screws('/users/Gaming/Desktop/rsz_screw_png3029.png', random.randint(0, <ScreenSize>), c) 
ScrewGroup = pygame.sprite.Group() 

는 다시 한번, 변수는 변경하지만 c 높은는 빠른 나사가 떨어질 것입니다. ab은 풍선의 위치를 ​​결정하고 random.randint()은 나사의 위치를 ​​결정합니다. self.rect.top은 이것을 rect의 "상단"위치의 위치로 사용하여 위치를 찾는 방법입니다. 이 경우에도 동일하게 유지됩니다. self.rect.left과 동일하지만 rect의 "왼쪽"면의 위치입니다. 지금 벌룬의 가동부 가고, UP 및 DOWN (피로감) 키의 과도한 압박을 방지 직후 코드의 다음 행을 추가 활성화 각 KEYDOWNis 밀리 초 량이

delay = 100 
interval = 50 
pygame.key.set_repeat(delay, interval) 
on = True 
screwy = 0 

delay 인 interval은 반복되는 KEYDOWN을 시작할 때까지 기다리는 시간 (밀리 초)입니다. 이것은 사용자로 하여금 오른쪽 화살표 키를 계속 누르고 있으면 풍선이 원하는 방향으로 계속 진행할 수 있도록 도와줍니다. onscrewy 변수에 대해서는 다음 절에서 설명합니다. 다음으로, while 루프가 거의이다

while True: 
    screen.blit(balloon.image, balloon.rect) 
    while int(screwy - 1) > -1: 
     screen.blit(screw.image, screw.rect) 
    pygame.display.flip() 

screwy의 그 수만큼 값으로 루프만큼 나사 스폰하면서 - 1 -1보다 작다 (부 1) . 또한 화면에 "트랙"이 표시되지 않도록 화면을 뒤집습니다. 이제 풍선의 이동 부분 :

for event in pygame.event.get(): 
    #Remember to do this : from pygame.locals import *# 
    if event.type == QUIT: 
     on = False 
     #Remember to import sys!# 
     sys.exit() 
    elif event.type == pygame.KEYDOWN: 
     if event.key = K_LEFT: 
      balloon.rect.left -= 30 
     elif event.key == K_RIGHT: 
      #This can only work if (width_of_the_picture - a) is equal to 30# 
      balloon.rect.left += int(width_of_the_picture - a) 

이 당신이 풍선을 이동할 수 있습니다 (당신은 진정한 비디오 게임처럼 움직이는 풍선을 kepp 아래로 키를 저장할 수 있습니다). (같은 self.rect.top 값이 현실적인 보이게하기 위해)이 임의의 장소에서 나사를 생성합니다

if screwy < 10: 
    ScrewGroup.append(Screws('/users/Gaming/Desktop/rsz_screw_png3029.png', random.randint(0, b), [0, 15])) 
    screwy += 1 

: 다음은 나사의 지속적인 산란 될 것입니다. b은이 경우 화면 너비와 같습니다. 마지막으로, 스프라이트 감지 :

if pygame.sprite.spritecollide(balloon, ScrewGroup, True):  
    on = False 
    sys.exit() 
    pass 

풍선이 나사와 충돌했는지를 감지합니다. 그것이 사실이라면 잘 결정할 수 있습니다. while 루프를 종료하고 프로그램을 종료하면 프로그램을 종료 할 수 있습니다.그러나 print 'Game Over!과 같은 것을하려는 경우 on = False/sys.exit()을 수행하기 전에 해당 라인을 추가하면 즉시 루프/프로그램이 종료됩니다. 당신은 이미지를 다시 블럭 전송하고 화면의 출구가 매끄럽게 (pygame.quit)를 허용해야합니다

screen.fill([255, 255, 255]) 
    screen.blit(balloon.image, balloon.rect) 
    while int(screwy - 1) > -1: 
     screen.blit(screw) 
    pygame.display.flip() 
pygame.quit() 

는 while 루프 또는 것입니다 즉시이 사라 화면 밖에서 pygame.quit()을 넣어해야합니다. 물론 풍선이 화면에서 나가지 않도록 일부 코드를 만드십시오. 이에를 keyDown 부분 변경을 수행해야합니다 바로 1 회/왼쪽으로가는 풍선이 부분적으로 화면을 잎 만드는 경우

elif event.type == pygame.KEYDOWN: 
    if event.key == K_LEFT: 
     if int(balloon.rect.left) - 30 < 0: 
      pass 
     elif int(balloon.rect.left) - 30 >= 0: 
      balloon.rect.left -= 30 
    elif event.key == K_RIGHT: 
     if int(balloon.rect.left) + (<Width_OF_Balloon> - a) > <Width_OF_Screen>: 
      pass 
     elif int(balloon.rect.left) + (<Width_OF_Balloon> - a) <= <Width_OF_Screen>: 
      #This can only work if (<Width_OF_Balloon> - a) is equal to 30# 
      baloon.rect.left + (<Width_OF_Balloon> - a) 

, 프로그램은 바로 pass으로 아무것도하지 않고하여 풍선이/왼쪽으로 이동을 허용하지 않습니다. 이렇게하면 프로그램이 크게 향상되고 질문에 대한 답변을 얻을 수 있습니다. 이게 너를 돕기를 바란다.