Пытаясь вернуть мяч в середину после того, как мяч покинул экран - PullRequest
4 голосов
/ 23 января 2020

Я пытаюсь воссоздать игру в понг просто для удовольствия.

Вот мой полный код на данный момент.

import pygame, random, math

pygame.init()

#colours:-------------------------------------------------------------
R = random.randrange(1,255)
B = random.randrange(1,255)
G = random.randrange(1,255)
WHITE = (255, 255, 255)
GREEN = (39, 133, 20)
YELLOW = (252, 252, 25)
BLACK = (0, 0, 0)
BLUE = (30, 100, 225)
RED = (255,0,0)
RANDOM_COLOR = (R, B, G)

#Surface:-------------------------------------------------------------
width = 700
height = 600
size = (width, height)
screen = pygame.display.set_mode(size)
screen_rect = screen.get_rect()

pygame.display.set_caption("Pong Remake")

background = pygame.image.load("background.png").convert()
background = pygame.transform.scale(background, (width, height))

logo = pygame.image.load("logo.png").convert()
logo.set_colorkey((BLACK))
credits = pygame.image.load("credits.png")
credits.set_colorkey((BLACK))

#variables:-----------------------------------------------------------
clock = pygame.time.Clock()
done = False
text = pygame.font.Font(None,25)
display_instructions = True
instruction_page = 1
start_font = pygame.font.Font("C:\Windows\Fonts\BAUHS93.TTF", 35)
instruction_font = pygame.font.Font(None, 17)
win_lose_font = pygame.font.Font("C:\Windows\Fonts\BAUHS93.TTF",50)
score = pygame.font.Font(None, 100)
bounce = pygame.mixer.Sound("bounce.wav")
playerOne_score = 0
playerTwo_score = 0

playerOne = ""
playerTwo = ""
x = 350
y = 300

ball_rect = pygame.Rect(x,y,10,10)
paddleOne_rect = pygame.Rect(10, 250, 20, 60)
paddleTwo_rect = pygame.Rect(670, 250, 20, 60)

x_speed = random.randrange(5, 10)
y_speed = random.randrange(5,10)

def draw_background(screen, pic, x,y):
    screen.blit(pic, (x,y))


#main loop


    #INPUT v ---------------------------------------------------------
    #Start Page
while not done and display_instructions:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.MOUSEBUTTONDOWN:
            instruction_page += 1
            if instruction_page == 2:
                display_instructions = False
        #Shows the start of the page
    if instruction_page == 1:
            draw_background(screen, logo, 100,-150)  
            draw_background(screen, credits, 100,50)
            instruction_text = instruction_font.render("How to Play. The objective to this game is to score the ball on the other side before the opponent can.", False, WHITE)
            instruction_text_three = instruction_font.render("First Player to get 10 points wins, Have Fun and Good Luck!", False, WHITE)
            instruction_text_two = instruction_font.render("For Player One, use the a and the z keys to move up and down, For Player Two, use the k and m keys.", False, WHITE)
            continue_text= start_font.render("Click to Play...",True, WHITE)


            screen.blit(continue_text, [200, 400])
            screen.blit(instruction_text, [0,500])
            screen.blit(instruction_text_three, [0,532])
            screen.blit(instruction_text_two,[0,516])

    if instruction_page == 2:
        display_instructions = False


    clock.tick(60)

    pygame.display.flip()

while not done:
    click = False

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.MOUSEBUTTONDOWN:
            click = True




    #INPUT ^ =========================================================



    #PROCESS v -------------------------------------------------------
    str(playerOne_score)
    str(playerTwo_score)
    scoreOne = text.render("Player One:" + str(playerOne_score), False, WHITE)
    scoreTwo = text.render("Player Two:" + str(playerTwo_score), False, WHITE)
    #moves paddles with keys on keyboar
    key = pygame.key.get_pressed()
    if key[pygame.K_a]: paddleOne_rect.move_ip(0, -10)
    if key[pygame.K_z]: paddleOne_rect.move_ip(0, 10)
    if key[pygame.K_k]: paddleTwo_rect.move_ip(0, -10)
    if key[pygame.K_m]: paddleTwo_rect.move_ip(0, 10)

    #makes sure paddles stay on screen
    paddleOne_rect.clamp_ip(screen_rect)
    paddleTwo_rect.clamp_ip(screen_rect)    
    ball_rect.move_ip(x_speed, y_speed)


    if ball_rect.y  + ball_rect.height> screen_rect.height or ball_rect.y < 0:
        y_speed = y_speed * -1
        bounce.play()

    if ball_rect.collidelist([paddleOne_rect, paddleTwo_rect]) > -1:
        x_speed = -x_speed
        R = random.randrange(1,255)
        B = random.randrange(1,255)
        G = random.randrange(1,255)
        bounce.play()

    if ball_rect.x >= 700:        
        x_speed * -1
        playerOne_score += 1
        pygame.display.flip

    if ball_rect.x <= 0:
        x_speed * -1
        playerTwo_score += 1







    #PROCESS ^ =======================================================
    #DRAWING GOES BELOW HERE v ------------------------------------
    draw_background(screen, background, 0,0)
    screen.blit(scoreOne, (0,0))
    screen.blit(scoreTwo, (500,0))
    pygame.draw.ellipse(screen, WHITE,ball_rect )
    pygame.draw.rect(screen,RANDOM_COLOR, paddleOne_rect)
    pygame.draw.rect(screen,RANDOM_COLOR, paddleTwo_rect)    
    pygame.draw.line(screen, WHITE, (350,0),(350,700), 1)

    #DRAWING GOES ABOVE HERE ^ ------------------------------------





    pygame.display.flip()
    clock.tick(60)


pygame.quit()

С чем у меня сейчас проблемы в в тот момент, когда мяч уходит с экрана, я хочу, чтобы он снова вернулся в центр go, когда кто-то набрал очко. Но я немного застрял в том, что делать.

Если вы, ребята, сможете мне помочь, это было бы потрясающе !!

1 Ответ

2 голосов
/ 23 января 2020

Здесь много кода, поэтому он не соответствует указанным вами c переменным, но я надеюсь, что это поможет.

1) Найдите ширину экрана

2) Возьмите координаты x и y, которые вы используете, чтобы знать, где рисовать шарик

3) Сделайте оператор if, который по существу говорит (псевдокод)

if x > 1000
  score1 += 1
  x = 500
if x < 0
  score2 += 1
  x = 500
``
I hope this can set you on the right track, and I suggest checking out the pygame docs.
Cheers!
...