not able to open another file in python, pygame - python

i am trying to open settings.py in main.py by importing it like a library, but whenever i run main.py, the setting page opens immediately and im not sure why
whats is meant to happen is when you press the Account button you are supposed to run the settings page and get that the to load however that doesnt happen, instead whenever you run main.py settings.py instantly gets run without the main menu loading. This worked fine with the button but it doesnt work with the settings page i have tried to use exec and os to open it instead but that doesnt work.
the myLibrary is just the button defintion i used to create the account button
main.py
import pygame, sys, os
import myLibrary as lib
import settings
def runSettings():
print(settings.mainloop())
return
script_dir = sys.path[0]
bg_path = os.path.join(script_dir, '../info/images/backgrounds/MainMenu background.png')
bg = pygame.image.load(bg_path)
(width, height) = (1300, 790)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Main Menu')
Account_img = os.path.join(script_dir, '../info/images/MainMenu buttons/account.png')
Account_btn = lib.Button(Account_img, (180,340), runSettings)
while True:
screen.blit(bg, (0, 0))
screen.blit(Account_btn.image, Account_btn.rect)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
Account_btn.on_click(event)
pygame.display.update()
settings.py
import pygame, sys, os
import myLibrary as lib
script_dir = sys.path[0]
bg_path = os.path.join(script_dir, '../info/images/backgrounds/Settings background.png')
bg = pygame.image.load(bg_path)
(width, height) = (1100, 700)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Settings')
#titles
Username_img = pygame.image.load(os.path.join(script_dir, '../info/images/Settings buttons/username.png'))
def mainloop():
while True:
screen.blit(bg, (0,0))
screen.blit(Username_img, (30,20))
for event in pygame.event.get():
pass
pygame.display.update()
mainloop()
button definition, myLibrary as lib
import pygame
#button class will take the image, the position and callback
#function to create and place buttons
class Button:
def __init__(self, image, position, callback):
self.image = pygame.image.load(image)
self.image.convert()
self.rect = self.image.get_rect(topleft=position)
self.callback = callback
def on_click(self, event):
if event.button == 1:
if self.rect.collidepoint(event.pos):
self.callback()

Related

Why can't I change the python window icon? [duplicate]

This question already has an answer here:
Icons are not displayed properly with pygame
(1 answer)
Closed 2 years ago.
I want to change the pygame window icon with code:
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Snake Game")
icon = pygame.image.load('snake icon.png')
pygame.display.set_icon(icon)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
When I use that code It won't work,
like the window closed on its own,
but when I change the code to:
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Snake Game")
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
It works, but It's still have the default pygame icon, i want to change the pygame icon,
can someone tell me what's wrong with the code?
Make sure that the resource (image) path and the working directory is correct.
The image file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python file.
The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd() and can be changed by os.chdir(path).
import os
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(sourceFileDir)
Furthermore see pygame.display.set_icon():
[...] Some systems do not allow the window icon to change after it has been shown. This function can be called before pygame.display.set_mode() to create the icon before the display mode is set.
Set the icon before screen = pygame.display.set_mode((800, 600)):
icon = pygame.image.load('snake icon.png')
pygame.display.set_icon(icon)
screen = pygame.display.set_mode((800, 600))

Pygame window freezes and stop responding, how could I fix this?

