I am currently learning the code from a tutorial on Pygame Game Development:
https://www.youtube.com/watch?v=fcryHcZE_sM
I have copied the code exactly into Pycharm and I believe it should work.
#Pygame Sprite Example
import pygame
import random
import os
WIDTH = 360
HEIGHT = 480
FPS = 30
#Colours
BLACK = (0, 0, 0)
WHITE= (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# set up assets folders
game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, "img")
class Player(pygame.sprite.Sprite):
# sprite for the player
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(os.path.join(img_folder, "p1_jump.png")).convert()
self.image.set_colourkey(BLACK)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
def update(self):
self.rect.x += 5
if self.rect.left > WIDTH:
self.rect.right = 0
#initialise pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
#Game Loop
running = True
while running:
#keep loop running at right speed
clock.tick(FPS)
#Process Input/Events
for event in pygame.event.get():
#check for closing window
if event.type == pygame.QUIT:
running = False
#Update
all_sprites.update()
#Draw/Render
screen.fill(BLUE)
all_sprites.draw(screen)
# *after drawing everything, flip the display*
pygame.display.flip()
pygame.quit()
it gives me this error when I run it:
C:\Users\George\PycharmProjects\app\venv1\Scripts\python.exe "C:/Users/George/Documents/School/Year 12/IT/Coursework/SpriteExample.py"
Traceback (most recent call last):
File "C:/Users/George/Documents/School/Year 12/IT/Coursework/SpriteExample.py", line 46, in <module>
player = Player()
File "C:/Users/George/Documents/School/Year 12/IT/Coursework/SpriteExample.py", line 28, in __init__
self.image = pygame.image.load(os.path.join(img_folder, "p1_jump.png")).convert()
pygame.error: Couldn't open C:/Users/George/Documents/School/Year 12/IT/Coursework\img\p1_jump.png
Process finished with exit code 1
In the tutorial video, the guy is using a Mac, and I am using a Windows laptop (running Windows 7).
I have tried researching around the site and I couldn't find anything specific enough to my error. I also tried changing the code in and just above the initialization of the class Player to this:
game_folder = os.path.dirname(os.path.abspath(__file__))
img_folder = os.path.join(game_folder, "img")
image1 = pygame.image.load(os.path.join(img_folder, "p1_jump.png" ))
class Player(pygame.sprite.Sprite):
# sprite for the player
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = image1.convert()
self.image.set_colourkey(BLACK)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
and it still didn't work.
If you make a little python file name it my_path.py or similar and place it in documents folder and run it.
It will help you see that the sprite2.py file should be in documents folder and that you will need a sub folder within documents that is labelled 'img' and contains the 'png' file. Then the game should run ok. Therefore the game_folder is actually 'documents folder' and img_folder is img within documents. I hope that is a little clearer then the code above or within sprite2.py can be tinkered with if you have game in another folder
game_folder = os.path.dirname(__file__)
print(game_folder)
img_folder = os.path.join(game_folder, "img")
print(img_folder)
Related
I'm starting to code and have been following a series of videos to create a game with pygame. However, even when I've followed everything the guy in the video said, and after checking many times mine and his code, I got this error:
File "C:/Users/sdf/PycharmProjects/pygame1/pygametutorial 2/tutorail 1 template.py", line 43, in
all_sprites.update()
TypeError: update() missing 1 required positional argument: 'self'
this is the code I've programmed so far:
import pygame
import random
import sprites as sprites
height = 360
width = 480
FPS = 30
White = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Tutorial")
clock = pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 50))
self.image.fill(green)
self.rect = self.image.get_rect()
self.rect.center = (height / 2, width / 2)
all_sprites = pygame.sprite.Group
player = Player()
all_sprites.add(player)
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
all_sprites.update()
screen.fill(black)
sprites.draw(screen)
# after every drawing flip the display
pygame.display.flip()
Im not sure what import sprites as sprites is, is it another file you made? Is it meant to be import pygame.sprite.Sprite as sprite?
all_sprites = pygame.sprite.Group
Group is a class so you need the brackets
all_sprites = pygame.sprite.Group()
now you are calling it and all_sprites is a group object, not referencing the class
now i changed sprites.draw(screen) to all_sprites.draw(screen) as not don't have sprites, and not sure what is is.
i being following this pygame tutorial and I can't have my sprite show on the window. When I run the program I see the rectangle move on the screen but it just shows all black. I try changing the background color on my rectangle according to the window but i still get nothing. I do notice that the rectangle changes shape according to the different images i try to load. Here is the code. Thank you
import pygame
import random
import os
WIDTH = 800
HEIGHT = 600
FPS = 30
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
#SET ASSETS FOLDERS
game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, "img")
class Player(pygame.sprite.Sprite):
# sprite for the Player
def __init__(self):
# this line is required to properly create the sprite
pygame.sprite.Sprite.__init__(self)
# create a plain rectangle for the sprite image
self.image = pygame.image.load(os.path.join(img_folder, "p1_jump.png")).convert()
# find the rectangle that encloses the image
self.rect = self.image.get_rect()
# center the sprite on the screen
self.rect.center = (WIDTH / 2, HEIGHT / 2)
def update(self):
# any code here will happen every time the game loop updates
self.rect.x += 5
if self.rect.left > WIDTH:
self.rect.right = 0
# initialize pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Sprite Example")
clock = pygame.time.Clock()
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
# Game loop
running = True
while running:
# keep loop running at the right speed
clock.tick(FPS)
# Process input (events)
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
# Update
all_sprites.update()
# Draw / render
screen.fill(GREEN)
all_sprites.draw(screen)
# *after* drawing everything, flip the display
enter code herepygame.display.flip()
pygame.quit()
I just changed one line near the end of the code in your question and it started working:
.
.
.
# Game loop
running = True
while running:
# keep loop running at the right speed
clock.tick(FPS)
# Process input (events)
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
# Update
all_sprites.update()
# Draw / render
screen.fill(GREEN)
all_sprites.draw(screen)
# *after* drawing everything, flip the display
pygame.display.flip() # <----- FIX THIS LINE
pygame.quit()
Im trying to make a rain effect with pygame but it seems as if the background is not cleaning up before updating the sprites.
this is what it looks like when i execute the code..
I wonder if there's a way to fix this problem.
rain.py (main file)
#!/usr/bin/python
VERSION = "0.1"
import os, sys, raindrop
from os import path
try:
import pygame
from pygame.locals import *
except ImportError, err:
print 'Could not load module %s' % (err)
sys.exit(2)
# main variables
WIDTH, HEIGHT, FPS = 300, 300, 30
# initialize game
pygame.init()
screen = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Rain and Rain")
# background
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((40,44,52))
# blitting
screen.blit(background,(0,0))
pygame.display.flip()
# clock for FPS settings
clock = pygame.time.Clock()
def main():
raindrops = pygame.sprite.Group()
# a function to create new drops
def newDrop():
nd = raindrop.Raindrop()
raindrops.add(nd)
# creating 10 rain drops
for x in range(0,9): newDrop()
# variable for main loop
running = True
# event loop
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
raindrops.update()
screen.blit(background,(100,100))
raindrops.draw(screen)
pygame.display.flip()
pygame.quit()
if __name__ == '__main__': main()
raindrop.py ( class for raindrops )
import pygame
from pygame.locals import *
from os import path
from random import randint
from rain import HEIGHT
img_dir = path.join(path.dirname(__file__), 'img')
class Raindrop(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.width = randint(32, 64)
self.height = self.width + 33
self.image = pygame.image.load(path.join(img_dir, "raindrop.png")).convert_alpha()
self.image = pygame.transform.scale(self.image, (self.width, self.height))
self.speedy = 5 #randint(1, 8)
self.rect = self.image.get_rect()
self.rect.x = randint(0, 290)
self.rect.y = -self.height
def update(self):
self.rect.y += self.speedy
if self.rect.y == HEIGHT:
self.rect.y = -self.height
self.rect.x = randint(0, 290)
This is the line you use to clear the screen:
screen.blit(background, (100, 100))
In other words; you're clearing the screen starting at x=100, y=100. Since pygame coordinates starts from topleft and extends to the right and downwards, you're not clearing the screen left of x=100 and above y=100.
Simple fix is blitting at 0, 0 as you did at the start of the program.
screen.blit(background, (0, 0))
Recently, I started to take a look at pygame, but now I´m facing a serious problem. I followed the tutorial by "KidsCanCode" on Youtube and now have this code:
# Pygame template - skeleton for a new pygame project
import pygame
import random
WIDTH = 600
HEIGHT = 480
FPS = 30
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
class Player(pygame.sprite.Sprite):
# sprite for the Player
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 50))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT - 10
self.speedx = 0
def update(self):
self.speedx = 0
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT]:
self.speedx = -5
if keystate[pygame.K_RIGHT]:
self.speedx = 5
self.rect.x += self.speedx
if self.rect.right > WIDTH:
self.rect.right = WIDTH
if self.rect.left < 0:
self.rect.left = 0
# initialize pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
# Game loop
running = True
while running:
# keep loop runnig at the right speed
clock.tick(FPS)
# Process input (events)
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
# Update
all_sprites.update()
# Draw / render
screen.fill(BLACK)
all_sprites.draw(screen)
# *after* drawing everything, flip the display
pygame.display.flip()
pygame.quit()
The code itself is working fine, the pygame window appears and I can see the green sprite. But when I try to control the sprite via arrow keys, I only control the cursor in the text editor, I wrote the script in.
If I didn't open the text editor in full screen mode, the pygame window even disappears to behind the editor´s window. When I move the editor aside / minimize it, and click on the pygame window it still doesn't´t get focused.
I´m using a Mac, macOS 10.12.4, Python 3.6.0, Anaconda 4.3.1.
When I try to go to the pygame window via "cmd + tab", it doesn't´t even appear in the list.
I installed pygame via pip.
I hope someone has either seen this problem before / has an idea to fix this.
I had that bug sometime ago as well. It seems like either the pygame module is buggy on Mac OS or Mac OS is preventing from being intractable. Try running the code on Windows or install a different version of pygame.
I'm developing a Space Invaders clone using Python 3.5.1 and PyGame. My issue is that I cannot manage to load my sprites onto the screen. I keep receiving the error:
Traceback (most recent call last):
File "C:\Users\supmanigga\Documents\Space Invaders\spaceinvaders.py", line 44, in
allSprites.draw(screen)
File "C:\Users\supmanigga\AppData\Local\Programs\Python\Python35\lib\site-packages\pygame\sprite.py", line 475, in draw
self.spritedict[spr] = surface_blit(spr.image, spr.rect)
AttributeError: 'Ship' object has no attribute 'image'
My code is as follows:
import pygame
import sys
width = 500
height = 700
white = (255, 255, 255)
black = (0, 0, 0)
score = 0
screen = pygame.display.set_mode([width, height])
class Ship(pygame.sprite.Sprite):
def _init_(self):
sprite.Sprite._init_(self)
self.image = pygame.image.load("player").convert()
self.rect = self.image.get_rect()
class Enemy(pygame.sprite.Sprite):
def _init_(self):
sprite.Sprite._init_(self)
self.image = pygame.image.load("enemy").convert()
self.rect = self.image.get_rect()
class Bullet(pygame.sprite.Sprite):
def _init_(self):
sprite.Sprite._init_(self)
self.image = pygame.image.load("laser").convert()
self.rect = self.image.get_rect()
player = Ship()
allSprites = pygame.sprite.Group()
allSprites.add(player)
running = True
while running == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.fill(black)
allSprites.draw(screen)
pygame.display.flip()
pygame.quit()
def _init_(self): should be def __init__(self):
Otherwise, the line self.image = pygame.image.load("player").convert() is never executed, and thus your Ship instance will have no image attribute.