python - 我的 pygame 俄罗斯方 block 游戏总是卡住

标签 python pygame tetris

我是一个初学者Python程序员,我正在尝试制作一个俄罗斯方 block 游戏。当我运行游戏时,方 block 每秒向下移动 10 像素。问题是, block 随机停止,我的打印语句也停止打印。我没有收到错误,根据任务管理器的说法,内存没问题。我有带有赛扬处理器的 Vista 32 位,但我也在带有 i5 处理器的 Windows 7 上尝试过,问题仍然存在,所以我迷路了。

这是代码:

import pygame
from pygame.locals import *
from datetime import datetime
import Blocks

def Gravity(Box, rate):

    # Gravity effect
    Box.set_yCoor(Box.get_yCoor()+ rate)
    Box.Edge.set_yCoor(Box.Edge.get_yCoor()+ rate)
    return Box


def main():
    # initailize all pygame modules
    pygame.init()

    windowWidth,windowHeight= 640,700
    screen_color= (255,255,255)

    # Determines how many pixels per time the box will fall
    gravity= 10

    # Create screen/window and change color to white
    screen= pygame.display.set_mode((windowWidth,windowHeight),0,32)
    screen.fill(screen_color)

    # Used to determine whether to draw box and apply gravity
    index =0

    # Put box and border info in list
    # Args: (x,y) (len, width) (color)
    boxInfo= [10,10, 20,50, (0,0,0)]
    borderInfo= [5,5, 30,60, (154,24,214)]
    # Create instance of box and pass info
    Box= Blocks.Box(boxInfo, borderInfo)

    #Create an endless loop that the game will run inside of
    while True:
        for event in pygame.event.get():
            if event.type== QUIT:
                pygame.quit()
                return

        # Get second and millisecond time and convert to string
        startTime= str(datetime.now())
        # Splice time string and convert to float
        startTime= float(startTime[17:23])

        if index== 0:
            # Pull the box down by gravity
            Box= Gravity(Box, gravity)

            # Move box back to the top of window
            if Box.Edge.get_yCoor() > windowHeight - Box.Edge.get_boxWid():
                Box.Edge.set_yCoor(5)
                Box.set_yCoor(10)

            # Clear screen
            screen.fill(screen_color)
            # Display Screen
            Box.display(screen)
            # Set the stop time used to determine when to call gravity and display
            stopTime= startTime+ 1
            index= 1

            # Get second and millisecond time and convert to string
            bug= str(datetime.now())
            # Splice time string and convert to float
            bug= bug[17:23]

            print("\nDisplayed at:")
            print('Start:', startTime)
            print('Stop:', stopTime)
            print('Bug:', bug)
        elif startTime >= stopTime:
            index= 0
            # Get second and millisecond time and convert to string
            bug= str(datetime.now())
            # Splice time string and convert to float
            bug= bug[17:26]

            print("\nNot displaying at:")
            print('Start:', startTime)
            print('Stop:', stopTime)
            print('Bug:', bug)


# Call main
main()

这是 block 类: 导入pygame 从 pygame.locals 导入 *

class Box():

    def __init__(self, boxInfo, edgeInfo):
        # Pixel location of the box
        self.__xCoor= boxInfo[0]
        self.__yCoor= boxInfo[1]

        # Pixel length and width of the box
        self.__boxLen= boxInfo[2]
        self.__boxWid= boxInfo[3]

        # Pixel color is white by default
        self.__color= boxInfo[4]

        self.Edge= Border(edgeInfo)

    # ---- ACCESSORS -- and -- MUTATORS ----

    def set_xCoor(self,Coordx):
        self.__xCoor= Coordx

    def get_xCoor(self):
        return self.__xCoor

    def set_yCoor(self,Coordy):
        self.__yCoor= Coordy

    def get_yCoor(self):
        return self.__yCoor

    def set_boxLen(self,Length):
        self.__boxLen= Length

    def get_boxLen(self):
        return self.__boxLen

    def set_boxWid(self,Width):
        self.__boxWid= Width

    def get_boxWid(self):
        return self.__boxWid

    def set_color(self,color):
        self.__color= color

    def get_color(self):
        return self.__color

    # ---- METHODS ----

    def boxStatCheck(self):
        # Prints all the attributes in the shell for debug
        print("x-Coordinate=", self.get_xCoor())
        print("y-Coordinate=", self.get_yCoor())
        print("Box Length=", self.get_boxLen())
        print("Box Width=", self.get_boxWid())
        print("Color Value=", self.get_color())


    def display(self, screen):
        screen.lock()
        pygame.draw.rect(screen, self.Edge.get_color(), Rect((self.Edge.get_xCoor(),self.Edge.get_yCoor()),
                                                        (self.Edge.get_boxLen(),self.Edge.get_boxWid())))

        pygame.draw.rect(screen, self.get_color(), Rect((self.get_xCoor(),self.get_yCoor()),
                                                        (self.get_boxLen(),self.get_boxWid())))
        screen.unlock()
        pygame.display.update()


