2014-03-26 2 views
-3

파이 게임에서 파이 게임을 사용하여 게임을 개발 중입니다. 다음을 수행 할 수있는 코드가 있어야합니다. 크기가 800 * 800이라고 말하는 화면을 만듭니다. 고정 크기 30 * 30 크기의 화면 사각형이 오른쪽에서 나타나고 왼쪽으로 천천히 이동합니다. 그들이 왼쪽 벽과 충돌하자마자 사라집니다. 직사각형은 임의 높이와 고정 속도로 와야합니다. 이 내가 뭘하려 :파이 게임을 사용하여 임의의 오브젝트 만들기

import pygame, sys 
from pygame.locals import * 
addrect = 0 
addrect_rate = 40 
rectangles = [] 
while True: 
    for r in rectangles: 
     addrect += 1 
     if addrect == addrect_rate: 
      addect = 0 
      newrect = {'rect': pygame.Rect(40, 40, 10, 10), 
         'speed': rect_speed, 
         'image': pygame.draw.rect((50, 50), 10, 10) 
         } 
    for r in rectangles: 
     rectangles.append(newrect) 

기본적인 방법이있다. 화면을 그려서 코드 완성을 도와 주시고이 작업을하십시오. 감사합니다.

+4

스택 오버플로에 오신 것을 환영합니다! 우리가 당신을 위해 몇 가지 코드를 작성하기를 원하는 것처럼 보입니다. 대부분의 사용자는 곤경에 처한 코더 코드를 기꺼이 만들지 만 일반적으로 포스터가 이미 문제를 해결하려고 시도했을 때만 도움이됩니다. 이러한 노력을 입증하는 좋은 방법은 지금까지 작성한 코드, 예제 입력 (있는 경우), 예상 출력 및 실제로 얻은 출력 (콘솔 출력, 스택 추적, 컴파일러 오류 등)을 포함시키는 것입니다. 응용할 수 있는). 더 자세하게 제공할수록 더 많은 답변을받을 수 있습니다. [FAQ]와 [ask]를 확인하십시오 – Ffisegydd

+0

편집 된 질문에서, 제가 정말로하고 싶은 샘플을 포함 시켰습니다. 도움이 도움이됩니다. – user3456011

+0

기술적으로 말하면 여전히 코드를 작성하도록 요청하는 중입니다. – KodyVanRy

답변

0

코드를 추가해 주셔서 감사합니다. 나는 파이 게임에 익숙하지 않았기 때문에 그것을 끝내는 방법을 알아 내기 위해 다시 써야했다. 나는 각 부분이 무엇을하는지 명확하게하기 위해 충분한 주석을 달았습니다.

파이 게임을 사용하는 방법에 대해 더 자세히 배우고 싶다면 programarcadegame의 "introduction to sprites"을 사용하여이 작업을 수행하는 방법을 파악할 수 있습니다.

공차 유럽 박스 제비

import random 

import pygame 

# create a screen of size say 800 * 800. 
screen_width, screen_height = 800, 800 
pygame.init() 
pygame.display.set_caption('Unladen European Box Swallows') 
screen = pygame.display.set_mode((800, 800)) 

# On the screen rectangles of a fixed size of 30*30... 
BLACK, WHITE = (0, 0, 0), (255, 255, 255) 
swallows = pygame.sprite.Group() 
class Swallow(pygame.sprite.Sprite): 
    def __init__(self, width=30, height=30, x=0, y=0, color=WHITE): 
     #super(Swallow, self).__init__() # this is for python 2.x users 
     super().__init__() 
     # self.image and self.rect required for sprite.Group.draw() 
     self.image = pygame.Surface((width, height)) 
     self.image.fill(color) 
     self.rect = self.image.get_rect() 
     self.x_subpixel = x 
     self.y_subpixel = y 

    # subpixel required for constant movement rate per second 
    @property 
    def x_subpixel(self): 
     return self._x_subpixel 
    @x_subpixel.setter 
    def x_subpixel(self, new_x): 
     self._x_subpixel = new_x 
     self.rect.x = int(round(new_x)) 
    @property 
    def y_subpixel(self): 
     return self._y_subpixel 
    @y_subpixel.setter 
    def y_subpixel(self, new_y): 
     self._y_subpixel = new_y 
     self.rect.y = int(round(new_y)) 


chance_to_appear = 0.01 
airspeed_velocity = 100 
clock = pygame.time.Clock() 
done = False 
while not done: 
    ticks = clock.tick(60) 
    # ...appear from the right [at random heights]... 
    if random.random() < chance_to_appear: 
     swallow = Swallow(x=screen_width, y=random.randrange(screen_height)) 
     swallows.add(swallow) 
    # ...[and fixed speed] 
    for swallow in swallows: 
     swallow.x_subpixel -= float(airspeed_velocity) * ticks/1000 
    # as soon as they collide with the left wall, they disappear. 
    for swallow in swallows: 
     if swallow.x_subpixel <= 0: 
      swallows.remove(swallow) 
    # do regular pygame stuff 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      done = True 
    screen.fill(BLACK) 
    swallows.draw(screen) # Group.draw uses each .image and .rect to draw 
    pygame.display.flip() 
pygame.quit() 

다음 시간

추신 제발 StackOverflow에 대한 미래의 답변을 위해이 많은 코드 생성을 기대하지 마십시오. 나는이 일을하는 경험을 원했다. 나는 그것이 당신을 돕기를 바랍니다. 앞으로는 더 좋은 답변과 더 많은 표를 얻기 위해 성공적인 질문을 쓸 때 this kind of guide을 읽는 것이 좋습니다.

0

코드에 젖어있는 몇 가지. 무엇보다도, for 루프에서 특히 주위를 돌아 다니면서 목록에 직사각형을 추가해서는 안됩니다.

import pygame, sys, random 
from pygame.locals import * 
pygame.init() 
surface = pygame.display.set_mode((400,400)) 
addrect = 0 addrect_rate = 40 
rectangles = [] 
while True: 
    addrect += 1 
    if addrect == addrect_rate: 
     # also wrong!!! You are using a pygame call in a dict newrect = {'rect': pygame.Rect(40, 40, 10, 10), 'speed': rect_speed, 'image': pygame.draw.rect((50, 50), 10, 10) } 
     newrect = {'rect': pygame.Rect(40, random.randint(1,400), 10, 10), 'speed': rect_speed } 
    for r in rectangles: 
     r['rect'].x += r['speed'] 
     pygame.draw.rect(surface, (255,0,0) r['rect']) 
    #wrong 
    #for r in rectangles: 
     #addrect += 1 
     #if addrect == addrect_rate: 
      #addect = 0 
      #newrect = {'rect': pygame.Rect(40, 40, 10, 10), 'speed': rect_speed, 'image': pygame.draw.rect(} 
    #for r in rectangles: 
     #rectangles.append(newrect) 
관련 문제