доработка игры на pygame с использованием pyQt5

Еще раз здравствуйте, продолжаю дорабатывать игру 'Машинка и тракторы'. На этот раз решил добавить чуток интерфейса. Должна выводиться Qt форма, а после нажатия на кнопку - форма pygame.

Но они выводятся обе сразу. И непонятно, почему. Надеюсь на помощь.

from PyQt5 import QtCore, QtGui, QtWidgets
from igra import Ui_Form
import pygame, sys, time, random 
from pygame.locals import *

# Create application
app = QtWidgets.QApplication(sys.argv)
def okno():
    #Вывод окна
    sys.exit(app.exec_())
    pygame.display.update()
    mainClock.tick(40 ) 

#Create form and init UI
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
pygame.init()
mainClock = pygame.time.Clock()

# Настройка окна
WINDOWWIDTH = 1000
WINDOWHEIGHT = 1000
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Спрайты и звуки')

# Настройка цвета
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)

# Создание структур данных блока
car = pygame.Rect(500, 300, 40, 40)
count = 0
imageCarLeft = pygame.image.load('carL.gif')
carLStretchedImage = pygame.transform.scale(imageCarLeft, (40, 40))
foodImage = pygame.image.load('90695.jpg')
foodCounter = 0
NEWFOOD = 40
FOODSIZE = 20
foods = []
for i in range(20):
    foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 20), random.randint(0, WINDOWHEIGHT - 20), 20, 20))

# создание переменных клавиатуры
moveLeft = False
moveRight = False
moveUp = False
moveDown = False

MOVESPEED = 6

#Настройка музыки
avaria = pygame.mixer.Sound('avaria.wav')
tractor = pygame.mixer.Sound('tractor.wav')
pygame.mixer.music.load('dvigatel.wav')
pygame.mixer.music.play(-1, 0.0)
musicPlaying = True

# Запуск игрового цикла
while True:
    # проверка событий
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            #Изменение переменных клавиатуры
            if event.key == K_LEFT or event.key == K_a:
                moveRight = False
                moveLeft = True

            if event.key == K_RIGHT or event.key == K_d:
                moveLeft = False
                moveRight = True

            if event.key == K_UP or event.key == K_w:
                moveDown = False
                moveUp = True

            if event.key == K_DOWN or event.key == K_s:
                moveUp = False
                moveDown = True

        if event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()
            if event.key == K_LEFT or event.key == K_a:
                moveLeft = False
            if event.key == K_RIGHT or event.key == K_d:
                moveRight = False
            if event.key == K_UP or event.key == K_w:
                moveUp = False
            if event.key == K_DOWN or event.key == K_s:
                moveDown = False
            if event.key == K_x:
                car.top = random.randint(0, WINDOWHEIGHT - car.height)
                car.left = random.randint(0, WINDOWWIDTH - car.width)
            if event.key == K_m:
                if music.playing:
                    pygame.mixer.music.stop()
                else:
                    pygame.mixer.music.play(-1, 0.0)
                musicPlaying = not musicPlaying

        if event.type == MOUSEBUTTONUP:
            foods.append(pygame.Rect(event.pos[0] - 10, event.pos[1] - 10, 20, 20))


    if foodCounter <= NEWFOOD:
     # Добавление новой "еды"
     foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 20), random.randint(0, WINDOWHEIGHT - 20), 20, 20))
     foodCounter += 1

    #Создание белого фона
    windowSurface.fill(WHITE)

    #Перемещение игрока
    if moveDown and car.bottom < WINDOWHEIGHT:
        car.top += MOVESPEED
    if moveUp and car.top > 0:
        car.top -= MOVESPEED
    if moveLeft and car.left > 0:
        car.left -= MOVESPEED
    if moveRight and car.right < WINDOWWIDTH:
        car.right += MOVESPEED
    if moveDown and car.bottom == WINDOWHEIGHT:
        avaria.play
    if moveUp and car.top == 0:
        avaria.play
    if moveLeft and car.left == 0:
        avaria.play
    if moveRight and car.right == WINDOWWIDTH:
        avaria.play


    windowSurface.blit(carLStretchedImage, car)
    # Проверка, не пересекся ли игрок с блоками "еды".
    for food in foods[:]:
        if car.colliderect(food) and event.type == KEYDOWN:
            if event.key == K_SPACE:
                foods.remove(food)
                foodCounter -= 1
                if musicPlaying:

                    tractor.play()
                    tractorS = True

                    if tractorS == True:
                            tractor.stop()
                            tractor.play()


    for food in foods:
        windowSurface.blit(foodImage, food)
    ui.pushButton.clicked.connect(okno)


