Pyinstaller - Error Message: name Actor is not defined - python

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

Related

how do you add images into replit? [duplicate]

I'm making a simple 2d exploration game in replit (hoping to have a nice base for a future game I'm making) and I have all my map tiles as images
WATER = pygame.image.load(r'water.jpg')
SAND = pygame.image.load(r'sand.jpg')
GRASS = pygame.image.load(r'grass.jpg')
FOREST = pygame.image.load(r'Forest.jpg')
VILLAGE = pygame.image.load(r'village.jpg')
and I have my dictionary which compresses them into a single letter
TileMap = {'W': WATER, 'S': SAND, 'G': GRASS, 'F': FOREST, 'V': VILLAGE }
and I have my map which should usually come up with the image after the code:
map1 = ["WWWWWWWWWWWWWWWWWWWWWWW",
"WWWWWWWWWGGGWWWWWWWWWWW",
"WWWWWGGGGGGGGGGGWWWWWWW",
"WWWWGGGGGFFFGGGGGVWWWWW",
"WWWGGGGGFFFFFFGGGGGWWWW",
"WWWGGGGGGFFFFFGGGGGGWWW",
"WWGGGGGGGGGFFGGGGGGGWWW",
"WWGGGGGGGGGGGGGGGGGGGWW",
"WWGGGGGGSSSSSSSGGGGGGGW",
"WWGGGGSSSSSSSSSSGGGGGGW",
"WGGGGGGGSSGGGGGGGGGGGSW",
"WGGGGGGGGGGGGGGGGGGGSSW",
"WSGGGGGGGGFFGGGGGGGGSSW",
"WSSGGGGGGFFFGGGGGFFGGSW",
"WSSGGGGGFFFFFFGGFFFFFGW",
"WSGGGGFFFFFFFFFFFFFFGGW",
"WWGGGGGFFFFFFFFFFFFGGWW",
"WWGGGGGGGFFFFFFFFGGGWWW",
"WWWWGGGGGGGGFFGGGGGWWWW",
"WWWWWWSSSSSGGGGSSSWWWWW",
"WWWWWWWWWSSSSSSSSWWWWWW",
"WWWWWWWWWWWWWWSWWWWWWWW",
"WWWWWWWWWWWWWWWWWWWWWWW"
]
and I have a attempt at showing the images
pygame.image.load_basic(TileMap(map1))
and I get this error message:
pygame 2.1.2 (SDL 2.0.16, Python 3.8.12)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "main.py",line 74, in <module>
pygame.image,load_basic(TileMap(map1))
TypeError: 'dict' object is not callable
>>>
does anyone have any suggestions as to how to make this work?
here is the link to the replit code: my game
WATER, SAND, etc are already pygame.Surface objects. You do not need to load them again. Just blit the images:
# application loop
while run:
# [...]
for row in range(MAPHEIGHT):
for col in range(MAPWIDTH):
c = map1[row][col]
image = TileMap[c]
x = col * TILESIZE
y = row * TILESIZE
DISPLAY.blit(image, (x, y))
# [...]
(The code is based on the code in your previous question: how do you make the map more detailed?)

Python turtle game error _tkinter.TclError: invalid command name ".!canvas"

I have coded a small game using python turtle, and it seems like whenever I close the turtle window manually it gives me an error, but if the game finished running and then I close it's fine. I think it has something to do with the ontimer part of the code, but I'm not sure how to fix it.
import turtle
from random import randint
wn = turtle.Screen()
circle1 = turtle.Turtle(shape = 'circle')
bullet = turtle.Turtle(shape = "circle")
bullet.ht()
bullet.speed(0)
circle1.speed(-1)
circle1.penup()
circle1.ht()
circle1.sety(-270)
circle1.st()
wn.setup(300, 600)
enemies = []
score = 0
prevscore = 1
speed = 10
for i in range(10):
p = turtle.Turtle(shape='square',visible=False)
p.speed(0)
p.penup()
p.color('blue')
x = randint(-240,240)
y = randint(180,360)
p.goto(x,y)
p.showturtle()
enemies.append(p)
def enemy_move():
global game_on
global speed
global score
global prevscore
for p in enemies:
y = p.ycor()
p.sety(y-speed)
if p.ycor() < -300 or p.distance(bullet.pos())<30:
if p.distance(bullet.pos())<30:
score += 1
p.hideturtle()
y = randint(180,360)
p.sety(y)
p.showturtle()
if circle1.isvisible() and p.distance(circle1.pos())<20:
p.hideturtle()
circle1.hideturtle()
game_on = False
wn.clear()
circle1.goto(0, 0)
circle1.write(f"Your final score is {score}", align ="center", font = ("Arial", 26, "normal"))
if game_on == True:
if score%10 == 0:
if score != prevscore:
speed += 0.5
prevscore = score
wn.ontimer(enemy_move,50)
else:
return
game_on = True
enemy_move()
def goright():
if(circle1.xcor() < 130):
circle1.seth(0)
circle1.fd(10)
def goleft():
if(circle1.xcor() > -130):
circle1.seth(180)
circle1.fd(10)
def shoot():
bullet.penup()
bullet.goto(circle1.pos())
bullet.seth(90)
bullet_move()
bullet.showturtle()
def bullet_move():
if bullet.ycor() <= 300:
bullet.sety(bullet.ycor() + 10)
wn.ontimer(bullet_move, 50)
else:
bullet.hideturtle()
wn.listen()
wn.onkeypress(goright, "Right")
wn.onkeypress(goleft, "Left")
wn.onkeypress(shoot, "Up")
wn.mainloop()
The error I get when I exit the code manually is this:
Traceback (most recent call last):
File "/Users/luke/PycharmProjects/Class Teaching/Game interface example.py", line 1, in <module>
import game
File "/Users/luke/PycharmProjects/Class Teaching/game.py", line 31, in <module>
p.goto(x,y)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/turtle.py", line 1777, in goto
self._goto(Vec2D(x, y))
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/turtle.py", line 3159, in _goto
screen._pointlist(self.currentLineItem),
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/turtle.py", line 756, in _pointlist
cl = self.cv.coords(item)
File "<string>", line 1, in coords
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 2762, in coords
self.tk.call((self._w, 'coords') + args))]
_tkinter.TclError: invalid command name ".!canvas"
It is caused by the for loop inside enemy_move(). If you try to exit the application by destroying the window, the for loop may still be running and so accessing the already destroyed canvas raises the exception.
You can check game_on at the beginning of each iteration of the for loop:
def enemy_move():
...
for p in enemies:
# exit the function is game_on is False
if not game_on:
return
...
...
Then you need to set game_on to False before destroying the window. It can be done using tkinter.protocol() (as turtle is built on tkinter):
...
def on_quit():
global game_on
game_on = False
# give some time to stop the for loop before destroying window
wn._root.after(100, wn._root.destroy)
wn._root.protocol("WM_DELETE_WINDOW", on_quit)
wn.mainloop()

