So we will have these 3 functions, main, main_menu, game_over, they represent different scenes of our game, for now, we will only focus on the main function or the main game logic. Now it's time to plan our core game logic, You also might have seen the CLOCK variable I declared, it just initializes () and using it, in the while loop, I used CLOCK.tick(25), which just tells pygame to run the while loop 25 times per second, you are more than welcome to change the number ╮(╯3╰)╭. Then I wrote another for loop which checks for events like mouse-clicking, hover and others, (The method () returns the events that are occurring currently, there, I am checking if event.type is equal to the event pygame.QUIT or in other words did the user click the cross button, if that's true, quit the program, else continue to run. ? In the above, I just wrote a simple infinite while loop, Now if you run the program, the window is going to stay until you press the exit button, congrats if you could follow up on this ?. exit () #using CLOCK variable mentioned above and using QUIT : #if user clicked the exit button, quit the game #which is predefined in pygame as the exit button #by checking if the event.type is pygame.QUIT get (): #here we are checking if user has clicked the exit button While 1 : #checking for events in () whichįor event in pygame. #For how many times per second our game loopĬLOCK = pygame. #The FPS or frame per second or more explicitly
set_caption ( 'snake game' ) #initializing () which controls init () WIN_X = 800 WIN_Y = 600 WIN = pygame. Import sys, random import pygame pygame. Let's go ahead and implement our game loop
As we didn't define any game loop, the window was visible for a moment, but then the program ended, and so the game screen was also gone. Ī game loop is just an infinite loop, that goes on forever until the user exits or closes it. Ĭan you guess why this happens ?, well cause we didn't define any game loop. Now if you run this code, you will see the game screen for a short time, and then it exits the program. In the end, I just set up a caption or label for the game window using _caption() method passing in the caption string, you can pass any string you want here ?. Next, we set up our game window, or tell pygame to initialize our game window with _mode() method passing in our screen dimensions in a tuple (? The reason we need this is that pygame creates a game window and we need to declare the width and height of it, you can choose any width and height, I am choosing 800圆00) We make two variables or constants, WIN_X and WIN_Y to store our screen dimensions or our screen width and screen height, We import pygame and some other local modules, then use the init method on pygame to start our game or start pygame.Enter fullscreen mode Exit fullscreen mode