Syntax Error When Following Pygame/Python Tutorial on youtube - python

I've just downloaded python 3.3.2 and pygame-1.9.2a0.win32-py3.3.msi.
I have decided to try a few tutorials on youtube and see if they work.
I have tried thenewboston's 'Game Development Tutorial - 2 - Basic Pygame Program' to see if it works. It is supposed to produce a black background and a ball that is the mouse (or so i think). It comes up with a syntax error when i try to run it, if i delete it it just produces a black pygame window. Here is the code:
bgg="bg.jpg"
ball="ball.png"
import pygame, sys
from pygame.locals import *
pygame.init()
screen=pygame.display.set_mode((540,341),0,32)
background=pygame.image.load(bgg).convert()
mouse_c=pygame.image.load(ball).convert_alpha()
while True:
for event in pygame.event.get():
if event.type ==QUIT:
pygame.quit()
sys.exit()
screen.blit(background), (0,0))
The screen.blit(bakcgorund, (0,0)) command is the problem, when it comes up with the syntax error it highlights the second bracket on the furthest right of the command. If I delete it it just shows a black pygame window. can anyone help me?

I updated your code:
import pygame
from pygame.locals import *
#about: pygame boilerplate
class GameMain():
# handles intialization of game and graphics, as well as game loop
done = False
def __init__(self, width=800, height=600):
"""Initialize PyGame window.
variables:
width, height = screen width, height
screen = main video surface, to draw on
fps_max = framerate limit to the max fps
limit_fps = boolean toggles capping FPS, to share cpu, or let it run free.
now = current time in Milliseconds. ( 1000ms = 1second)
"""
pygame.init()
# save w, h, and screen
self.width, self.height = width, height
self.screen = pygame.display.set_mode(( self.width, self.height ))
pygame.display.set_caption( "pygame tutorial code" )
self.sprite_bg = pygame.image.load("bg.jpg").convert()
self.sprite_ball = pygame.image.load("ball.png").convert_alpha()
def main_loop(self):
"""Game() main loop."""
while not self.done:
self.handle_events()
self.update()
self.draw()
def draw(self):
"""draw screen"""
self.screen.fill(Color('darkgrey'))
# draw your stuff here. sprites, gui, etc....
self.screen.blit(self.sprite_bg, (0,0))
self.screen.blit(self.sprite_ball, (100,100))
pygame.display.flip()
def update(self):
"""physics/move guys."""
pass
def handle_events(self):
"""handle events: keyboard, mouse, etc."""
events = pygame.event.get()
kmods = pygame.key.get_mods()
for event in events:
if event.type == pygame.QUIT:
self.done = True
# event: keydown
elif event.type == KEYDOWN:
if event.key == K_ESCAPE: self.done = True
if __name__ == "__main__":
game = GameMain()
game.main_loop()

Your parenthesis are unbalanced; there are 2 opening parenthesis, and 3 closing parenthesis; that is one closing parenthesis too many:
screen.blit(background), (0,0))
# -----^ ------^ ---^
You probably want to remove the closing parenthesis after background:
screen.blit(background, (0,0))

Related

Resize pygame window with minimum width/height without flickering [duplicate]