import sys
from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(604, 595)
        Form.setStyleSheet("QPushButton{\n"
"    background-color: white;\n"
"    width: 75px;\n"
"    height: 50px;\n"
"    font-size: 14px;\n"
"    font-weight: bold;\n"
"    border: none;\n"
"    text-align: center;\n"
"}\n"
"QPushButton:hover{\n"
"    background-color: silver;\n"
"}\n"
"QPushButton:pressed{\n"
"    background-color: red;\n"
"}\n"
"QLabel{\n"
"    background-color:white;\n"
"    text-align: center;\n"
"}\n"
"QWidget{\n"
"    background-color: white;\n"
"}")
        self.verticalLayoutWidget = QtWidgets.QWidget(Form)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 230, 601, 171))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.pushButton = QtWidgets.QPushButton(self.verticalLayoutWidget)
        font = QtGui.QFont()
        font.setFamily("Kozuka Mincho Pro R")
        font.setPointSize(-1)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName("pushButton")
        self.verticalLayout.addWidget(self.pushButton)
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(110, 70, 251, 81))
        font = QtGui.QFont()
        font.setFamily("GrilledCheese BTN Toasted")
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(Form)
        self.label_2.setGeometry(QtCore.QRect(6, 412, 141, 61))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(Form)
        self.label_3.setGeometry(QtCore.QRect(150, 440, 21, 16))
        self.label_3.setObjectName("label_3")
        self.label_4 = QtWidgets.QLabel(Form)
        self.label_4.setGeometry(QtCore.QRect(180, 440, 101, 21))
        self.label_4.setObjectName("label_4")
        self.label_5 = QtWidgets.QLabel(Form)
        self.label_5.setGeometry(QtCore.QRect(0, 480, 211, 51))
        self.label_5.setObjectName("label_5")
        self.label_6 = QtWidgets.QLabel(Form)
        self.label_6.setGeometry(QtCore.QRect(210, 500, 21, 16))
        self.label_6.setObjectName("label_6")
        self.label_7 = QtWidgets.QLabel(Form)
        self.label_7.setGeometry(QtCore.QRect(240, 500, 81, 21))
        self.label_7.setObjectName("label_7")
        self.label_8 = QtWidgets.QLabel(Form)
        self.label_8.setGeometry(QtCore.QRect(170, 410, 231, 20))
        font = QtGui.QFont()
        font.setFamily("Muller Heavy")
        font.setBold(True)
        font.setWeight(75)
        self.label_8.setFont(font)
        self.label_8.setObjectName("label_8")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.pushButton.setText(_translate("Form", "НАЧАТЬ ИГРУ"))
        self.label.setText(_translate("Form", "        МАШИНКА             И          ТРАКТОРЫ"))
        self.label_2.setText(_translate("Form", "               SPACE"))
        self.label_3.setText(_translate("Form", "-----"))
        self.label_4.setText(_translate("Form", "Шугать тракторы"))
        self.label_5.setText(_translate("Form", "    AWSD или стрелки на клавиатуре"))
        self.label_6.setText(_translate("Form", "-------"))
        self.label_7.setText(_translate("Form", "  Движение"))
        self.label_8.setText(_translate("Form", "                            УПРАВЛЕНИЕ"))


if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

Все файлы тут - https://yadi.sk/d/srMDGjW9Xg6Jlg


Ответы (1 шт):

Автор решения: S. Nick

я отметил для вас строки, которые изменил, добавил, удалил. Пробуйте.

import sys
import time
import random
from PyQt5 import QtCore, QtGui, QtWidgets
import pygame
from pygame.locals import *