Pygame error : AttributeError: module 'pygame' has no attribute 'load'

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(...).

pygame`s get_at is not working for me

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.

Traceback on 3 click house code

I'm new to python and I'm getting an invalid syntax(see error below)I'm suck with this error....help? I am writing code to build a house in 4 clicks. A lot of the code below is my trying different things so just ignore it(or give me suggestions with what I should do) It's the p2 error that has me stumped.
<using graphics.py>
import graphics
from graphics import*
def house():
win=GraphWin(800,500)
win.setCoords(0.0,0.0,4.0,4.0)#reset coordinates
Text(Point(2.0,3.5),"click spot to designate 2 corners of house").draw(win)
p1=win.getMouse()
p1.draw(win)
side1=(Point(p1.getX(),(p1.getY()))
p2=win.getMouse()<----------------------------ERROR with the p2
p2.draw(win)
side2=(Point(p2.getX(),(p2.getY()))
rect = Rectangle(side1,side2)
rect.draw(win)
#door- p3=center top edge of door
msg2 = Text(Point(2.0,0.5),"click to designate top of door")
msg2.draw(win)
p3=win.getMouse()
p3.draw(win)
#golden:)
Line(Point(p3.getX(),(p3.getY())),(Point(p2.getX()),(p2.getY()))).draw(win)
"""
p3 = dwidth.getCenter()
rectWidth = (p2.getX()) - (p1.getX())
#doorWidth = door.setWidth(distance/5.0)#width 1/5 of house
dwidth= eval((rectWidth) / (5))
dheight=((getP3(),(getP2()))#height = from top corners to bottom of the frame
#door = Rectangle((dwidth) * (dheight))"""
#door.draw(win)
"""#Window
message3 = Text(Point(2.0, 1.0),"click to designate center of square window").draw(win)
p4=win.getMouse()
p4.draw(win)
c=door.getCenter()
dx=p4.getX()-c.getX()
dy=p4.getY()-c.getY()
window = Rectangle(Point(dx,dx),Point(dy,dy))
window.draw(win)
#window side = half of door with
#roof top = half way btwn l and r edges
#house height = half height of house frame
#win.getMouse()
#win.close
"""
#window one forth of the door
#window = Rectangle(p4)
#window.setWidth(doorwidth/ 4.0)
#window.draw(win)
house()
>>> ================================ RESTART ================================
>>>
Traceback (most recent call last):
File "E:\ICS 140\ass 8.py", line 57, in <module>
house()
File "E:\ICS 140\ass 8.py", line 28, in house
Line(Point(p3.getX()),(p3.getY()),(Point(p2.getX()),(p2.getY()))).draw(win)
TypeError: __init__() missing 1 required positional argument: 'y'
>>>
The error happens because a Point needs an x and a y argument, but you are only passing an x in the line where you try to create a Rectangle.
Not exactly sure what your code is trying to do, but hopefully this will help get you started in the right direction:
from graphics import *
def house():
win=GraphWin(800,500)
win.setCoords(0.0,0.0,3.0,4.0)#reset coordinates
Text(Point(1.5,3.5),"click spot to designate 2 corners of house").draw(win)
p1 = win.getMouse()
p1.draw(win)
p2 = win.getMouse()
p2.draw(win)
rectangle = Rectangle(p1, p2)
rectangle.setWidth(3)
rectangle.draw(win)
win.getMouse()
win.close()
house()

Categories

Resources