I am creating a game but I am having a problem with my button class for my gui. There are no compile errors and no runtime errors either. The only problem is that on run it immediately freezes the pygame window. I don't know how to solve this.
I've tried fiddling around with the callback function (which I removed entirely) and with the update and draw loop as well but nothing seems to work.
Python 3.7.0 and Pygame 1.9.4
Button Class:
import sys
import time
import pygame
pygame.init()
class button:
def __init__(self, txt, location, bg=(255,255,255),fg=(0,0,0),size=(80,30),font_name="Times New Roman",font_size=16):
#bg is the colour of the button
#fg is the colour of the text
#location refers to the center points of the button
self.colour = bg
self.bg = bg
self.fg = fg
self.size = size
self.font = pygame.font.SysFont(font_name,font_size)
self.txt = txt
self.txt_surf = self.font.render(self.txt, 1, self.fg)
self.txt_rect = self.txt_surf.get_rect(center=[s//2 for s in self.size])
self.surface = pygame.surface.Surface(size)
self.rect = self.surface.get_rect(center=location)
def mouseover(self):
self.bg = self.colour
pos = pygame.mouse.get_pos()
if self.rect.collidepoint(pos):
self.bg = (200,200,200)
def draw(self, screen):
self.mouseover()
self.surface.fill(self.bg)
self.surface.blit(self.txt_surf, self.txt_rect)
screen.blit(self.surface, self.rect)
Actual update/draw loop
import gui
import pygame
import sys
import time
import win32api
pygame.init()
screen = pygame.display.set_mode((400,400))
button1 = gui.button("No", (200,200))
intro = True
while intro:
screen.fill((255,255,255))
button1.draw(screen)
if win32api.GetKeyState(0x01) == -127 or win32api.GetKeyState(0x01) == -128:
if button1.rect.collidepoint(pygame.mouse.get_pos()):
intro = False
pygame.quit()
sys.exit()
pygame.display.flip()
pygame.time.wait(20)
I really just want the window to stop freezing up on run and to actually have a button press work. What it should do is immediately quit the application when you press the button in the middle. Not actually do that though.
You have to let pygame process the events in the event queue by calling pygame.event.get (or pygame.event.pump, but you should stick to use get).
Otherwise, the queue will fill up and new events will be dropped. This includes internal events that tell your OS to draw the window etc, so your window will freeze.
Also, there's no reason to use win32api to get the state of the keyboard (you can use pygame.key.get_pressed instead), but that's another topic.

Why is my pygame window opening and immediately closing?

Pygame window opens and the closes immediately.
I have copied the code from a youtube channel and it still opens and closes immediately
import pygame
pygame.init()
class Game():
def __init__(self):
self.width = 800
self.height = 600
self.win = pygame.display.set_mode((self.width, self.height))
def run(self):
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
Game = Game()
The while loop should be waiting for me to quit but its auto executing the quit function
You need to call your run method as follows:
game = Game()
game.run()
By calling using game = Game() and then game.run(), the code should work.

background music not playing in pygame

When i run the code it play only the .wav file
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((500, 400), 0, 32)
pygame.mixer.music.load('background.ogg')
pygame.mixer.music.play()
soundObj = pygame.mixer.Sound('bird.wav')
soundObj.play()
pygame.mixer.music.stop()
someone know what i should do for the background.ogg to be played too?
Remove this line:
pygame.mixer.music.stop()
Basically, you're loading and playing the background noise, and then immediately stopping it. I also suggest you create a main loop, like so:
import pygame
from pygame.locals import *
# This makes sure that you're not importing the module.
if __name__ == "__main__":
# Create surface
size = width, height = (500, 400)
# You don't need the extra arguments
window = pygame.display.set_mode(size)
# Do sound stuff
pygame.mixer.music.load('background.ogg')
pygame.mixer.music.play()
soundObj = pygame.mixer.Sound('bird.wav')
soundObj.play()
# This is your main loop.
running = True
while running:
# Check if escape was pressed
Most of the time people just check if Escape was pressed in their main loop (if it was pressed, they set running = False and exit the program).

pygame.error: file not a windows.bmp file (have looked at other similar questions but unsuccessful so far)

I'm very new to pygame, and am using the book "Beginning Game developement with Python and Pygame". I have pretty much typed the example code and keep getting the same
"pygame error: file not a windows.bmp file"
and would like to be able to load jpg/png as in the example in the book. I'm pretty sure I'm in the right directory for mine to work and the images I wanted to use are the same format as in the example. I have also searched for solutions but none of the answers seemed to work for me.
The code from the book is as follows (I have python 2.7.4, Ubuntu 13.04 and (I think) pygame 1.2.15):
background_image_filename = 'sushiplate.jpg'
mouse_image_filename = 'fugu.png'
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background_image_filename).convert()
mouse_cursor = pygame.image.load(mouse_image_filename).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background, (0,0))
x, y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() / 2
y-= mouse_cursor.get_height() / 2
screen.blit(mouse_cursor, (x, y))
pygame.display.update()
my version of the code so far:
import os.path
background = os.path.join('Documents/Python/Pygame','Background.jpg')
cursor_image = os.path.join('Documents/Python/Pygame','mouse.png')
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background).convert()
mouse_cursor = pygame.image.load(cursor_image).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background, (0,0))
x, y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() / 2
y-= mouse_cursor.get_height() / 2
screen.blit(mouse_cursor, (x, y))
pygame.display.update()
Thanks for your help :)
I can almost guarantee that you're getting your paths wrong. In your code, you've put in relative paths, meaning that pygame is looking for your assets in subfolders of the working directory (the directory where you execute your code).
A demo of how I think you would have to have things laid out and where your code is looking is below - in this example you would have a command prompt open in /home/your_username/Documents/my_games (or ~/Documents/my_games) and you'd be running python your_game_script.py.
|---home
|---your_username
|---Documents
|---some_subfolder
|---my_games
|---your_game_script.py
|---Documents
|---Python
|---Pygame
|---Background.jpg
|---mouse.png
This would work, but I suspect you don't have your folders set up this way, and that's the reason it's not working. If you run an interactive python prompt in the same folder as your game script, try the following:
import os
os.path.isfile('Documents/Python/Pygame/Background.jpg')
os.path.isfile('Documents/Python/Pygame/mouse.png')
I suspect the result will be false for both - meaning the files couldn't be found at that subfolder location. I would recommend that you have the following structure for your game files:
|---my_game
|---your_game_script.py
|---images
|---Background.jpg
|---mouse.png
Then in your_game_script.py you can load the files in the following way:
background = 'images/Background.jpg' #relative path from current working dir
cursor_image = 'images/mouse.png' #relative path from current working dir
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background).convert()
mouse_cursor = pygame.image.load(cursor_image).convert_alpha()

Categories