#from igra import Ui_Form
class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("form")
        Form.resize(604, 595)
        Form.setStyleSheet("QPushButton{\n"
"    background-color: white;\n"
"    width: 75px;\n"
"    height: 50px;\n"
"    font-size: 14px;\n"
"    font-weight: bold;\n"
"    border: none;\n"
"    text-align: center;\n"
"}\n"
"QPushButton:hover{\n"
"    background-color: silver;\n"
"}\n"
"QPushButton:pressed{\n"
"    background-color: red;\n"
"}\n"
"QLabel{\n"
"    background-color:white;\n"
"    text-align: center;\n"
"}\n"
"QWidget{\n"
"    background-color: white;\n"
"}")
        self.verticalLayoutWidget = QtWidgets.QWidget(Form)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 230, 601, 171))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.pushButton = QtWidgets.QPushButton(self.verticalLayoutWidget)
        font = QtGui.QFont()
        font.setFamily("Kozuka Mincho Pro R")
# ?       font.setPointSize(-1)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName("pushButton")
        self.verticalLayout.addWidget(self.pushButton)
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(110, 70, 251, 81))
        font = QtGui.QFont()
        font.setFamily("GrilledCheese BTN Toasted")
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(Form)
        self.label_2.setGeometry(QtCore.QRect(6, 412, 141, 61))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(Form)
        self.label_3.setGeometry(QtCore.QRect(150, 440, 21, 16))
        self.label_3.setObjectName("label_3")
        self.label_4 = QtWidgets.QLabel(Form)
        self.label_4.setGeometry(QtCore.QRect(180, 440, 101, 21))
        self.label_4.setObjectName("label_4")
        self.label_5 = QtWidgets.QLabel(Form)
        self.label_5.setGeometry(QtCore.QRect(0, 480, 211, 51))
        self.label_5.setObjectName("label_5")
        self.label_6 = QtWidgets.QLabel(Form)
        self.label_6.setGeometry(QtCore.QRect(210, 500, 21, 16))
        self.label_6.setObjectName("label_6")
        self.label_7 = QtWidgets.QLabel(Form)
        self.label_7.setGeometry(QtCore.QRect(240, 500, 81, 21))
        self.label_7.setObjectName("label_7")
        self.label_8 = QtWidgets.QLabel(Form)
        self.label_8.setGeometry(QtCore.QRect(170, 410, 231, 20))
        font = QtGui.QFont()
        font.setFamily("Muller Heavy")
        font.setBold(True)
        font.setWeight(75)
        self.label_8.setFont(font)
        self.label_8.setObjectName("label_8")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.pushButton.setText(_translate("Form", "НАЧАТЬ ИГРУ"))
        self.label.setText(_translate("Form", "        МАШИНКА             И          ТРАКТОРЫ"))
        self.label_2.setText(_translate("Form", "               SPACE"))
        self.label_3.setText(_translate("Form", "-----"))
        self.label_4.setText(_translate("Form", "Шугать тракторы"))
        self.label_5.setText(_translate("Form", "    AWSD или стрелки на клавиатуре"))
        self.label_6.setText(_translate("Form", "-------"))
        self.label_7.setText(_translate("Form", "  Движение"))
        self.label_8.setText(_translate("Form", "                            УПРАВЛЕНИЕ"))


# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
# Create application
class Form(QtWidgets.QWidget):
    def __init__(self):
        super(Form, self).__init__()
#Create form and init UI
#Form = QtWidgets.QWidget()
        ui = Ui_Form()
        ui.setupUi(self)
        ui.pushButton.clicked.connect(self.okno)
#Form.show()

    def okno(self):
        #Вывод окна
#        sys.exit(app.exec_())
        self.hide()
        pyGame()
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