class Border():

    def __init__(self, listInfo):
        # Pixel location of the box
        self.__xCoor= listInfo[0]
        self.__yCoor= listInfo[1]

        # Pixel length and width of the box
        self.__boxLen= listInfo[2]
        self.__boxWid= listInfo[3]

        # Pixel color is white by default
        self.__color= listInfo[4]

    # ---- ACCESSORS -- and -- MUTATORS ----

    def set_xCoor(self,Coordx):
        self.__xCoor= Coordx

    def get_xCoor(self):
        return self.__xCoor

    def set_yCoor(self,Coordy):
        self.__yCoor= Coordy

    def get_yCoor(self):
        return self.__yCoor

    def set_boxLen(self,Length):
        self.__boxLen= Length

    def get_boxLen(self):
        return self.__boxLen

    def set_boxWid(self,Width):
        self.__boxWid= Width

    def get_boxWid(self):
        return self.__boxWid

    def set_color(self,color):
        self.__color= color

    def get_color(self):
        return self.__color

    # ---- METHODS ----

    def boxStatCheck(self):
        # Prints all the attributes in the shell for debug
        print("x-Coordinate=", self.get_xCoor())
        print("y-Coordinate=", self.get_yCoor())
        print("Box Length=", self.get_boxLen())
        print("Box Width=", self.get_boxWid())
        print("Color Value=", self.get_color())


    def display(self, screen):
        pygame.draw.rect(screen, self.get_color(), Rect((self.get_xCoor(),self.get_yCoor()),
                                                        (self.get_boxLen(),self.get_boxWid())))

最佳答案

我认为你的问题在于如何使用日期时间来控制何时向下移动 block 。

您应该查看 pygame.time 模块。我建议您创建一个变量(例如 Wanted_fps),其中包含一个整数,表示您希望无限循环每秒运行的频率。 您的代码应该如下所示:

wanted_fps = 1 # how often I want the endless loop to run per second
fpsHandler = pygame.time.Clock() # fpsHandler created to handle fps

while(True): # our endless loop
    # do something awesome
    fpsHandler.tick(wanted_fps) # makes sure fps isn't higher than wanted_fps

您可以在这里阅读有关 pygame.time 的信息: http://www.pygame.org/docs/ref/time.html

此外,如果您想要看似没有事件处理延迟,您可以将 Wanted_fps 设置为 60 之类的值,然后创建某种计数器变量(例如 mycounter)来处理您希望某件事发生的频率。假设您在无限循环中做了类似的事情:

# handle events
if mycounter > 0:
    mycounter -= 1
else:
    # do something amazing
    mycounter = 30

你每秒做一些令人惊奇的事情 60/30=2 次,但你每秒处理事件 60 次,因此你可以看似立即响应事件。

关于python - 我的 pygame 俄罗斯方 block 游戏总是卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16655465/

相关文章:

python - Ubuntu 完全删除不是 Anaconda 的 python

python - Vim - 如何在 python shell 中运行当前的 python3 文件?

python - 导入 python-igraph 时出错

python - Pygame圆碰撞?

python - 如何在pygame中添加一个具有我原始图像形状的白色表面?

python - 列表索引超出范围,我不明白为什么?

java - 使用 Stacks 的类似俄罗斯方 block 的小程序——从顶部弹出

python - mypy 泛型可以表示将返回序列类型作为参数传递吗?

JavaScript 俄罗斯方 block 在移动和旋转后分开

python - 俄罗斯方 block 从 block 生成彩色形状