I am 9 and self teaching, please be kind and keep that in mind when you reply, thank you very much for your time.
I have the image Bluecar.png and the following code in the same file:
import pygame, time
pygame.init()
(width, height) = (300, 200)
screen = pygame.display.setmode((width, height))
pygame.display.flip()
player = Bluecar.png
screen.blit(player)
while True:
time.sleep(0.1)
But, it causes this error:
Traceback (most recent call last):
File "/home/pi/escape/listings/listings/listing7-2.py", line 7, in <module>
player = Bluecar.png
NameError: name 'Bluecar' is not defined.
Also, after fixing the NameError, I think an Attribute Error will occur.
You probably want to use the pygame.image.load() function
import pygame, time
import os.path
pygame.init()
(width, height) = (300, 200)
screen = pygame.display.setmode((width, height))
pygame.display.flip()
filepath = os.path.dirname(__file__)
x = 0 #x co-ordinate
y = 0 #y co-ordinate
player = pygame.image.load(os.path.join(filepath, "Bluecar.png"))
screen.blit(player, (x, y))
Edit
Included os.path.join to ensure image loaded from the directory of the python file.
Related
I use Python 3.7.4 and Pygame 1.9.6. I'm trying to create just a test game so I can save data like a score per say using pickle this is my first time. But I'll get down that path once I'm done with the test game.
I'm getting an error two separate occasions in ball(ballX[i], ballY[i], i) and in screen.blit(ballImg, (x, y), i). It's a TypeError: arugument 1 must be pygame.Surface, not list.
Full Trace Back:
Traceback (most recent call last):
File "C:Test/main.py", line 128, in <module>
ball(ballX[i], ballY[i], i)
File "C:/Test/main.py", line 66, in ball
screen.blit(ballImg, (x, y), i)
The code:
import pygame
import random
# Ball
ballImg = []
ballX = []
ballY = []
num_of_balls = 4
for i in range(num_of_balls):
ballImg.append(pygame.image.load('ball.png'))
ballX.append(random.randint(0, 736))
ballY.append(random.randint(50, 535))
'''This code is above the while running loop'''
def ball(x, y, i):
screen.blit(ballImg, (x, y), i)
running = True
while running:
'''The key stuff and what not'''
'''I have the screen color load before the image appears'''
for i in range(num_of_balls):
ball(ballX[i], ballY[i], i)
pygame.display.update()
I'm not understanding what I'm doing wrong in my function/list or evening bliting the image. I feel like I'm doing everything right filling out the parameters, etc. I appreciate the advice. So thank you.
A few things:
As #Ewong mentioned, you are passing ballImg to blit instead of ballImg[i]
You're not processing OS messages, so the program will freeze
Try this code:
import pygame
import random
scr_width = 800
scr_height = 600
screen = pygame.display.set_mode((scr_width, scr_height))
# Ball
ballImg = []
ballX = []
ballY = []
num_of_balls = 4
for i in range(num_of_balls):
ballImg.append(pygame.image.load('ball.png'))
ballX.append(random.randint(0, 736))
ballY.append(random.randint(50, 535))
#'''This code is above the while running loop'''
def ball(x, y, i):
screen.blit(ballImg[i], (x, y))
running = True
while running:
#'''The key stuff and what not'''
#'''I have the screen color load before the image appears'''
for i in range(num_of_balls):
ball(ballX[i], ballY[i], i)
for event in pygame.event.get(): # process OS messages
if event.type == pygame.QUIT:
pygame.quit()
break
pygame.display.update()
Hey i'm just making a small game in python its python 2.7.13 i'm using cause i'm used to its syntax(lol i have a syntax error in a way its to do with TypeError: argument 1 must be pygame.Surface, not function) but i'm taking an image from the same directory and trying to display it on screen just to get the layout of the game but i can't get it to work the error i get is on this line
display.blit(floor,(x,y))
THE ERROR:
Traceback (most recent call last):
File "1stgame.py", line 38, in
floor(x,y)
File "1stgame.py", line 25, in floor
display.blit(floor,(x,y))
TypeError: argument 1 must be pygame.Surface, not function
here's the code
import pygame
#Start pygame
pygame.init()
#Window/Screen/Display
display_x = 800
display_y = 600
display = pygame.display.set_mode((display_x,display_y))
pygame.display.set_caption('Platforms')
clock = pygame.time.Clock()
#Colors
black = (0,0,0)
green = (1,166,17)
#Images
floor = pygame.image.load('rock.jpg')
def floor(x,y):
display.blit(floor,(x,y))
x = (display_x * 0.45)
y = (display_y * 0.8)
not_dead=True
while not_dead:
for event in pygame.event.get():
if (event.type==pygame.QUIT):
not_dead=False
display.fill(black)
pygame.draw.rect(display, green, [0,550,800,50])
floor(x,y)
pygame.display.update()
clock.tick(60)
print "Hello"
pygame.quit()
You just need to read the traceback:
Here's the error:
def floor(x,y):
display.blit(floor,(x,y))
When you do def floor, you define the function floor. So, the value of floor is now a function instead of the surface you set earlier. So, in your function, you're trying to blit a function, and not a Surface.
You need to change the variable name of either
the function
the surface
So I'm trying to get into using Pygame, but all of the tutorials I can find online utilize only one file. I played around with ideas on how I can load all of the images in a single function. and decided on saving them in a Dictionary. Problem is, when I try to paste the image from the dictionary, I get the following error:
Traceback (most recent call last):
File "J:\Growth of Deities\Main.py", line 32, in <module>
pygame.Surface.blit(Sprites["TileWastelandBasic"], (0, 0))
TypeError: argument 1 must be pygame.Surface, not tuple
So I played around with the code a bit and googled it for an hour or so, but I can't figure out why I'm getting an error. I assume it's because I can't save images in dictionaries, but I'm not certain. Does anyone have any ideas on how to fix it?
My Main File:
import pygame
from Startup import LoadTextures
pygame.init()
#Sets the color White
WHITE = (255, 255, 255)
#Sets screen size Variable
size = (900, 900)
#Sets Screen Size
screen = pygame.display.set_mode(size)
#Sets name of Game
pygame.display.set_caption("Growth of Deities")
closeWindow = False
clock = pygame.time.Clock()
Sprites = LoadTextures.Load()
while not closeWindow:
#Repeat while game is playing
for event in pygame.event.get():
#Close Window if you close the window
if event.type == pygame.QUIT:
closeWindow = True
#Logic Code
#Rendering Code
pygame.Surface.blit(Sprites["TileWastelandBasic"], (0, 0))
#Clear Screen
screen.fill(WHITE)
#Update Screen
pygame.display.flip()
#Set Tick Rate
clock.tick(60)
#Closes Game
pygame.quit()
My Image Loading File:
import pygame
import os, sys
def Load():
Sprites = {}
WastelandSprites = 'Assets\Textures\Tile Sprites\Wasteland'
Sprites["TileWastelandBasic"] = pygame.image.load(os.path.join(WastelandSprites + "\WastelandBasic.png")).convert_alpha()
Sprites["TileWastelandBasic"] = pygame.transform.scale(Sprites["TileWastelandBasic"], (50, 50)).convert_alpha()
return Sprites
The problem is not because of your dictionary. The signature of blit is
blit(source, dest, area=None, special_flags = 0) -> Rect
where source must be a surface. However, this assumes that blit is being invoked with a pygame.Surface instance as the receiver. Instead, you're calling the blit function from its class, which means that its signature is effectively
blit(self, source, dest, area=None, special_flags = 0) -> Rect
where self must also be a surface. You could fix your problem by changing the call to
pygame.Surface.blit(screen, Sprites["TileWastelandBasic"], (0, 0))
but I would recommend the more idiomatic
screen.blit(Sprites["TimeWastelandBasic"], (0, 0))
instead.
See: http://www.pygame.org/docs/ref/surface.html#pygame.Surface.blit
I'm working on a time based movement program in pygame. And I keep receiving this error.
Traceback (most recent call last):
File "C:\Documents and Settings\Mohammad Raza\Desktop\Python
Scripts\TimeBasedMovement.py", line 11, in <module>
background = pygame.image.load(background_image_filename).convert()
error: Couldn't open Wolf.jpg
I thought perhaps I deleted the image, but I checked and the image is not deleted. It is saved as the name "Wolf" and stored as a JPEG image.
Here is the entire code below.
background_image_filename = 'Wolf.jpg'
sprite_image_filename = 'Cartoon.jpg'
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640,480),0,32)
background = pygame.image.load(background_image_filename).convert()
sprite = pygame.image.load(sprite_image_filename)
clock = pygame.time.Clock()
x = 0.
speed = 250
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background,(0,0))
screen.blit(sprite,(x,100))
time_passed = clock.tick()
time_passed_seconds = time_passed_seconds / 1000.0
distance_moved = time_passed_seconds * speed
x += distance_moved
if x > 640.:
x -= 640.
pygame.display.update()
Also make sure the image is in the current working directory.
fullname = os.path.join('data', name)
image = pygame.image.load(fullname)
Also it should be
time_passed_seconds = time_passed / 1000.
So I'm developing a game using Pygame and trying to abstract away a lot of the code. In the process though, I'm getting some weird errors. Namely, when I run main.py, I get this trace:
>>>
initializing pygame...
initalizing screen...
initializing background...
<Surface(Dead Display)> #Here I print out the background instance
Traceback (most recent call last):
File "C:\Users\Ceasar\Desktop\pytanks\main.py", line 19, in <module>
background = Background(screen, BG_COLOR)
File "C:\Users\Ceasar\Desktop\pytanks\background.py", line 8, in __init__
self.fill(color)
error: display Surface quit
I imagine it has something to do with me using a context in my main to manage the screen.
#main.py
import math
import sys
import pygame
from pygame.locals import *
...
from screen import controlled_screen
from background import Background
BATTLEFIELD_SIZE = (800, 600)
BG_COLOR = 100, 0, 0
FRAMES_PER_SECOND = 20
with controlled_screen(BATTLEFIELD_SIZE) as screen:
background = Background(screen, BG_COLOR)
...
#screen.py
import pygame.display
import os
#The next line centers the screen
os.environ['SDL_VIDEO_CENTERED'] = '1'
class controlled_screen:
def __init__(self, size):
self.size = size
def __enter__(self):
print "initializing pygame..."
pygame.init()
print "initalizing screen..."
return pygame.display.set_mode(self.size)
def __exit__(self, type, value, traceback):
pygame.quit()
#background.py
import pygame
class Background(pygame.Surface):
def __init__(self, screen, color):
print "initializing background..."
print screen
super(pygame.Surface, self).__init__(screen.get_width(),
screen.get_height())
print self
self.fill(color)
self = self.convert()
screen.blit(self, (0, 0))
Any thoughts on what is causing the error here?
Not technically my answer here, but the problem is that Surface cannot be extended with Python's super. Rather, it should be referred to as a Python old style class like so:
class ExtendedSurface(pygame.Surface):
def __init__(self, string):
pygame.Surface.__init__(self, (100, 100))
self.fill((220,22,22))
# ...
SOURCE: http://archives.seul.org/pygame/users/Jul-2009/msg00211.html
i was also trying to subclass pygame.Surface because i wanted to be able to add attributes to it. the following accomplishes that. i hope it helps future people.
pygame.display.set_mode() must be called because it inits all the pygame.video stuff. it appears that pygame.display is the surface that ultimately gets drawn to the screen. therefore we need to blit whatever surface we create to the return value of pygame.display.set_mode() (which is just another pygame.Surface object).
import pygame
from pygame.locals import *
pygame.init()
SCREEN_SIZE = (800, 600)
font = pygame.font.SysFont('exocet', 16)
class Screen(pygame.Surface):
def __init__(self):
pygame.Surface.__init__(self, SCREEN_SIZE)
self.screen = pygame.display.set_mode((SCREEN_SIZE))
self.text = "ella_rox"
My_Screen = Screen()
text_surface = font.render(My_Screen.text, 1, (155, 0, 0))
while True:
My_Screen.fill((255, 255, 255))
My_Screen.blit(text_surface, (50, 50))
My_Screen.screen.blit(My_Screen, (0, 0))
pygame.display.update()