I'm developing a grid based game in pygame, and want the window to be resizable. I accomplish this with the following init code:
pygame.display.set_mode((740, 440), pygame.RESIZABLE)
As well as the following in my event handler:
elif event.type == pygame.VIDEORESIZE:
game.screen = pygame.display.set_mode((event.w, event.h),
pygame.RESIZABLE)
# Code to re-size other important surfaces
The problem I'm having is that it seems a pygame.VIDEORESIZE event is only pushed once the user is done resizing the window, i.e. lets go of the border. screen.get_size() updates similarly. Since the graphics of my game are very simple, I'd really prefer for them to resize as the user drags the window. This is trivial in many other languages, but I can't find any reference for it in pygame - although I can't imagine a feature this basic would be impossible.
How can I update my game as the screen is being resized in pygame?
EDIT: Here is a minimal working example. Running on Windows 10, pygame 1.9.4, the following code will only draw the updated rectangle after the user finishes dragging the window.
import sys
import pygame
pygame.init()
size = 320, 240
black = 0, 0, 0
red = 255, 0, 0
screen = pygame.display.set_mode(size, pygame.RESIZABLE)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.VIDEORESIZE:
pygame.display.set_mode((event.w, event.h), pygame.RESIZABLE)
screen.fill(black)
pygame.draw.rect(screen, red, (10,10,screen.get_width(),screen.get_height()))
pygame.display.flip()
If you run into this kind of problem, it's always worth to google it using SDL instead of pygame, since pygame is a pretty low-level SDL wrapper.
So that's not a problem of pygame itself, but rather how sdl and your window manager interact, e.g. see this SDL bug report.
Nonetheless, if you really need to update the window while resizing, if you're using Windows, you can listen for the actual WM_SIZE event of Windows, redraw your screen, and update the "Windows"-window by calling RedrawWindow.
Here's a simple example:
import pygame
import win32gui
import win32con
def wndProc(oldWndProc, draw_callback, hWnd, message, wParam, lParam):
if message == win32con.WM_SIZE:
draw_callback()
win32gui.RedrawWindow(hWnd, None, None, win32con.RDW_INVALIDATE | win32con.RDW_ERASE)
return win32gui.CallWindowProc(oldWndProc, hWnd, message, wParam, lParam)
def main():
pygame.init()
screen = pygame.display.set_mode((320, 240), pygame.RESIZABLE | pygame.DOUBLEBUF)
def draw_game():
screen.fill(pygame.Color('black'))
pygame.draw.rect(screen, pygame.Color('red'), pygame.Rect(0,0,screen.get_width(),screen.get_height()).inflate(-10, -10))
pygame.display.flip()
oldWndProc = win32gui.SetWindowLong(win32gui.GetForegroundWindow(), win32con.GWL_WNDPROC, lambda *args: wndProc(oldWndProc, draw_game, *args))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
elif event.type == pygame.VIDEORESIZE:
pygame.display.set_mode((event.w, event.h), pygame.RESIZABLE| pygame.DOUBLEBUF)
draw_game()
if __name__ == '__main__':
main()
Default behaviour:
With RedrawWindow:

Why does the converted image seem laggy when it is moving?

