Pygame Side Scroller - python

I've written my code and whenever I run it, I expect for it to open up the screen with the background but instead nothing happens at all. I don't know where I went wrong or what I did wrong.
My code:
import os.path
import sys
import pygame
from settings import Settings
class Slingshot_Adventures:
def __init__(self):
"""Initialize the game, and create game resources."""
pygame.init()
self.screen = pygame.display.set_mode((1280, 720))
pygame.display.set_caption('Slingshot Adventures')
self.bg_color = (0, 0, 0)
bg = pygame.image.load_basic(os.path.join('Final/bg.bmp'))
def run_game(self):
while True:
# Watch for keyboard and mouse events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# Redraw the screen during each pass through the loop.
self.screen.fill(self.bg_color)
# Make the most recently drawn screen visible.
pygame.display.flip()
if __name__ == '__main__':
# Make a game instance, and run the game.
ai = Slingshot_Adventures()
ai.run_game

You have set the local variable bg in the constructor of the class Slingshot_Adventures, but you did not set the attribute self.bg:
bg = pygame.image.load_basic(os.path.join('Final/bg.bmp'))
self.bg = pygame.image.load_basic(os.path.join('Final/bg.bmp'))

class Slingshot_Adventures:
def __init__(self):
"""Initialize the game, and create game resources."""
pygame.init()
self.screen = pygame.display.set_mode((1280, 720))
pygame.display.set_caption('Slingshot Adventures')
self.bg_color = (0, 0, 0)
#put your path to the image here
self.image = pygame.image.load(r"path/to/your/image.png")
def run_game(self):
while True:
# Watch for keyboard and mouse events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# Redraw the screen during each pass through the loop.
self.screen.fill(self.bg_color)
self.screen.blit(self.image, (0, 0))
# Make the most recently drawn screen visible.
pygame.display.flip()
if __name__ == '__main__':
# Make a game instance, and run the game.
ai = Slingshot_Adventures()
ai.run_game()

Related

How can I call my image up from desktop or folder in Python?

import pygame
import sys
from time import sleep
BLACK = (0, 0, 0)
padWidth = 480 # Width of game screen
padHeight = 640 # Height of game screen
def initGame():
global gamePad, clock, background
pygame.init()
gamePad = pygame.display.set_mode((padWidth, padHeight))
pygame.display.set_caption('SPACE INVADERS') # Title of game
background = pygame.image.load('background.png')
clock = pygame.time.Clock()
def runGame():
global gamepad, clock, background
onGame = False
while not onGame:
for event in pygame.event.get():
if event.type in [pygame.QUIT]: # Quit game program
pygame.quit()
sys.exit()
gamePad.fill(BLACK) #game screen is black
pygame.display.update() #draw game screen
clock.tick(60) # Frame per second of game screen
pygame.quit() # QUit game
initGame()
runGame()
This is my code for game screen, for inserting background, I used pygame.image.load('file name'). But the background image doesn't pop up, and it says FileNotFoundError: No such file or directory. The image file is on both my desktop and folder, and I didn't type the different file name. What should I do?
Did you try to use the path of the file instead of just the file name?

Why isnt anything showing for me except the background in the pygame window

Here's the code. I have both images correctly named in the same folder, so thats not the issue. Both the runner.png and the rectangle for the button don't show, but the background does.
class gamewindow():
def __init__(self):
pygame.init()
self.game = pygame.display.set_mode((1300, 768))
background = pygame.image.load('temporarybackground.jpg')
self.green = (1,255,1)
self.buttonstart = pygame.draw.rect(self.game, self.green,(100,100, 20, 20))
self.runner = pygame.image.load('runner.png')
from sys import exit
while True:
self.game.fill((0,0,0))
self.game.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
pygame.display.flip()
JasonHarper's comment is correct. You're not drawing the button or runner in the loop. When you redraw the background, the other objects are erased.
Corrected code:
class gamewindow():
def __init__(self):
pygame.init()
self.game = pygame.display.set_mode((1300, 768))
background = pygame.image.load('temporarybackground.jpg')
self.green = (1,255,1)
self.runner = pygame.image.load('runner.png')
from sys import exit
while True:
self.game.fill((0,0,0)) # clear screen
self.game.blit(background, (0, 0)) # draw background
self.game.blit(self.runner, (50, 0)) # draw runner
pygame.draw.rect(self.game, self.green,(100,100, 20, 20)) # draw button
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
pygame.display.flip()
You also have your game code in a class constructor, which seems odd. It may be better to put your game in a standard function.

