Попытка сделать игру Rock Paper Scissors, используя Pygame - PullRequest
0 голосов
/ 24 марта 2020

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

import pygame
import time
pygame.init()
# Set up the drawing window
screen = pygame.display.set_mode([1000, 600])

# Run until the user asks to quit
running = True
while running:

    # Did the user click the window close button?
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    #Variables
    pygame.font.init()
    myfont = pygame.font.SysFont('Comic Sans MS', 50)
    rockColour = (0, 0, 0)
    rockLight = (100, 100, 100)
    paperColour = (255, 255, 255)
    paperColourBorder = (0,0,0)
    paperBorderLight = (100, 100, 100)
    scissorColour = (0, 0, 0)
    scissorLight = (100, 100, 100)
    P1Choice = ()
    Player1 = True
    Player2 = False
    white = (250, 250, 250)
    black = (0, 0, 0)
    #P1 Text
    textsurface = myfont.render('Player 1', False, black)
    screen.blit(textsurface,(400,25))
    # Fill the background with white
    screen.fill(white)
    #mouse
    mousepos = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    mouseclick = click [0]
    mouserock = 125+150 > mousepos [0] > 125 and 225+150 > mousepos [1] > 225
    mousepaper = 400+150 > mousepos [0] > 400 and 225+150 > mousepos [1] > 225
    mousescissors = 850 > mousepos [0] > 700 and 375 > mousepos [1] > 255
    #ICONS UPDATES
    if Player1 == True and Player2 == False:
        if mouserock == True:
            pygame.draw.circle(screen,rockColour, (200, 300), (75))
            textsurface = myfont.render('ROCK', False, black)
            screen.blit(textsurface,(137,150))
        else:
            pygame.draw.circle(screen,rockLight, (200, 300), (75))


        if mousepaper == True:
            pygame.draw.rect(screen,paperColourBorder, (400, 225, 150, 150))
            pygame.draw.rect(screen,paperColour, (410, 235, 130, 130))
            textsurface = myfont.render('PAPER', False, black)
            screen.blit(textsurface,(400,150))
        else:
            pygame.draw.rect(screen,paperBorderLight, (400, 225, 150, 150))
            pygame.draw.rect(screen,paperColour, (410, 235, 130, 130))
        if mousescissors == True:
            pygame.draw.line(screen, scissorColour, (700,375), (850,225), 20)
            pygame.draw.line(screen, scissorColour, (850,375), (700,225), 20)
            textsurface = myfont.render('SCISSORS', False, black)
            screen.blit(textsurface,(635,150))
        else:
           pygame.draw.line(screen, scissorLight, (700,375), (850,225), 20)
           pygame.draw.line(screen, scissorLight, (850,375), (700,225), 20)

    #MouseClick
        if mouserock == True and mouseclick == 1:
            Player1 = False
            Player2 = True

        if 400+150 > mousepos [0] > 400 and 225+150 > mousepos [1] > 225 and click [0] == 1:
            P1Choice = ("paper")

        if 850 > mousepos [0] > 700 and 375 > mousepos [1] > 255 and click [0] == 1:
            P1Choice = ("scissor")
        #Player 1 text
        if Player1 == False and Player2 == True:
            textsurface = myfont.render('Player 1', False, (255, 255, 255))
            screen.blit(textsurface,(400,25))
            textsurface = myfont.render('Player 2', False, (0, 0, 0))
            screen.blit(textsurface,(400,25))    


    #Flip the display
    pygame.display.flip()

    # Done! Time to quit.
pygame.quit()

Ответы [ 2 ]

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

Хорошо, так что сначала все эти переменные должны быть глобальными, а не в основной игре l oop (поэтому переменные должны быть выше во время работы), в противном случае, когда вы увеличиваете их, а затем возвращаетесь через l oop, они все будет сброшено к исходному состоянию, и l oop продолжит действовать на них. Без почти свободного sh перезапуска или серьезного редактирования я не могу просто показать вам все, что вам нужно сделать, чтобы сделать эту работу. Я хотел бы предложить выбрать учебник, в котором вы узнаете, как создать другую игру, изучить синтаксис и детали, необходимые для создания игры, а затем вернуться к своей игре RPS, как только вы поймете, какие части необходимы для функционирования вашей игры

0 голосов
/ 25 марта 2020

Как указывает @ Pmac1687, код переустанавливает все переменные состояния внутри главной l oop, поэтому состояние теряется при каждой итерации l oop.