I was trying to create a simple pygame game that uses sprites, but when i compiled the code the movement seemed to have some kind of lag spikes. I did some debugging and extracted the problem into the code below. The image moves smoothly for most of a second, but then a lag spike occurs and so on.
I've seen that converting images helped a lot of people, but nothing changed for me.
import pygame, sys
class Game():
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((1280, 720))
pygame.display.set_caption("Spaceshooter")
self.clock = pygame.time.Clock()
self.image = pygame.image.load("player.png").convert_alpha()
self.rect = self.image.get_rect()
def run(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
self.screen.fill("black")
self.rect.x += 5
self.screen.blit(self.image, self.rect)
self.clock.tick(60)
pygame.display.update()
if __name__ == "__main__":
game = Game()
game.run()
Try to reduce the movement speed and increase the fps. I believe it will help you, Adam.

Pygame wait for screen to update

I just started with pygame, and I am just trying to move points across my screen. The problem is that it happens way to fast and my pygame screen freezes (Not Responding) while the loop runs and then only shows the last iterations position of dots.
I am thinking the updating happens to fast.
When I include pygame.event.wait() then as I give an input the loop progresses and I can follow live in the window how the dots are moving across the screen. However, I would like to have it that they move across the screen without an input required.
This is my main loop:
def run(self):
self.food_spread()
self.spawn_animal()
for k in range(20000):
print(k)
for member in self.zoo:
self.move(member)
self.screen.fill(black)
for i in range(self.food_locations.shape[0]):
pygame.draw.rect(self.screen, white, (self.food_locations[i,1], self.food_locations[i,2],1,1))
for member in self.zoo:
pygame.draw.circle(self.screen, green,(member.location[0], member.location[1]), 2,1)
pygame.display.update()
pygame.event.wait()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
You have an application loop, use if. Use pygame.time.Clock() to control the framerate . The application loop has to
control the framerate (clock.tick(60))
handel the events and move the objects
clear the display
draw the scene
update the display
e.g:
class App:
def __init__(self):
# [...]
self.clock = pygame.time.Clock()
def run(self):
self.food_spread()
self.spawn_animal()
run = True
while run:
# control the framerate
self.clock.tick(60) # 60 FPS
# handel the events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# move the objects
for member in self.zoo:
self.move(member)
# clear the display
self.screen.fill(black)
# draw the scene
for i in range(self.food_locations.shape[0]):
pygame.draw.rect(self.screen, white, (self.food_locations[i,1], self.food_locations[i,2],1,1))
for member in self.zoo:
pygame.draw.circle(self.screen, green,(member.location[0], member.location[1]), 2,1)
# update the display
pygame.display.update()

PyGame - Plotting a Pixel and Printing out it's coordinates

This may seem like a really easy question to answer, but I'm just a beginner in need of quick help.
I'm trying to create a program that when you click somewhere on the pyGame window, it'll print out that you hit it with the left button on the mouse, and also print out co-ordinates of where it was pressed. I've got this already. I'm having problems with making it plot the pixel on the pyGame window. Basically, I want it to draw a pixel where I pressed down on the pyGame window.
#!/usr/bin/env python
#import the module for use
import pygame
#setting up some variables
running = 1
LEFT = 1
#Set up the graphics area/screen
screen=pygame.display.set_mode((640,400))
#continuous loop to keep the graphics running
while running==1:
event=pygame.event.poll()
if event.type==pygame.QUIT:
running=0
pygame.quit()
elif event.type==pygame.MOUSEBUTTONDOWN and event.button==LEFT:
print "You pressed the left mouse button at (%d,%d)" %event.pos
elif event.type==pygame.MOUSEBUTTONUP and event.button==LEFT:
print "You released the left mouse button at (%d,%d)" %event.pos
Try setting the color of each pixel when you receive the mouse down event.
elif event.type==pygame.MOUSEBUTTONDOWN and event.button==LEFT:
print "You pressed the left mouse button at (%d,%d)" %event.pos
screen.set_at((event.pos.x, event.pos.y), pygame.Color(255,0,0,255))
Note that this will temporarily lock and unlock the Surface as needed.
I edited Aesthete's code to a working standalone example:
Depending what you are doing, get/setting individual pixels can be slow. ( There is Surfarray and Pixelarray if you need to. )
import pygame
from pygame.locals import *
class Game(object):
done = False
def __init__(self, width=640, height=480):
pygame.init()
self.width, self.height = width, height
self.screen = pygame.display.set_mode((width, height))
# start with empty screen, since we modify it every mouseclick
self.screen.fill(Color("gray50"))
def main_loop(self):
while not self.done:
# events
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT: self.done = True
elif event.type == KEYDOWN:
if event.key == K_ESCAPE: self.done = True
elif event.type == MOUSEMOTION:
pass
elif event.type == MOUSEBUTTONDOWN and event.button == 1:
print "Click: ({})".format(event.pos)
self.screen.set_at(event.pos, Color("white"))
# draw
pygame.display.flip()
if __name__ == "__main__":
g = Game()
g.main_loop()

Python Pygame image not displaying

I am trying to display a game in pygame. But it won't work for some reason, any ideas? Here is my code:
import pygame, sys
from pygame.locals import *
pygame.init()
screen=pygame.display.set_mode((640,360),0,32)
pygame.display.set_caption("My Game")
p = 1
green = (0,255,0)
pacman ="imgres.jpeg"
pacman_x = 0
pacman_y = 0
while True:
pacman_obj=pygame.image.load(pacman).convert()
screen.blit(pacman_obj, (pacman_x,pacman_y))
blue = (0,0,255)
screen.fill(blue)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type==KEYDOWN:
if event.key==K_LEFT:
p=0
pygame.display.update()
Just a guess, as I haven't actually ran this:
Is the screen just showing up blue and you're missing the pacman image? What might be happening is that you are blitting pacman onto the screen, and then doing a screen.fill(blue), which is essentially overwriting your pacman image with blue. Try reversing these steps in your code (that is, filling the screen blue, then blitting pacman after).
if the screen shows up blue, it is because you need to "blit" the image after you do screen.fill
also, blue has to be defined at the top, and it should be in a different loop. here is how i would do it:
import pygame, sys
from pygame.locals import *
pygame.init()
screen=pygame.display.set_mode((640,360),0,32)
pygame.display.set_caption("My Game")
p = 1
green = (0,255,0)
blue = (0,0,255)
pacman ="imgres.jpeg"
pacman_x = 0
pacman_y = 0
pacman_obj=pygame.image.load(pacman).convert()
done = False
clock=pygame.time.Clock()
while done==False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
if event.type==KEYDOWN:
if event.key==K_LEFT:
p=0
screen.fill(blue)
screen.blit(pacman_obj, (pacman_x,pacman_y))
pygame.display.flip()
clock.tick(100)
pygame.quit()
Note:
You are creating a new image every frame. This is slow.
Coordinates for blit can be Rect()s
Here's updated code.
WINDOW_TITLE = "hi world - draw image "
import pygame
from pygame.locals import *
from pygame.sprite import Sprite
import random
import os
class Pacman(Sprite):
"""basic pacman, deriving pygame.sprite.Sprite"""
def __init__(self, file=None):
"""create surface"""
Sprite.__init__(self)
# get main screen, save for later
self.screen = pygame.display.get_surface()
if file is None: file = os.path.join('data','pacman.jpg')
self.load(file)
def draw(self):
"""draw to screen"""
self.screen.blit(self.image, self.rect)
def load(self, filename):
"""load file"""
self.image = pygame.image.load(filename).convert_alpha()
self.rect = self.image.get_rect()
class Game(object):
"""game Main entry point. handles intialization of game and graphics, as well as game loop"""
done = False
color_bg = Color('seagreen') # or also: Color(50,50,50) , or: Color('#fefefe')
def __init__(self, width=800, height=600):
"""Initialize PyGame window.
variables:
width, height = screen width, height
screen = main video surface, to draw on
fps_max = framerate limit to the max fps
limit_fps = boolean toggles capping FPS, to share cpu, or let it run free.
color_bg = backround color, accepts many formats. see: pygame.Color() for details
"""
pygame.init()
# save w, h, and screen
self.width, self.height = width, height
self.screen = pygame.display.set_mode(( self.width, self.height ))
pygame.display.set_caption( WINDOW_TITLE )
# fps clock, limits max fps
self.clock = pygame.time.Clock()
self.limit_fps = True
self.fps_max = 40
self.pacman = Pacman()
def main_loop(self):
"""Game() main loop.
Normally goes like this:
1. player input
2. move stuff
3. draw stuff
"""
while not self.done:
# get input
self.handle_events()
# move stuff
self.update()
# draw stuff
self.draw()
# cap FPS if: limit_fps == True
if self.limit_fps: self.clock.tick( self.fps_max )
else: self.clock.tick()
def draw(self):
"""draw screen"""
# clear screen."
self.screen.fill( self.color_bg )
# draw code
self.pacman.draw()
# update / flip screen.
pygame.display.flip()
def update(self):
"""move guys."""
self.pacman.rect.left += 10
def handle_events(self):
"""handle events: keyboard, mouse, etc."""
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT: self.done = True
# event: keydown
elif event.type == KEYDOWN:
if event.key == K_ESCAPE: self.done = True
if __name__ == "__main__":
game = Game()
game.main_loop()
First you blit the image and then fill it with BLUE ,so it might show only blue screen ,
Solution: First fill screen blue and then blit it.
import pygame, sys
from pygame.locals import *
pygame.init()
screen=pygame.display.set_mode((640,360),0,32)
pygame.display.set_caption("My Game")
p = 1
green = (0,255,0)
pacman ="imgres.jpeg"
pacman_x = 0
pacman_y = 0
while True:
pacman_obj=pygame.image.load(pacman).convert()
blue = (0,0,255)
screen.fill(blue) # first fill screen with blue
screen.blit(pacman_obj, (pacman_x,pacman_y)) # Blit the iamge
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type==KEYDOWN:
if event.key==K_LEFT:
p=0
pygame.display.update()

Categories

Resources