Python crash course doesn't run with no errors

I just get the general "finished with exit code 0" Not sure why its not printing the screen anymore. What would cause this?
If anyone has any input as to why this would be, i'd very much appreciate it so i can move forward & finish the project!
From what ive read, its hard to go on without knowing what actually is causing the "none-error"
import sys
import pygame
from settings import Settings
from ship import Ship
class Alieninvasion:
"""overall class to manage game assets & behaviors"""
def __init__(self):
"""initialize the game & create game resources"""
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode(
(self.settings.screen_width, self.settings.screen_height))
self.screen = pygame.display.set_mode((1000, 600)) # the self.screen portion makes it available in all methods in the class
pygame.display.set_caption("Alien Invasion!!!") # the self.settings & self.screen can possibly replace the
# screen & bg_color that doesn't include the settings syntax
self.ship = Ship(self)
# set the background color
self.bg_color = (230, 230, 230)
def run_game(self):
"""starting the main loop for the game"""
while True:
self._check_events()
self.update_screen()
# redraw the screen during each pass through the loop
self.screen.fill(self.bg_color)
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
def _check_events(self):
"""responds to keypresses & mouse events"""
for event in pygame.event.get():
if event.type == pygame.QUIT():
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key ==pygame.K_RIGHT:
# move the ship to the right
self.ship.rect.x += 1
# makes the most recently drawn screen visible. Continually updates the display to show new game position elements and hide old ones.
pygame.display.flip()
def update_screen(self):
"""update images on the screen & flip to a new screen"""
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
pygame.display.flip()
if __name__ == 'main':
# make a game instance and run the game.
ai = Alieninvasion()
ai.run_game()
"""the run_game as part of the if block ensures it only runs if the file is called directly"""

Image lagging while blitting on top of mouse rect