Кроме того, код не получать отдельные события мыши, но полагаться на текущее состояние мыши. Это может l oop через код "click-has-случился" много раз прежде, чем медленный человек отпустит кнопку мыши. Изменение этого параметра на событие исправляет это.

Порядок отображения на экране тоже немного неправильный. Некоторые вещи выводятся на экран прямо перед тем, как он будет заполнен белым.

В любом случае, я немного перестроил код и добавил обработку события для мыши. Компоновка экрана и щелчки, кажется, делают кое-что сейчас. Надеюсь, это немного подтолкнет вас в правильном направлении.

import pygame
import time
pygame.init()
# Set up the drawing window
screen = pygame.display.set_mode([1000, 600])

#Variables
pygame.font.init()
myfont = pygame.font.SysFont('Comic Sans MS', 50)
rockColour = (0, 0, 0)
rockLight = (100, 100, 100)
paperColour = (255, 255, 255)
paperColourBorder = (0,0,0)
paperBorderLight = (100, 100, 100)
scissorColour = (0, 0, 0)
scissorLight = (100, 100, 100)
P1Choice = ()
Player1 = True
Player2 = False
white = (250, 250, 250)
black = (0, 0, 0)

# Run until the user asks to quit
running = True
while running:

    mouseclick    = False  # reset all these
    mouserock     = False
    mousepaper    = False
    mousescissors = False
    click         = [ False, False ]   # Mouse button clicks

    for event in pygame.event.get():
        # Did the user click the window close button?
        if event.type == pygame.QUIT:
            running = False

        elif ( event.type == pygame.MOUSEBUTTONDOWN ):
            mouseclick = True
            mousepos = pygame.mouse.get_pos()
            click[ event.button-1 ] = True    # which button was pressed
            mouserock = 125+150 > mousepos [0] > 125 and 225+150 > mousepos [1] > 225
            mousepaper = 400+150 > mousepos [0] > 400 and 225+150 > mousepos [1] > 225
            mousescissors = 850 > mousepos [0] > 700 and 375 > mousepos [1] > 255

            if 400+150 > mousepos [0] > 400 and 225+150 > mousepos [1] > 225 and click [0] == 1:
                P1Choice = ("paper")
            if 850 > mousepos [0] > 700 and 375 > mousepos [1] > 255 and click [0] == 1:
                P1Choice = ("scissor")

    # Fill the background with white
    screen.fill(white)

    #P1 Text
    textsurface = myfont.render('Player 1', False, black)
    screen.blit(textsurface,(400,25))

    #mouse
    #ICONS UPDATES
    if Player1 == True and Player2 == False:
        if mouserock == True:
            pygame.draw.circle(screen,rockColour, (200, 300), (75))
            textsurface = myfont.render('ROCK', False, black)
            screen.blit(textsurface,(137,150))
        else:
            pygame.draw.circle(screen,rockLight, (200, 300), (75))

        if mousepaper == True:
            pygame.draw.rect(screen,paperColourBorder, (400, 225, 150, 150))
            pygame.draw.rect(screen,paperColour, (410, 235, 130, 130))
            textsurface = myfont.render('PAPER', False, black)
            screen.blit(textsurface,(400,150))
        else:
            pygame.draw.rect(screen,paperBorderLight, (400, 225, 150, 150))
            pygame.draw.rect(screen,paperColour, (410, 235, 130, 130))
        if mousescissors == True:
            pygame.draw.line(screen, scissorColour, (700,375), (850,225), 20)
            pygame.draw.line(screen, scissorColour, (850,375), (700,225), 20)
            textsurface = myfont.render('SCISSORS', False, black)
            screen.blit(textsurface,(635,150))
        else:
           pygame.draw.line(screen, scissorLight, (700,375), (850,225), 20)
           pygame.draw.line(screen, scissorLight, (850,375), (700,225), 20)

    #MouseClick
        if mouserock == True and mouseclick == 1:
            Player1 = False
            Player2 = True

        #Player 1 text
        if Player1 == False and Player2 == True:
            textsurface = myfont.render('Player 1', False, (255, 255, 255))
            screen.blit(textsurface,(400,25))
            textsurface = myfont.render('Player 2', False, (0, 0, 0))
            screen.blit(textsurface,(400,25))    


    #Flip the display
    pygame.display.flip()

    # Done! Time to quit.
pygame.quit()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...