I am following a tutorial to understand pygame. In this game i just set background color, and draw a image of ship and also handle events to manage position of ship (image). My code works properly in static screen size but gives blank screen when i try to open in full screen mode. Here is the properly working code for AlienInvasion class
class AlienInvasion:
def __init__(self):
pg.init()
self.settings = Settings()
self.screen = pg.display.set_mode((self.settings.width, self.settings.height))
# width and height are static value 1366 and 768
pg.display.set_caption('Pygame')
self.ship = Ship(self)
self.x = float(self.ship.rect.x)
self.move_right = False
self.move_left = False
def run_game(self):
while True:
self._check_events()
self.update()
self._update_screen()
# Function to manage events
def _check_events(self):
for event in pg.event.get():
if(event.type == pg.QUIT):
sys.exit()
elif(event.type == pg.KEYDOWN):
self._check_keydown_events(event)
elif(event.type == pg.KEYUP):
self._check_keyup_events(event)
# manage key down events
def _check_keydown_events(self, event):
if(event.key == pg.K_RIGHT):
self.move_right = True
elif(event.key == pg.K_LEFT):
self.move_left = True
elif(event.key == pg.K_q):
sys.exit()
# manage key up enevts
def _check_keyup_events(self, event):
if(event.key == pg.K_RIGHT):
self.move_right = False
elif(event.key == pg.K_LEFT):
self.move_left = False
# Update position of image object
def update(self):
if(self.move_right and self.ship.rect.right < self.ship.screen_rect.right):
self.x += self.settings.ship_speed
elif(self.move_left and self.ship.rect.left > 0):
self.x -= self.settings.ship_speed
self.ship.rect.x = self.x
# Actual Function that set background and display image object
def _update_screen(self):
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
pg.display.flip()
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
Code for Settings class
class Settings:
def __init__(self):
self.width = 1366
self.height = 768
self.bg_color = (230, 230, 230)
self.ship_speed = 1.5
Code for Ship class
class Ship:
def __init__(self, ai_game):
self.screen = ai_game.screen
self.screen_rect = ai_game.screen.get_rect()
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
self.rect.midbottom = self.screen_rect.midbottom
def blitme(self):
a = self.screen.blit(self.image, (self.rect[0], self.rect[1] - 70))
Here is the updated code of AlienInvasion.init function to open in full screen mode
def __init__(self):
pg.init()
self.settings = Settings()
# Updated lines start
self.screen = pg.display.set_mode((0, 0), pg.FULLSCREEN)
self.settings.width = self.screen.get_rect().width
self.settings.height = self.screen.get_rect().height
# End Update Lines
pg.display.set_caption('Pygame')
self.ship = Ship(self)
self.x = float(self.ship.rect.x)
self.move_right = False
self.move_left = False
Now it shows a blank black screen. I cant understand why