2016-10-28 3 views
0

그래서 이것을 서언하기 위해, 나는 미성년자가 컴퓨터 과학 인 교육 학생입니다. 제 주된 관심사는 코딩 작업이 아니기 때문에 제가 아직 보지 못했던 몇 가지 큰 실수를 저지른 것 같습니다. 현재 문제는 내가 오류를 받게됩니다.초심자 파이 게임, 업데이트되지 않음/변수를 찾을 수 없음

"Traceback (most recent call last): 
    File "/home/user/Downloads/PongV1.py", line 158, in <module> 
    main() 
    File "/home/user/Downloads/PongV1.py", line 13, in <module> 
    game.play() 
    File "/home/user/Downloads/PongV1.py", line 42, in <module> 
    self.update() 
    File "/home/user/Downloads/PongV1.py", line 77, in <module> 
    self.ball.move() 
    File "/home/user/Downloads/PongV1.py", line 136, in <module> 
    game.score2 = game.score2 + 1 
builtins.NameError: name 'game' is not defined 

이 게임을 실행하려고 할 때마다. 나는 그것이 현재 다운로드 중임을 알고 있지만, 나는 이것을 급하게 VM 기계를 조합하여 실행하고있다. 내가 아는 한, 나는 내 점수 1/점수 2 변수를 잘 호출했다.

내가하려는 일의 목표는 공이 벽에 부딪 힐 때 모서리의 점수를 업데이트하는 것입니다. 현재, 그

This is what my screen looks like when I try to run this program

보고에 대한 여러분 모두 감사합니다 데프 이동 섹션에 있습니다!

# pygame v2 

import pygame 
import uaio 
import math 
import time 
from pygame.locals import * 

# User-defined functions 
def main(): 
    surface = create_window() 
    game = Game(surface) 
    game.play() 
    pygame.quit() 

# Create window 
def create_window(): 
    pygame.init() 
    surface_size = (700,600) 
    title = 'Pong' 
    surface = pygame.display.set_mode(surface_size) 
    pygame.display.set_caption(title) 
    return surface 
# define class games 
class Game: 
    def __init__ (self, surface): 
     self.surface = surface #locations and surface colors of games 
     self.bg_color = pygame.Color('black') 
     self.pause_time = 0.01 
     self.close_clicked = False 
     self.continue_game = True 
     self.ball = Ball(pygame.Color('white'),[350,300],5,[6,2], surface) 
     self.paddle= Paddle(pygame.Color('white'),(100,300),100,100, surface) 
     self.score1 = 0 
     self.score2 = 0 

    def play(self): #playing the game while the game is not closed 
     self.draw() 
     while not self.close_clicked: 
      self.handle_event() 
      if self.continue_game: 
       self.update() 
       self.decide_continue 
      self.draw() 
      time.sleep(self.pause_time) 

def handle_event(self): #continuing the game 
    event = pygame.event.poll() 
    if event.type == QUIT: 
     self.close_clicked = True 

def draw(self): #drawing the balls and paddles 
    self.surface.fill(self.bg_color) 
    self.ball.draw() 
    self.paddle.draw() 
    self.draw_score() 
    pygame.display.update() 

def draw_score(self): 
    string = str(self.score1) 
    location = 0,0 
    size = 80 
    #fg_color = pygame.Color('white') 
    uaio.draw_string(string, self.surface,location,size) 

    string = str(self.score2) 
    location = 650,0 
    size = 80 
    #fg_color = pygame.Color('white') 
    uaio.draw_string(string, self.surface,location,size) 

def paddlecollide(self): 
    self.paddle.collide_right(x, y) 
    self.paddle.collidge_left(x, y)   

def update(self): #updating the movement of the ball 
    self.ball.move() 
    self.ball.collide(self.paddle) 


def decide_continue(self): # deciding to continue teh game 
    pass 

class Paddle: #defining paddle 

def __init__(self, color, left, width, height, surface): 
    #location of paddle etc 
    self.color = color 
    self.left = left 
    self.surface = surface 
    self.width = width 
    self.height = height 
    self.paddle1 = pygame.Rect(140,270,20,80) 
    self.paddle2 = pygame.Rect(540,270,20,80) 
    #return self.paddle1, self.paddle2 


def draw(self): 
    #drawing paddle 
    pygame.draw.rect(self.surface, self.color, self.paddle1) 
    pygame.draw.rect(self.surface, self.color, self.paddle2) 

