2016-05-28 1 views
0

Как я могу получить правильный табло в «Понге», используя pygame? Я пробовал много раз, но на табло показывает только мне 0 и 1.Как я могу получить правильный табло в «Понге», используя pygame?

Вот мой код:

import pygame, sys, time 
from pygame.locals import * 

def main(): 
# Initialize pygame 
    pygame.init() 

    # Set window size and title, and frame delay 
    surfaceSize = (500, 400) # example window size 
    windowTitle = 'Pong' # Window title is called 'Pong' 
    frameDelay = 0.02 # smaller is faster game 

    # Create the window 
    surface = pygame.display.set_mode(surfaceSize, 0, 0) 
    pygame.display.set_caption(windowTitle) 

    # create and initialize objects 
    gameOver = False 
    # Set center 
    center = [250, 200] 
    # Ball/Score/Paddle color 
    color = pygame.Color('white') 
    # Set ball radius to 5 
    ball_radius = 5 
    # Set speed to [4, 1] 
    ball_speed = [4, 1] 
    # Set the size of the left paddle 
    left_paddle = pygame.Rect(90, 180, 10, 40) 
    # Set the size of the right paddle 
    right_paddle = pygame.Rect(410, 180, 10, 40) 
    # Set left score to 0 
    left_score = 0 
    # Set right score to 0 
    right_score = 0 


    # Draw the small ball 
    pygame.draw.circle(surface, color, center, ball_radius, 0) 
    # Draw the left paddle 
    pygame.draw.rect(surface, color, left_paddle) 
    # Draw the right paddle 
    pygame.draw.rect(surface, color, right_paddle) 


    # Refresh the display 
    pygame.display.update() 

    # Loop forever 
    while True: 
     # Check event 
     event = pygame.event.poll() 
     if event.type == QUIT: 
      pygame.quit() 
      sys.exit() 
     # Handle additional events 

     # Update and draw objects for the next frame 
     gameOver = update(center,surface,ball_speed,color,ball_radius, 
      left_paddle,right_paddle) 

     # Refresh the display 
     pygame.display.update() 

     # Set the frame speed by pausing between frames 
     time.sleep(frameDelay) 

def update(center,surface,ball_speed,color,ball_radius, 
      left_paddle,right_paddle): 
    # Check if the game is over. If so, end the game and 
    # return True. Otherwise, update the game objects, draw 
    # them, and return False. 
    # This is an example update function - replace it. 
    # - center is a list containing the x and y int coords 
    # of the center of a circle 
    # - surface is the pygame.Surface object for the window 
    if False: # check if the game is over 
     return True 
    else: # continue the game 
     # Erase the old one 
     bgColor = pygame.Color('black') 
     surface.fill(bgColor) 

     # Move 
     moveDot(surface,center, ball_speed,ball_radius,right_paddle,left_paddle) 
     pygame.draw.circle(surface, color, center, ball_radius) 
     paddles(surface, color, left_paddle, right_paddle) 
     drawScore(surface,center,ball_radius,right_score, left_score) 
     return False 

def moveDot(surface,center, ball_speed,ball_radius,right_paddle,left_paddle): 
    size = surface.get_size() 
    for coord in range(0, 2): 
     center[coord] = center[coord] + ball_speed[coord] 
     # Left edge or the top edge 
     if center[coord] < ball_radius: 
      ball_speed[coord] = -ball_speed[coord] 
     # Right edge or the bottom edge 
     if center[coord] + ball_radius > size[coord]: 
      ball_speed[coord] = -ball_speed[coord] 
     # Left paddle bounce and go through 
     if left_paddle.collidepoint(center) and ball_speed[0] < 0: 
      ball_speed[0] = -ball_speed[0] 
     # Right paddle bounce and go through 
     if right_paddle.collidepoint(center) and ball_speed[0] > 0: 
      ball_speed[0] = -ball_speed[0] 

def paddles(surface,color,left_paddle,right_paddle): 
    pygame.draw.rect(surface, color, left_paddle) 
    pygame.draw.rect(surface, color, right_paddle) 

Проблема здесь

def drawScore(surface,center,ball_radius,right_score,left_score): 
    fgColor = pygame.Color('white') 
    bgColor = pygame.Color('black') 
    font = pygame.font.SysFont(None,80,True) 
    left_location = (0,0) 
    right_location = (465,0)  
    size = surface.get_size() 
    if center[0] < ball_radius: 
     right_score = right_score + 1  
    right_textSurface = font.render(str(right_score),True,fgColor,bgColor) 
    surface.blit(right_textSurface,right_location)   
    if center[0] > size[0] - ball_radius:  
     left_score = left_score + 1  
    left_textSurface = font.render(str(left_score),True,fgColor,bgColor) 
    surface.blit(left_textSurface,left_location) 

main() 
+1

Вы уверены, что ваш фрагмент кода _minimal_, как это определено в [MCVE]? –

+2

Или, по крайней мере, скопируйте/отпечатайте отсюда до IDE и выполнитесь. Я предложил редактировать, чтобы сделать полный c/p компилируемым. – AK47

+0

Вы можете скопировать и вставить эти фрагменты в Wing IDE, я просто не хочу, чтобы мой код выглядел так долго – Steven

ответ

1

Вы перезаписать параметры и не фактический счет в игре

def drawScore(...,right_score,left_score): # given here 
    ... 
    if center[0] < ball_radius: 
     right_score = right_score + 1 # updated, but only locally 
    ... 
    if center[0] > size[0] - ball_radius:  
     left_score = left_score + 1  # updated, but only locally 
    ... 

Эти новые значения ЕЭС не сохраняются, когда метод вызывается снова, и поэтому вы видите только 0 или 1.


Если вы хотите сохранить состояние игры, объявить эти переменные за пределами локальной области видимости.

import pygame, sys, time 
from pygame.locals import * 

left_score = 0 
right_score = 0 

def main(): 
    ... 
    # remove score definition here 

И вы тогда не нужно передавать эти результаты как параметры,

def drawScore(...): # remove the scores 
    global left_score, right_score 
    ... 
    if center[0] < ball_radius: 
     right_score = right_score + 1 # accessed from global scope 
    ... 
    if center[0] > size[0] - ball_radius:  
     left_score = left_score + 1 # accessed from global scope 
    ... 
+0

Спасибо, что помогли мне, но мой код не будет работать. Я следую вашему пути, чтобы изменить свой код, и Wing IDE показывает мне ошибку: локальная переменная «right_score», на которую ссылаются до назначения – Steven

+0

@Steven Я думаю, что забыл «глобальную» линию. Я обновил ответ –

+0

Большое вам спасибо. Он работает так хорошо !!!!! – Steven