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).
Related
My pygame window closes without any errors right after I run the code
Here's my code:
import pygame
pygame.init() # initialises pygame
win = pygame.display.set_mode((500, 500)) # width, height
pygame.display.set_caption("Project_01")
If anyone can help, thank you in advance :)
See Why is my PyGame application not running at all? Your application will exit right after the window is created. You have to implement an application loop. You must implement an application loop to prevent the window from closing immediately:
import pygame
pygame.init() # initialises pygame
win = pygame.display.set_mode((500, 500)) # width, height
pygame.display.set_caption("Project_01")
clock = pygame.time.Clock()
run = True
while run:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
win.fill((0, 0, 0))
# draw scene
# [...]
pygame.display.flip()
pygame.quit()
I am trying to write my first game using Python3 & Pygame in the Pycharm Community IDE. I am trying to make a simple Pong game :-D lol I am a beginner so please help me if you can.
When I run my code, I am getting the following error:
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "/home/TechSlugz/PycharmProjects/Pong-Project/Pong1.py", line 7, in <module>
clock = pygame.time.clock()
AttributeError: module 'pygame.time' has no attribute 'clock'
Process finished with exit code 1
The code is just the basic set up for a game window, check it out
import pygame
import sys
# General Setup
pygame.init()
clock = pygame.time.clock()
# Setting Up The Main Window
screen_width = 1280
screen_height = 960
screen = pygame.display.setmode((screen_width, screen_height))
pygame.display.set_caption("Pong")
while True:
#handling input
for event in pygame.event.get():
if event.type == pygame.quit:
pygame.quit()
sys.exit()
#Updating The Window
pygame.display.flip()
clock.tick(60)
Can you notice anything that I am doing wrong to get this issue? None of my IDEs seem to recognise time as a pygame module but I am pretty damn sure it is...
The clock is a class, so you should use C instead of c.
clock = pygame.time.Clock()
and you have another problem, setmode is not an available function. You meant to write set_mode
The code that works fine for me:
import pygame
import sys
# General Setup
pygame.init()
clock = pygame.time.Clock()
# Setting Up The Main Window
screen_width = 1280
screen_height = 960
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Pong")
while True:
#handling input
for event in pygame.event.get():
if event.type == pygame.quit:
pygame.quit()
sys.exit()
#Updating The Window
pygame.display.flip()
clock.tick(60)
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.
I am new to Python programming and I recently started working with the PyGame module. Here is a simple piece of code to initialize a display screen. My question is : Currently, the maximize button is disabled and I cannot resize the screen. How do I enable it to switch between full screen and back?
Thanks
import pygame, sys
from pygame.locals import *
pygame.init()
#Create a displace surface object
DISPLAYSURF = pygame.display.set_mode((400, 300))
mainLoop = True
while mainLoop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainLoop = False
pygame.display.update()
pygame.quit()
To become fullscreen at native resolution, do
DISPLAYSURF = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
To make the window resizeable, add the pygame.RESIZABLE parameter when seting the mode. You can set the mode of the screen surface multiple times but you might have to do pygame.display.quit() followed by pygame.display.init()
You should also check the pygame documentation here http://www.pygame.org/docs/ref/display.html#pygame.display.set_mode
The method you are looking for is pygame.display.toggle_fullscreen
Or, as the guide recommends in most situations, calling pygame.display.set_mode() with the FULLSCREEN tag.
In your case this would look like
DISPLAYSURF = pygame.display.set_mode((400, 300), pygame.FULLSCREEN)
(Please use the pygame.FULLSCREEN instead of just FULLSCREEN because upon testing with my own system FULLSCREEN just maximized the window without fitting the resolution while pygame.FULLSCREEN fit my resolution as well as maximizing.)
import pygame, os
os.environ['SDL_VIDEO_CENTERED'] = '1' # You have to call this before pygame.init()
pygame.init()
info = pygame.display.Info() # You have to call this before pygame.display.set_mode()
screen_width,screen_height = info.current_w,info.current_h
These are the dimensions of your screen/monitor. You can use these or reduce them to exclude borders and title bar:
window_width,window_height = screen_width-10,screen_height-50
window = pygame.display.set_mode((window_width,window_height))
pygame.display.update()
This will let you toggle from maximize to the initial size
import pygame, sys
from pygame.locals import *
pygame.init()
#Create a displace surface object
#Below line will let you toggle from maximize to the initial size
DISPLAYSURF = pygame.display.set_mode((400, 300), RESIZABLE)
mainLoop = True
while mainLoop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainLoop = False
pygame.display.update()
pygame.quit()
You'd have to add the full screen parameter onto the display declaration like this:
import pygame, sys
from pygame.locals import *
pygame.init()
#Create a displace surface object
DISPLAYSURF = pygame.display.set_mode((400, 300), FULLSCREEN)
mainLoop = True
while mainLoop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainLoop = False
pygame.display.update()
pygame.quit()
Just use pygame.RESIZABLE as an easier option.
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()