how do you add images into replit? [duplicate] - python

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?)

Related

Why is the window so slow? And how can I fix it? [duplicate]

I cant blit images in normal speed if the images in array.
#brife review
In my code i defined 10 images as a variable(x1-x10)
those 100 images relevant for specific class (object.draw_function()), and will be bliting in main loop according specific condtions.
in the object.draw_function() all the images are saved in lst "images_lst" = [img1,img2,img3,,,,img10]
and bliting from that array according rulles.
i noticed that if the len of the array is higher then 4,5 , the loop FPS is slower. and i dont understand why ? the loading images is outside the loop.
Code example:
#loading images
img1 = pygame.image.load(r'images\game_background1\img1.jpg')
img2 = pygame.image.load(r'images\game_background1\img2.jpg')
img3 = pygame.image.load(r'images\game_background1\img3.jpg')
'
'
'
img10= pygame.image.load(r'images\game_background1\img10.png')
#define font and space size
space_width,space_height = pysical_tm_img.get_width(),pysical_tm_img.get_height()
font0_0 = pygame.font.SysFont(pygame.font.get_fonts()[0],12)
font0_02 = pygame.font.SysFont(pygame.font.get_fonts()[0],17)
# define class
class EXAMPLE():
def __init__(self,x,y,text,power,energy,range):
self.rect = pygame.Rect(x,y,100,10)
self.text = text
self.power = power
self.energy = energy
self.range = range
def draw_func(self,surface):
img_lst = [img1,text1,img2,text2,img3,text3......img10,text10]
for i,img in enumerate(img_lst):
if i % 2 == 0 :
img_rect = img.get_rect(center=(self.rect.x +20 + (i *space_width*2),self.rect.top + space_height))
surface.blit(img,img_rect)
else:
img_rect = img.get_rect(center=(self.rect.x +20 + space_width + ((i-1) *space_width*2),self.rect.top + space_height))
surface.blit(img,img_rect)
#main loop
while True:
if somthing:
object1 = EXAMPLE(10,10,"abc",100,50,10)
object1.draw_func(screen)
elif somthing else:
object3 = EXAMPLE(10,10,"abc",100,50,10)
object3.draw_func(screen)
pygame.display.update()
clock.tick(60)
I dont understand whats wrong and why i cant append more images to my images list without reducing runtime.
Another question that not much relevant to this code but rellevant to runtime. if this code without the main loop is in file number 1 and in this file i import pygame and init the font only.
pygame.font.init()
and in file num 2 where the main loop is running i import pygame and init pygame
pygame.init()
is it reduce my proggram runtime?
Ensure that the image Surface has the same format as the display Surface. Use convert() (or convert_alpha()) to create a Surface that has the same pixel format. This improves performance when the image is blit on the display, because the formats are compatible and blit does not need to perform an implicit transformation.
e.g.:
img1 = pygame.image.load(r'images\game_background1\img1.jpg').convert()

Pyinstaller - Error Message: name Actor is not defined

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

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