У меня проблемы с тем, чтобы весла оставались на экране? - PullRequest
1 голос
/ 01 марта 2020

Я пытаюсь заставить весла двигаться вверх и вниз: 1 прямоугольник. перемещение с помощью клавиш w / a / s / d 2 прямоугольника. со стрелками У меня проблемы с тем, чтобы манипуляторы оставались на экране?

Вы сделаете две «лопасти» (т.е. прямоугольники), одну на левой стороне и одну на правой стороне экрана. Эти прямоугольники должны быть выше их ширины (т.е. выглядеть как весло из игры в понг). Лопатка слева должна иметь возможность перемещаться вверх и вниз с помощью клавиш w и s, весло справа должно двигаться вверх и вниз с помощью клавиш со стрелками вверх и вниз. Оба весла не должны покидать верхнюю или нижнюю часть экрана. (* для этого задания вы просто создаете весла и заставляете их двигаться правильно, без шариков). Старайтесь избегать жестко закодированных значений.

# import the necessary modules
import pygame
import sys

#initialize pygame
pygame.init()

# set the size for the surface (screen)
screen_h = 800
screen_w = 600

screen = pygame.display.set_mode((screen_h,screen_w),0)

# set the caption for the screen
pygame.display.set_caption("Template")

# define colours you will be using
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
YELLOW = (255,255,0)

#initialize variables for player
#variables for first rectangle
R1x = 740
R1y = 300
R1w = 50
R1h = 132
R1dx = 0
R1dy = 0

#variables for second rectangle
R2x = 10
R2y = 300
R2w = 50
R2h = 132
R2dx = 0
R2dy = 0

#speed
speed = 3

screen.fill(BLACK)

# set main loop to True so it will run
main = True
# main loop
while main:
    for event in pygame.event.get(): # check for any events (i.e key press, mouse click etc.)
        if event.type ==pygame.QUIT: # check to see if it was "x" at top right of screen
            main = False         # set the "main" variable to False to exit while loop
        if event.type ==pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                R1dx = 0
                R1dy = -speed
            elif event.key == pygame.K_DOWN:
                R1dx = 0
                R1dy = speed
            if event.key == pygame.K_w:
                R2dx = 0
                R2dy = -speed
            elif event.key == pygame.K_s:
                R2dx = 0
                R2dy = speed
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                R1dx = 0
                R1dy = 0
            elif event.key == pygame.K_w or event.key == pygame.K_s:
                R2dx = 0
                R2dy = 0


    # move the x and y positions of the rectangles
    oldR1x = R1x
    oldR1y = R1y

    R1x = R1x + R1dx
    R1y = R1y + R1dy

    if R1x >= screen_w-50:
        R1x = oldR1x
        R1y = oldR1y
    if R1x<= 50:
        R1x = oldR1x
        R1y = oldR1y
    if R1y>= screen_h-50:
        R1x = oldR1x
        R1y = oldR1y
    if R1y<= 50:
        R1x = oldR1x
        R1y = oldR1y

    # draw the shapes, in this case the blue rectangles
    pygame.draw.rect(screen, WHITE,(R1x, R1y, R1w, R1h),0)
    pygame.draw.rect(screen, WHITE,(R2x, R2y, R2w, R2h),0)

    # we are using .flip() here,  it basically works the same as .update()
    # we will discuss this more in class (you can use either one)
    pygame.display.flip()

# quit pygame and exit the program (i.e. close everything down)
pygame.quit()
sys.exit()

1 Ответ

1 голос
/ 01 марта 2020

Прежде всего вы поменяли местами ширину экрана (screen_w) и высоту экрана (screen_h). Это должно быть:

# set the size for the surface (screen)
screen_w = 800
screen_h = 600

screen = pygame.display.set_mode((screen_w,screen_h),0)

Лопатки перемещаются только вверх вниз, поэтому достаточно ограничить координату y pddels диапазоном [0, screen_h-R1h]. Обратите внимание, R1y соответственно R2y - это верхняя координата весла:

R1y = max(0, min(screen_h-R1h, R1y + R1dy))
R2y = max(0, min(screen_h-R2h, R2y + R2dy))

Кроме того, экран должен быть очищен в главном приложении l oop (screen.fill(BLACK)):

while main:
    for event in pygame.event.get(): # check for any events (i.e key press, mouse click etc.)
        if event.type ==pygame.QUIT: # check to see if it was "x" at top right of screen
            main = False         # set the "main" variable to False to exit while loop
        if event.type ==pygame.KEYDOWN:
            # [...]

    # move the x and y positions of the rectangles
    R1y = max(0, min(screen_h-R1h, R1y + R1dy))
    R2y = max(0, min(screen_h-R2h, R2y + R2dy))

    # clear screen
    screen.fill(BLACK)

    # draw the shapes, in this case the blue rectangles
    pygame.draw.rect(screen, WHITE,(R1x, R1y, R1w, R1h),0)
    pygame.draw.rect(screen, WHITE,(R2x, R2y, R2w, R2h),0)

    # we are using .flip() here,  it basically works the same as .update()
    # we will discuss this more in class (you can use either one)
    pygame.display.flip()

Обратите внимание, что если лопасти будут перемещаться также вдоль оси x (влево, вправо), то ограничение координаты x будет аналогичным:

R1x = max(0, min(screen_w-R1w, R1x + R1dx))
R2x = max(0, min(screen_w-R2w, R2x + R2dx))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...