def collide_left(self, x, y): 
    return self.paddle1.collidepoint(x, y) 

def collide_right(self, x, y): 
    return self.paddle2.collidepoint(x, y)  

class Ball: #defining ball 

def __init__(self, color, center, radius, velocity, surface): 
    #charactersitics of said ball 

    self.color = color 
    self.center = center 
    self.radius = radius 
    self.velocity = velocity 
    self.surface = surface 


def draw(self): 
    #drawing the ball 
    pygame.draw.circle(self.surface, self.color, self.center, self.radius) 

def move(self): 

    # how the ball moves as well as ist velocity 
    size = self.surface.get_size() 
    for coord in range(0, 2): 
     self.center[coord] = (self.center[coord] + self.velocity[coord]) 
     if self.center[coord] < self.radius: 
      self.velocity[coord] = -self.velocity[coord] 
      Game.score1 = Game.score1 + 1 
     if self.center[coord] + self.radius > size[coord]: 
      self.velocity[coord] = -self.velocity[coord] 
      Game.score2 = Game.score2 + 1 





def collide(self, paddles): 
    xcoord =0 
    if paddles.collide_left(self.center[0], self.center[1]): 
     self.velocity[xcoord] = -self.velocity[xcoord] 

    if paddles.collide_right(self.center[0], self.center[1]): 
     self.velocity[xcoord] = -self.velocity[xcoord]   

     #if x_velocity <= 0: 
     # collide = False 
     #  
     #else: collide = True 

주()

+0

Game.score2 = Game.score2 + 1은 Game에 대한 액세스 권한이없는 공에 앉아 있으며, 어쨌든 변수가 아닙니다. –

+0

볼이 부모를 찾고 점수를 올릴 수있게하는 방법은 http://stackoverflow.com/questions/10791588/getting-container-parent-object-from-within-python을 참조하십시오. –

답변

1

문제가있는 라인 (당신의 주어진 코드)이 하나입니다 : 첫째

  • :

    Game.score2 = Game.score2 + 1 
    

    이 줄 문제 두 가지가 있습니다 , 존재하지 않는 변수를 사용하려고합니다. Game은 사용자가 정의한 클래스의 이름입니다. 새 Game 개체를 만들고이를 사용하기 전에 변수에 할당해야합니다. 나는 당신이 가지고있는 것을보고 문제 2로 나를 인도한다 ...

  • 범위. 함수 main에 변수 game을 정의했습니다. 그러나이 변수는 로컬로으로 생성됩니다. 이 함수는 정의 된 함수가 아닌 다른 곳에서는 액세스 할 수 없습니다 (예외가 있음). 나는 범위를 조금 더 잘 이해하기 위해 this stackoverflow 대답을 읽는 것이 좋습니다.

score1score2은 모두 Games 클래스 내에 정의된다. main 함수 (12 행)에 새 Games 객체가 만들어지고 변수 games에 할당됩니다. 이 변수는 로컬 변수이며 main 함수 내에서만 액세스 할 수 있습니다.

이제 두 가지 옵션이 있습니다. 첫 번째 옵션은 Games 클래스에서 score1score2 변수를 모두 제거하고 프로그램의 본문에 정의 된 별도의 변수로 사용하는 것입니다. 이것은 그들 어디서나 액세스 할 수 있도록 것입니다 (분명히 당신이 game.score1 또는 game.score2.

두 번째 참조를 변경해야 할 것이며, 내 의견 바람직 옵션에 변수 game 전역 변수하게하는 것입니다.당신의 main 기능으로, 코드는 다음과 같습니다

def main(): 
    surface = create_window() 
    global game 
    game = Game(surface) 
    game.play() 
    pygame.quit() 

를 그런 다음 변수 game를 사용하는 것을, 그래서 거짓말, 그래서 당신의 main 기능의 외부 Game 클래스에 대한 참조를 해제 대문자로 기억 :

Game.score1 = Game.score1 + 1 

내가이 충분히 명확하게 설명하겠습니다

game.score1 = game.score1 + 1 

된다. 파이 게임에서 너무 멀리 파고 들기 전에 범위와 클래스가 파이썬에서 어떻게 작동하는지에 대해 읽어 볼 것을 권합니다.

+0

걱정할 필요없이 조금 더 도움이 될 내 대답을 편집했습니다. 희망적으로 말이 될 것입니다. – Inazuma

+0

고챠, 고마워! 그것은 많이 도움이 될 것입니다! –