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.
Related
This question already has answers here:
How do I detect collision in pygame?
(5 answers)
Not letting the character move out of the window
(2 answers)
How to make ball bounce off wall with PyGame?
(1 answer)
Closed 1 year ago.
I'm new to python/pygame and I'm trying to make a boids simulation but can't seem to get to create the borders so that the boids don't go outside of the window. Here's what I've done so far.
#importing the needed modules and libraries
import pygame, sys, random, pygame.math
#Initialize pygame and pygame time
pygame.init()
clock = pygame.time.Clock()
#This is some screen settings, giving the screen size.
screen_width = 1000
screen_height = 750
screen = pygame.display.set_mode((screen_width, screen_height))
#Making the background, loading it and scaling the background to fit the screen.
background = pygame.image.load("Background.jpg")
background = pygame.transform.scale(background, (screen_width, screen_height))
#Make parent-class for boids and hoiks
class Moving_Object(pygame.sprite.Sprite):
def __init__(self, picture_load, X_pos, Y_pos): #speed_x, speed_y
super().__init__()
#Creating picture_load to make it easier to load image. Creating a rectangle around image
self.image = pygame.image.load(picture_load)
self.image = pygame.transform.scale(self.image, (40, 40))
#Make rectangle around image
self.rect = self.image.get_rect()
self.rect.center = [X_pos, Y_pos]
self.speed_x = random.randint(-3,3)
self.speed_y = random.randint(-3,3)
def border(self):
if self.rect.right >= screen_width or self.rect.left <= 0:
self.speed_x *= -1
if self.rect.bottom >= screen_height or self.rect.top <= 0:
self.speed_y *= -1
if self.rect.collidrect(boid):
print("yesir")
def update(self):
self.rect.x += self.speed_x
self.rect.y += self.speed_y
#making moving_object group and adding boids & hoiks
moving_object_group = pygame.sprite.Group()
for boid in range(50):
new_boid = Moving_Object("Logo.png", random.randrange(0, screen_width), random.randrange(0, screen_height))
moving_object_group.add(new_boid)
for hoiks in range(10):
new_hoik = Moving_Object('skullObstacle.png',random.randrange(0, screen_width), random.randrange(0, screen_height))
moving_object_group.add(new_hoik)
"""Game loo, it keeps the window open and checks
for events and calls differnt classes and methods"""
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.flip()
screen.blit(background, (0,0))
moving_object_group.draw(screen)
moving_object_group.update()
clock.tick(60)
I can't see what's wrong with the below code. All I want to do is make the frog move across the screen, but it is simply redrawing many, many frogs all one pixel apart. How do I move the frog rather than just draw it again?
import pygame
from pygame.constants import *
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
class Frog(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.transform.scale(pygame.image.load('frog.png'), (64, 64))
self.rect = self.image.get_rect()
self.dx = 1
def update(self, *args):
self.rect.x += self.dx
running = True
frog = Frog()
entities = pygame.sprite.Group()
entities.add(frog)
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
entities.update()
entities.draw(screen)
That is how you do it in Pygame, you just redraw objects every iteration to give the illusion that they're moving but you must cover up the previous drawn objects by filling your window with a solid color e.g.
screen.fill((255, 255, 255))
This should be at the start of your game loop so you have a fresh canvas for drawing your objects each iteration.
while running:
screen.fill((255,255,255))
for event in pygame.event.get():
if event.type == QUIT:
running = False
entities.update()
entities.draw(screen)
pygame.display.update()
You may have to use the pygame.display.update() function to update the whole screen rather than just your entities.
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()
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)
For some reason when i run the code in netbeans i only get a blank screen
import pygame
import random
WIDTH = 480
HEIGHT = 600
FPS = 60
# define colours
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 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()
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((40, 50))
self.image.fill(BLUE)
self.rect = self.image.get_rect()
self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT - 10
self.speedx = 0
def update(self):
self.rect.x += self.speedx
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(BLACK)
all_sprites.draw(screen)
# *after* drawing everything, flip the display
pygame.display.flip()
pygame.quit()
please help me. when i run the code in netbeans it works but the screen where the game should be is blank, when i close the screen there is a frame of it in colour before it closes the window. I'm using OSX sierra
The sprites update and rendering calls are not being made in your while loop.
As pointed out in the comments, you need to indent the seven lines below # Update. Try this:
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(BLACK)
all_sprites.draw(screen)
# *after* drawing everything, flip the display
pygame.display.flip()
pygame.quit()