Начинающий Pygame, результаты не обновляются / переменные не найдены

Итак, чтобы предисловие к этому, я студент педагогического факультета, чьим второстепенным является информатика. Моя основная задача - не кодирование, и, возможно, я сделал здесь несколько больших ошибок, которых еще не видел. Моя текущая проблема заключается в том, что я получаю сообщение об ошибке

"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  

Каждый раз, когда я пытаюсь запустить эту игру. Я знаю, что в настоящее время она загружается, но я запускаю ее на спешно собранной виртуальной машине. Насколько мне известно, я назвал свой рейтинг 1 / оценка 2 переменной прилично хорошо.

Цель того, что я пытаюсь сделать, - обновить счет по углам, когда мяч ударяется о стену. В настоящее время это находится в разделе def move.

Вот как выглядит мой экран, когда я пытаюсь запустить эту программу

Всем спасибо, что заглянули!

  # 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 

главный()


person Dylan Johns    schedule 28.10.2016    source источник
comment
Game.score2 = Game.score2 + 1 сидит в шаре, где у него нет доступа к игре, которая в любом случае не является переменной.   -  person Jeremy Kahan    schedule 28.10.2016
comment
так что см. stackoverflow.com/questions / 10791588 / о том, как позволить мячу найти своего родителя и таким образом увеличить счет.   -  person Jeremy Kahan    schedule 28.10.2016


Ответы (1)


Проблемная строка - это (в вашем заданном коде):

Game.score2 = Game.score2 + 1

В этой строке есть две ошибки:

  • Во-первых, вы пытаетесь использовать несуществующую переменную. Game - это имя класса, который вы определили, вы должны создать новый Game объект и присвоить его переменной, прежде чем его можно будет использовать. Я вижу, что у вас есть, что подводит меня к проблеме 2 ...
  • Сфера. Вы определили переменную game в функции main. Однако эта переменная будет создана локально. К нему нельзя получить доступ нигде, кроме функции, в которой он был определен (за некоторыми исключениями). Я рекомендую прочитать этот ответ stackoverflow, чтобы немного лучше понять объем.

score1 и score2 определены в классе Games. В функции main (строка 12) создается новый объект Games, который назначается переменной games. Эта переменная является локальной, и к ней можно получить доступ только в функции main.

Теперь у вас есть 2 варианта. Первый вариант - полностью удалить переменные score1 и score2 из класса Games и сделать их отдельными переменными, определенными в основной части программы. Это позволит получить к ним доступ где угодно (очевидно, вам придется изменить любые ссылки на 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

Надеюсь, я объяснил это достаточно ясно. Я бы действительно рекомендовал прочитать, как области видимости и классы работают в python, прежде чем углубляться в pygame.

person Inazuma    schedule 28.10.2016
comment
Не беспокойтесь, я отредактировал свой ответ, чтобы он был немного полезнее. Надеюсь, это будет иметь смысл. - person Inazuma; 28.10.2016