def pyGame():
    pygame.init()
    mainClock = pygame.time.Clock()

    # Настройка окна
    WINDOWWIDTH = 1000
    WINDOWHEIGHT = 1000
    windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
    pygame.display.set_caption('Спрайты и звуки')

    # Настройка цвета
    WHITE = (255, 255, 255)
    GREEN = (0, 255, 0)

    # Создание структур данных блока
    car = pygame.Rect(500, 300, 40, 40)
    count = 0
    imageCarLeft = pygame.image.load('wolf.gif')                 # поставьте свои carL.gif
    carLStretchedImage = pygame.transform.scale(imageCarLeft, (40, 40))
    foodImage = pygame.image.load('shot5.jpg')                   # поставьте свои 90695.jpg
    foodCounter = 0
    NEWFOOD = 40
    FOODSIZE = 20
    foods = []
    for i in range(20):
        foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 20), random.randint(0, WINDOWHEIGHT - 20), 20, 20))

    # создание переменных клавиатуры
    moveLeft = False
    moveRight = False
    moveUp = False
    moveDown = False

    MOVESPEED = 6

    #Настройка музыки
    avaria = pygame.mixer.Sound('no.wav')                      # поставьте свои .wav
    tractor = pygame.mixer.Sound('no.wav')
    pygame.mixer.music.load('no.wav')
    pygame.mixer.music.play(-1, 0.0)
    musicPlaying = True

    # Запуск игрового цикла
    while True:
        mainClock.tick(40 )                                      # +

        # проверка событий
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == KEYDOWN:
                #Изменение переменных клавиатуры
                if event.key == K_LEFT or event.key == K_a:
                    moveRight = False
                    moveLeft = True

                if event.key == K_RIGHT or event.key == K_d:
                    moveLeft = False
                    moveRight = True

                if event.key == K_UP or event.key == K_w:
                    moveDown = False
                    moveUp = True

                if event.key == K_DOWN or event.key == K_s:
                    moveUp = False
                    moveDown = True

            if event.type == KEYUP:
                if event.key == K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                if event.key == K_LEFT or event.key == K_a:
                    moveLeft = False
                if event.key == K_RIGHT or event.key == K_d:
                    moveRight = False
                if event.key == K_UP or event.key == K_w:
                    moveUp = False
                if event.key == K_DOWN or event.key == K_s:
                    moveDown = False
                if event.key == K_x:
                    car.top = random.randint(0, WINDOWHEIGHT - car.height)
                    car.left = random.randint(0, WINDOWWIDTH - car.width)
                if event.key == K_m:
                    if music.playing:
                        pygame.mixer.music.stop()
                    else:
                        pygame.mixer.music.play(-1, 0.0)
                    musicPlaying = not musicPlaying

            if event.type == MOUSEBUTTONUP:
                foods.append(pygame.Rect(event.pos[0] - 10, event.pos[1] - 10, 20, 20))


        if foodCounter <= NEWFOOD:
         # Добавление новой "еды"
         foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 20), random.randint(0, WINDOWHEIGHT - 20), 20, 20))
         foodCounter += 1

        #Создание белого фона
        windowSurface.fill(WHITE)

        #Перемещение игрока
        if moveDown and car.bottom < WINDOWHEIGHT:
            car.top += MOVESPEED
        if moveUp and car.top > 0:
            car.top -= MOVESPEED
        if moveLeft and car.left > 0:
            car.left -= MOVESPEED
        if moveRight and car.right < WINDOWWIDTH:
            car.right += MOVESPEED
        if moveDown and car.bottom == WINDOWHEIGHT:
            avaria.play
        if moveUp and car.top == 0:
            avaria.play
        if moveLeft and car.left == 0:
            avaria.play
        if moveRight and car.right == WINDOWWIDTH:
            avaria.play

        windowSurface.blit(carLStretchedImage, car)
        # Проверка, не пересекся ли игрок с блоками "еды".
        for food in foods[:]:
            if car.colliderect(food) and event.type == KEYDOWN:
                if event.key == K_SPACE:
                    foods.remove(food)
                    foodCounter -= 1
                    if musicPlaying:

                        tractor.play()
                        tractorS = True

                        if tractorS == True:
                                tractor.stop()
                                tractor.play()

        for food in foods:
            windowSurface.blit(foodImage, food)
#            ui.pushButton.clicked.connect(okno)     # -

        pygame.display.update()                      # +


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    w = Form()
    w.show()
    sys.exit(app.exec_())

введите сюда описание изображения

→ Ссылка