I'm currently working on a game with pygame, in python 3.7.2.
I got a strange error when I run my program :
This is the full traceback :
hello from the 1st lign of this code :D
pygame 1.9.4
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "C:\Users\-------\----------\---------\WIP\newfile.py", line 69, in <module>
Window('load')
File "C:\Users\-------\----------\---------\WIP\newfile.py", line 52, in Window
bg32 = pygame.load('sprites/bg32.png').convert_alpha()
AttributeError: module 'pygame' has no attribute 'load'
It's really strange because 'load' function is a really basic and import function of pygame...
So this is my code ( full ), i still don't understand what's wrong here :
print('hello from the 1st lign of this code :D')
import time
spb = time.time()
import pygame
import os, sys
pygame.init()
os.environ['SDL_VIDEO_CENTERED'] = '1'
Very_Dark_Blue = ( 0, 0, 64)
barPos = (0, 0)
barSize = (400, 40)
borderColor = ( 0, 0, 0,)
max_a = 10000
a=0
screen=pygame.display.set_mode((1,1), pygame.NOFRAME)
def text(show_text, show_size, show_color, show_x, show_y):
fontObj = pygame.font.Font('Display_Font.ttf',show_size)
Load_text = fontObj.render(show_text,True,show_color,None)
render_text = Load_text.get_rect()
render_text.center = (show_x,show_y)
screen.blit(Load_text,render_text)
def image(name,x,y):
screen.blit(name,(x,y))
def DrawBar(pos, size, borderC, barC, progress):
global screen
pygame.draw.rect(screen, borderC, (*pos, *size), 1)
innerPos = (pos[0]+3, pos[1]+3)
innerSize = ((size[0]-6) * progress, size[1] - 6)
pygame.draw.rect(screen, barC, (*innerPos, *innerSize))
def Window(w):
global screen,a,max_a,barPos,barSize,Very_Dark_Blue,borderColor
if w == 'load':
screen=pygame.display.set_mode((400,40), pygame.NOFRAME)
bg32 = pygame.load('sprites/bg32.png').convert_alpha()
while w == 'load':
image(bg32,0,0)
DrawBar(barPos, barSize, borderColor, Very_Dark_Blue, a/max_a)
pygame.display.update()
a = a + 1
if a == max_a:
Window('main')
if w == 'main':
pygame.quit
screen=pygame.display.set_mode((1920,1080), pygame.NOFRAME)
while w == 'main':
image(background,0,0)
image(title,100,0)
pygame.display.update()
Window('load')
background = pygame.image.load('sprites/Background.png').convert_alpha()
title = pygame.image.load('sprites/Title.png').convert_alpha()
So I hope someone will find the problem :D
Thank for anyone who will try to help me !
As Rabbid76 already said in a comment, the load function is part of the image module, so you'll have to use pygame.image.load(...) instead of pygame.load(...).
Related
I'm creating FPS game with Ursina Engine (python). But I started to get a error whenever I tried to play it.
I just started coding so I don't know what I should do.
Code:
from ursina import *
from ursina.prefabs.first_person_controller import *
class Player(Entity):
def __init__(self, **kwargs):
self.controller = FirstPersonController(**kwargs)
super().__init__(parent=self.controller)
self.hand_gun = Entity(parent=self.controller.camera_pivot, scale=0.1, position=Vec3(0.7, -1, 1.5), rotation=Vec3(0, 170, 0), model='gun', Texture='M1911-RIGHT', visible=False)
self.knife = Entity(parent=self.controller.camera_pivot, scale=0.4, position=Vec3(0.7, -1, 1.5), rotation=Vec3(0, 170, 0), model='knife', Texture='knife', visible=False)
self.weapons = [self.hand_gun, self.knife]
self.current_weapon = 0
self.switch_weapons()
def switch_weapon(self):
for i, v in enumerate(self.weapons):
if i == self.current_weapon:
v.visible = True
else:
v.visible = False
def input(self, key):
try:
self.current_weapon = int(key) - 1
self.switch_weapon()
except ValueError:
pass
if key == 'scroll up':
self.current_weapon = (self.current_weapon + 1) % len(self.weapons)
self.switch_weapon()
if key == 'scroll down':
self.current_weapon = (self.current_weapon - 1) % len(self.weapons)
self.switch_weapon()
if key == 'left_mouse_down' and self.current_weapon == 0:
Bullet(model='sphere', color=color.black, scale=0.2, position=self.controller.camera_pivot.world_position, rotation=self.controller.camera_pivot.world_rotation)
def update(self):
self.controller.camera_pivot.y = 2 - held_keys['left control']
class Bullet(Entity):
def __init__(self, speed=50, lifetime = 10, **kwargs):
super().__init__(**kwargs)
self.speed = speed
self.lifetime = lifetime
self.start = time.time()
def update(self):
ray = raycast(self.world_position, self.forward, distance=self.speed*time.dt)
if not ray.hit and time.time() - self.start < self.lifetime:
self.world_position += self.forward * self.speed * time.daylight
else:
destroy(self)
app = Ursina
ground = Entity(model='plane', scale=20, texture='white_cube', texture_scale='mesh')
player = Player(position=(0,10,0))
app.run()
It's just small shooting game that I made for learning Ursina Engine
and the error message I got was:
package_folder: C:\Users\Yunwoo Chang\AppData\Roaming\Python\Python310\site-packages\ursina
asset_folder: c:\Users\Yunwoo Chang\Desktop\Tetris\Ursina Engine
Exception ignored in: <function Texture.__del__ at 0x000001E55A5129E0>
Traceback (most recent call last):
File "C:\Users\Yunwoo Chang\AppData\Roaming\Python\Python310\site-packages\ursina\texture.py", line 185, in __del__ del self._cached_image
AttributeError: _cached_image
Traceback (most recent call last):
File "c:\Users\Yunwoo Chang\Desktop\Tetris\Ursina Engine\03 - Weapons.py", line 71, in <module>
player = Player(position=(0,10,0))
File "c:\Users\Yunwoo Chang\Desktop\Tetris\Ursina Engine\03 - Weapons.py", line 6, in __init__
self.controller = FirstPersonController(**kwargs)
File "C:\Users\Yunwoo Chang\AppData\Roaming\Python\Python310\site-packages\ursina\prefabs\first_person_controller.py", line 32, in __init__
ray = raycast(self.world_position+(0,self.height,0), self.down, ignore=(self,))
File "C:\Users\Yunwoo Chang\AppData\Roaming\Python\Python310\site-packages\ursina\entity.py", line 433, in world_position
return Vec3(self.get_position(render))
NameError: name 'render' is not defined
How can I fix it?
I think it's some kind of attribute error but I don't know what to do.
You should instantiate Ursina with app = Ursina() before instantiating Entities. You're missing the ().
I created a small game with Pygame and MU IDE. Then I wanted to convert the .py file to a .exe file with pyinstaller. It was no problem to create the exe file. But if I want to execute the created exe file I get the following error message: 'name Actor is not defined'. With MU IDE I can execute the corresponding .py file without any problems. How can I fix the problem?
The full error message is:
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "test.py", line 11, in module
NameError: name 'Actor' is not defined
[1920] Failed to execute script test
Here is the code:
from random import randint
import time
import pygame
HEIGHT = 800
WIDTH = 800
score = 0
time_left = 10
banana = Actor("banana")
monkey = Actor("monkey")
pygame.mixer.init()
pygame.mixer.music.load("music\\music.mp3")
pygame.mixer.music.play(-1)
background = pygame.image.load("images\\background.png")
def draw():
screen.blit("background",(0,0))
banana.draw()
monkey.draw()
screen.draw.text("Anzahl der gesammelten Bananen: " + str(score), color = "black", topleft=(10,10))
screen.draw.text("verbleibende Sekunden: " + str(time_left), color = "black", topleft=(10,50))
def place_graphics():
banana.x = randint(125, 790)
banana.y = randint(186, 790)
monkey.x = 50
monkey.y = 740
def on_mouse_down(pos):
global score
if banana.collidepoint(pos):
score = score + 1
place_graphics()
if monkey.collidepoint(pos):
effect = pygame.mixer.Sound("sounds\\monkey.wav")
effect.play()
def update_time_left():
global time_left
if time_left:
time_left = time_left - 1
else:
game_over()
place_graphics()
clock.schedule_interval(update_time_left, 1.0)
def game_over():
global score
screen.fill("green")
screen.draw.text("Game Over: Du hast " + str(score) + " Bananen gesammelt!", topleft=(100,350), fontsize=40)
screen.draw.text("Magst du nochmal spielen? ja [j] oder nein [n]", topleft=(150,450), fontsize=30)
pygame.display.update()
Actor is not a part of PyGame. It is a class of Pygame Zero. See Actors. Pygame Zero is based on Pygame and adds many classes to Pygame. You have to import pgzrun:
import pgzrun
I have a red pixeled image and i wanted another image to be blitted at the red pixel, so I did this code:
import sys, pygame
pygame.init()
from pygame.locals import *
import time
#the function with get at
def colorscan(rect):
red = ( 255 , 0 , 0 , 255 )
for x in range(rect[0],rect[0]+rect[2]+1):
for y in range(rect[1],rect[1]+rect[3]+1):
print(x,y)
if tuple(screen.get_at((x,y)))==red:
print(x,y,"done")
return (x,y)
def load(path):
x = pygame.image.load(path)
return x
beam = load("menu/beam.png")
w_plat = load("menu/w_plat.png")
videoinfo = pygame.display.Info()
fullscreen = pygame.FULLSCREEN
screen = pygame.display.set_mode((videoinfo.current_w,videoinfo.current_h), fullscreen, 32)
time = pygame.time.Clock()
#main loop
while True:
beamrect = screen.blit(beam,(0,0))
xtl,ytl=beamrect.topleft
w_pos=colorscan( (xtl,ytl,35,+35) )
screen.blit(w_plat, w_pos)
my code is too large so i just wrote here what's important. Anyways, when i run it I get this error:
Traceback (most recent call last):
File "C:\Users\André Luiz\Desktop\Equilibrium\Equilibrium.py", line 171, in
screen.blit(w_plat, w_pos)
TypeError: invalid destination position for blit
after checking, printing w_pos returned "None", but I'm sure the red pixel has been ""scanned"".
I think what happens is that either your for loops are broken
for x in range(rect[0],rect[0]+rect[2]+1):
for y in range(rect[1],rect[1]+rect[3]+1):
by not executing, or the if statement is not executed because its conditions are not met:
if tuple(screen.get_at((x,y)))==red: (eg: not executed if != red)
because it's the only location you return a value. Otherwise when a function is not specified a return value, it returns None.
colorscan() has no default return value, this is why you get a None.
I have a problem with my pixel_at function in my code. Here are all necessary code snippets.
Here is my Helper module:
import gtk.gdk
def pixel_at(x, y):
gtk.gdk
rw = gtk.gdk.get_default_root_window()
pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, 1, 1)
pixbuf = pixbuf.get_from_drawable(rw, rw.get_colormap(), x, y, 0, 0, 1, 1)
return tuple(pixbuf.pixel_array[0, 0])
Here is the Controller class for initilaizing:
import Sensors as sensor
import Scanner as sc
import pyautogui
import time
class GameController(object):
COLOR_DINOSAUR = (83, 83, 83)
def __init__(self):
self.offset = (230, 270) #hardcoded Offset
self.width = 600 # hardcoded but alwways the same
# Stores points (jumps)
self.points = 0
#Listeners
self.onGameEnd = None
self.onGameStart = None
self.onSensorData = None
#Game State
self.gameState = 'OVER'
self.sensor = sensor.Sensors()
self.Scanner = sc.Scanner()
Here is my main function:
import pyautogui
import Helper
import GameController as GC
def main():
print Helper.pixel_at(25, 5)
Controller = GC.GameController()
# Just test values for this function
Controller.Scanner.scanUntil([75, 124],
(-2, 0),
(83, 83, 83),
75 / 2)
Here is the code for the Scanner:
import pyautogui
import Helper
def scanUntil(self, start, step, matchColor, iterLimit):
iterations = 0
current = self.makeInBounds(start)
if step[X] == 0 and step[Y] == 0:
return None
while not self.isOutOfBound(current):
color = Helper.pixel_at(current[X], current[Y])
# to slow color = pyautogui.pixel(current[X], current[Y])
if color == matchColor: # Tuple comparison
return current
current[X] += step[X]
current[Y] += step[Y]
iterations += 1
if iterations > iterLimit:
return None
return None
This line color = Helper.pixel_at(current[X], current[Y]) in the Scanner throws the error: Fatal IO error 0 (Success) on X server :0. But the print Helper.pixel_at(25, 5)call in main() returns me the correct RGB tuple.
The error is thrown at pixbuf = pixbuf.get_from_drawable(rw, rw.get_colormap(), x, y, 0, 0, 1, 1) in the pixel_at(x,y) so I think it has something to do with this.
From the documentation at http://www.pygtk.org/pygtk2reference/class-gdkpixbuf.html#method-gdkpixbuf--get-from-drawable I got this clue: In other words, copies image data from a server-side drawable to a client-side RGB(A) buffer.
But I don´t understand this server-side and client side and why is it working in my first print call but not for color = Helper.pixel_at(current[X], current[Y])?
I'm writing a roguelike with libtcodpy. It works, but when I run this listing: http://kooneiform.wordpress.com/2009/03/29/241/ at the bottom of the page is a full listing and a few others I've tried, I get errors such as this:
FYI I'm on Windows and do have the libtcodpy.py, SDL.dll, libtcod-mingw.dll files and they do work when following the tutorial that is most popular for libtcodpy.
For the listing above I receive this specific error:
$ python roguelike_practice2.py
Traceback (most recent call last):
File "roguelike_practice2.py", line 165, in <module>
draw()
File "roguelike_practice2.py", line 98, in draw
libtcod.console_set_foreground_color(0, libtcod.white)
AttributeError: 'module' object has no attribute 'console_set_foreground_color'
I also on that same program encounter the exact same issue with console_set_background_color, console_print_left. None work. All with the same error.
For other listings such as this one:
#!/usr/bin/python
###imports###
import os
import libtcodpy as libtcod
###utility functions###
def get_key(key):
if key.vk == libtcod.KEY_CHAR:
return chr(key.c)
else:
return key.vk
###global constants and variables###
window_width = 46
window_height = 20
first = True
fov_px = 9
fov_py = 10
fov_recompute = True
fov_map = None
fov_colors = {
'dark wall' : libtcod.Color(0, 0, 100),
'light wall' : libtcod.Color(130, 110, 50),
'dark ground' : libtcod.Color(50, 50, 150),
'light ground' : libtcod.Color(200, 180, 50)
}
fov_init = False
fov_radius = 4
do = {
'up' : (0, -1),
'down' : (0, 1),
'right' : (1, 0),
'left' : (-1, 0)
}
keys = {
'i' : do['up'],
'k' : do['down'],
'j' : do['left'],
'l' : do['right'],
libtcod.KEY_UP : do['up'],
libtcod.KEY_KP8 : do['up']
}
smap = ['##############################################',
'####################### #################',
'##################### # ###############',
'###################### ### ###########',
'################## ##### ####',
'################ ######## ###### ####',
'############### #################### ####',
'################ ###### ##',
'######## ####### ###### # # # ##',
'######## ###### ### ##',
'######## ##',
'#### ###### ### # # # ##',
'#### ### ########## #### ##',
'#### ### ########## ###########=##########',
'#### ################## ##### #####',
'#### ### #### ##### #####',
'#### # #### #####',
'######## # #### ##### #####',
'######## ##### ####################',
'##############################################',
]
###drawing###
def draw():
global fov_px, fov_py, fov_map, first
global fov_init, fov_recompute, smap
if first:
wh = window_height
ww = window_width
first = False
libtcod.console_clear(0)
libtcod.console_set_fore(0, ww, wh, libtcod.white)
libtcod.console_print_left(0, 1, 1, libtcod.BKGND_NONE,
"IJKL : move around")
libtcod.console_set_fore(0, ww, wh, libtcod.black)
libtcod.console_put_char(0, fov_px, fov_py, '#',
libtcod.BKGND_NONE)
for y in range(window_height):
for x in range(window_width):
if smap[y][x] == '=':
libtcod.console_put_char(0, x, y,
libtcod.CHAR_DHLINE,
libtcod.BKGND_NONE)
if not fov_init:
fov_init = True
fov_map = libtcod.map_new(window_width, window_height)
for y in range(window_height):
for x in range(window_width):
if smap[y][x] == ' ':
libtcod.map_set_properties(fov_map, x, y, True, True)
elif smap[y][x] == '=':
libtcod.map_set_properties(fov_map, x, y, True, False)
if fov_recompute:
fov_recompute = False
libtcod.map_compute_fov(fov_map, fov_px, fov_py, fov_radius, True)
for y in range(window_height):
for x in range(window_width):
affect, cell = 'dark', 'ground'
if libtcod.map_is_in_fov(fov_map, x, y):
affect = 'light'
if (smap[y][x] == '#'):
cell = 'wall'
color = fov_colors['%s %s' % (affect, cell)]
libtcod.console_set_back(0, x, y, color, libtcod.BKGND_SET)
###game state updates###
def update(key):
global fov_py, fov_px, fov_recompute, smap
key = get_key(key)
if key in keys:
dx, dy = keys[key]
if smap[fov_py+dy][fov_px+dx] == ' ':
libtcod.console_put_char(0, fov_px, fov_py, ' ',
libtcod.BKGND_NONE)
fov_px = fov_px + dx
fov_py = fov_py + dy
libtcod.console_put_char(0, fov_px, fov_py, '#',
libtcod.BKGND_NONE)
fov_recompute = True
###initialization and main loop###
font = os.path.join('fonts', 'arial12x12.png')
libtcod.console_set_custom_font(font, libtcod.FONT_LAYOUT_TCOD | libtcod.FONT_TYPE_GREYSCALE)
libtcod.console_init_root(window_width, window_height, 'Python Tutorial', False)
while not libtcod.console_is_window_closed():
draw()
libtcod.console_flush()
key = libtcod.console_wait_for_keypress(True)
update(key)
if key.vk == libtcod.KEY_ESCAPE:
break
I receive the following errors, again I have all the needed files in the folder and am on Windows.
Error for listing 2:
Traceback (most recent call last):
File "roguelike_practice1.py", line 167, in <module>
draw()
File "roguelike_practice1.py", line 100, in draw
libtcod.console_set_fore(0, ww, wh, libtcod.white)
File "c:\Users\cshenkan\CloudStation\Programming\Libtcod\Project 2\libtcodpy.p
y", line 764, in console_set_fore
_lib.TCOD_console_set_fore(con, x, y, col)
File "c:\Python27\lib\ctypes\__init__.py", line 378, in __getattr__
func = self.__getitem__(name)
File "c:\Python27\lib\ctypes\__init__.py", line 383, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'TCOD_console_set_fore' not found
I run into this TCOD_console_set_fore error a bunch. But say I comment that out, I get the same error but with another function such as TCOD_console_set_back, and others.
Not sure why I'm getting these errors. Using Python 2.7.9 32 bit, and libtcod 1.5.1 I believe. Running Windows 7 64 bit. Keep in mind I can get other programs to run that don't require any of those set_foreground and variation functions, or the print_left function or whatever other functions aren't working. But I'm sure it one or two issues affecting all the functions that wont work. \
If anyone has any ideas, I've spent a ton of time looking online to no avail for info. And the forum for libtcod takes days for administrator approval to join - lame.
Anyway thanks in advance! Ask me any questions or if you need clarification.
TCOD 1.5.1 renamed some functions, so that is why your two listings are crashing.
Version 1.5.1 renamed console_set_foreground_color to console_set_default_foreground,console_set_background_color to console_set_default_background, console_set_fore and console_set_back to console_set_char_foreground and console_set_char_background respectively, and console_wait_for_keypress has been replaced with sys_wait_for_event.
Also, console_print_left has been replaced by console_print_ex, which has an extra 'alignment' parameter between background and the string to print.
It appears that those functions were deprecated in 1.5.1. I can find them in 1.5.0, but neither in 1.5.1 nor 1.5.2. I think you would have to use console_print_ex or console_print_rect_ex instead.
Otherwise you could off course switch back to 1.5.0.