I'm trying to build a simple version of an aim trainer using pygame and have decided to change the original mouse pointer to a crosshair (an image). When testing if the image has been blitted on the mouse rect I noticed that the image is significantly lagging behind the position of the mouse.
I have tried to tamper with the FPS of the game by setting the clock.tick() to different integers. Tried loading the images in a different part of the code. However nothing seems to change the lag.
import pygame
pygame.init()
from win32api import GetSystemMetrics ## screen size getter so that theres no need to use coordinates, can be run on multiple resolutions
screen_width = GetSystemMetrics(0) ## get screen width and hieght
screen_hieght = GetSystemMetrics(1)
class GameWindow():
screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
pygame.display.toggle_fullscreen()
caption = pygame.display.set_caption("Alex's FPS Trainer")
main_screen_font = pygame.font.SysFont('consolas', 100)
main_screen_background = pygame.image.load("fps_background.jpg") ## loading images
xhair_image = pygame.image.load("crosshair.png")
def __init__(self):
self.background = pygame.transform.scale(GameWindow.main_screen_background, (screen_width, screen_hieght))
self.title = self.main_screen_font.render("Alex's FPS Aim Trainer", 1, (245, 66, 66))
self.run()
def blit(self):
self.screen.blit(self.background, (0, 0))
self.screen.blit(self.title, (screen_width/2 - screen_width/3.5, screen_hieght/5))
self.screen.blit(GameWindow.xhair_image, (pygame.mouse.get_pos()[0] - 13.5,pygame.mouse.get_pos()[1] - 13.5)) ## centres mouse
def createButton(self):
pass
def run(self):
run = True
while run:
pygame.time.Clock().tick(120)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE: ## temporary quit key
run = False
if event.type == pygame.MOUSEBUTTONDOWN: ## detect clicks
print("Mouse pressed")
self.blit()
pygame.display.update()
pygame.quit()
GameWindow = GameWindow()
I was hoping that the image would follow the mouse without lag since it is important for the crosshair in an aim trainer to follow the mouse well.
The easiest solution is to change the mouse cursor by win32api.SetCursor():
win32api.SetCursor(cursor)
A cursor can be loaded by win32gui.LoadImage() from a .cur file:
cursor = win32gui.LoadImage(0, "cursor.cur", win32con.IMAGE_CURSOR,
0, 0, win32con.LR_LOADFROMFILE)
or from an .ico file.
cursor = win32gui.LoadImage(0, path + "cursor.ico", win32con.IMAGE_ICON,
0, 0, win32con.LR_LOADFROMFILE)
See also Cursors and LoadImage.
To avoid flickering it is important to make the "pygame" cursor invisible by pygame.mouse.set_visible()
pygame.mouse.set_visible(False)
Set the cursor immediately before pygame.display.update() respectively pygame.display.flip(), to make it "visible" and to give pygame no chance to "hide" it.
win32api.SetCursor(cursor)
pygame.display.update()
See the example application:
import pygame
import win32api, win32gui, win32con
pygame.init()
screen = pygame.display.set_mode((640, 480))
cursor = win32gui.LoadImage(0, path + "cursor.ico", win32con.IMAGE_ICON,
0, 0, win32con.LR_LOADFROMFILE)
pygame.mouse.set_visible(False)
run = True
while run:
pygame.time.Clock().tick(120)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
win32api.SetCursor(cursor)
pygame.display.update()
pygame.quit()

Pygame Pong paddles not showing up

I'm working on a Ping Pong game in Pygame. Having some trouble getting the paddles to display on screen within a class. I have a feeling either my constructor init method is incorrect (although not throwing up any errors) or the display colour is overwriting the paddles.
Here's my code.
Program.py
import sys
import pygame
from settings import Settings
from paddles import Paddles
import game_functions as gf
def run_game():
# Initialise pygame, settings and screen object.
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height))
pygame.display.set_caption('Ping Pong')
# Start the main loop for the game.
while True:
gf.check_events()
gf.update_screen(ai_settings,screen)
#Make paddles
paddles = Paddles(screen)
run_game()
paddles.py
import pygame
import sys
class Paddles():
def __init__(self, screen):
self.screen = screen
self.paddle_l = pygame.draw.rect(screen, (255, 255, 255), [15, 250, 10, 100])
self.paddle_r = pygame.draw.rect(screen, (255, 255, 255), [780, 250, 10, 100])
def paddles(self):
pass
settings.py
class Settings():
"""A class to store all settings for Ping Pong"""
def __init__(self):
"""Initialise the game's settings."""
# Screen settings
self.screen_width = 800
self.screen_height = 600
self.bg_colour = (0,0,0)
game_functions.py
import sys
import pygame
def check_events():
"""Respond to keypresses and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
def update_screen(ai_settings, screen):
"""Update images on the screen and flip to the new screen."""
# Redraw the screen during each pass through the loop.
screen.fill(ai_settings.bg_colour)
pygame.display.flip()
Like I said I'm not getting any errors, the game window just opens to a black background. The code worked when I put it inside a normal function but not a class.
What am I doing wrong? How do I get the paddles to display?
Is there a reason you're setting paddles outside of the "main loop?"
Moving paddles into your update_screen method gets them showing, at the very least. However, this is newing up a new Paddles object each time update_screen is called.
def update_screen(ai_settings, screen):
"""Update images on the screen and flip to the new screen."""
# Redraw the screen during each pass through the loop.
screen.fill(ai_settings.bg_colour)
paddles = Paddles(screen)
pygame.display.flip()

Categories