0

I am creating a small level designer in Python (using PyGame). The program is supposed to just let you place down an image, change between images, export to a PNG file, and export image path and coordinates to where it was place in a text document. I have gotten all of these components to work, but I am stuck with one last component, and that is reading the text document back into PyGame, and re-placing all of the images in the correct places with the correct sprites.

The way that I have it currently (Which has been rewritten and Almost works) produces an error whenever I try to read from one of my exported files.

The error of course is:

stamped_surface.blit(image, (xcrds, ycrds))
TypeError: invalid destination position for blit

Here is my code:

import pygame as pg
import threading
import time
import pygame
from random import *
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfile
image_file = "../res/ExampleProject/TankGame/TankGameImg/tileGrass_transitionE.png"


f = open("../Saves/Backups/FailSafe.txt", "a+")
f.write("""
#################################################
#          PyEngine             #
#          FailSafe         #
#                File           #   
#       By MouseBatteries           #   
#################################################

""")


pg.init()

xcrds = 17
ycrds = 13
black = (0,0,0)
sw = 1280
sh = 720

screen = pg.display.set_mode((sw, sh))
pg.display.set_caption('thing')
image = pg.image.load(image_file).convert()

start_rect = image.get_rect()
image_rect = start_rect
running = True

stamped_surface = pg.Surface((sw, sh))




while running:
    event = pg.event.poll()
    keyinput = pg.key.get_pressed()

    # Escape Program
    if keyinput[pg.K_ESCAPE]:
        fname = "../Saves/Design_complete.png"

        pg.image.save(stamped_surface, fname)
        print("File saved at {} ".format(fname))
        quit()

    #Save Work In Project File
    if keyinput[pg.K_s]:
        fname = "../Saves/LevelSave.png"

        pg.image.save(stamped_surface, fname)
        print("File saved at {} ".format(fname))


    #Open New Selectable
    if keyinput[pg.K_n]:

        image_file = askopenfilename()
        image = pg.image.load(image_file).convert()
        print("Placable Updated!")


    if keyinput[pg.K_e]:

        fname = "../Saves/Export.png"

        pg.image.save(stamped_surface, fname)
        print("File saved at {} ".format(fname))
        pg.quit()


    #Recreate Terrain From File
    if keyinput[pg.K_o]:

        fileDest = askopenfilename()
        openFile = open(fileDest, "r")
        for line in openFile:
            li = line.strip()
            if li.startswith("Pec:"): #pec stands for "PyEngineCoords"
                reimgpath = (line.rstrip())
                nopecimgpath = reimgpath.replace("Pec:", "")
                print(nopecimgpath)
                image = pg.image.load(nopecimgpath).convert()
                pg.display.update()

            if li.startswith("Crdsx:"):
                xposcrds = (line.rstrip())
                xcrds = xposcrds.replace("Crdsx:", "")
                x = int(xcrds)
                print(x)
                pg.display.update()

            if li.startswith("Crdsy:"):
                yposcrds = (line.rstrip())
                ycrds = yposcrds.replace("Crdsy:", "")
                y = int(ycrds)
                print(y)
                pg.display.update()

                stamped_surface.blit(image, (xcrds, ycrds))



    elif event.type == pg.QUIT:
        running = False

    elif event.type == pg.MOUSEMOTION:
        image_rect = start_rect.move(event.pos)

    elif event.type == pg.MOUSEBUTTONDOWN:
        stamped_surface.blit(image, event.pos)
        print("Image Placed!")
        print(image_file, event.pos)
        f.write("\nPec:" + image_file + "\nCrdsx:")
        print(event.pos)

        xpos_str = str(pg.mouse.get_pos()[0])
        ypos_str = str(pg.mouse.get_pos()[1])

        f.write(xpos_str)
        f.write("\nCrdsy:")
        f.write(ypos_str)
        f.flush()



    screen.fill(black)
    screen.blit(stamped_surface, (0, 0))
    screen.blit(image, image_rect)
    pg.display.flip()

This program has a file system and certain controls to make things happen, so here they are:

ESC KEY - Auto Exports Program For Reference And Quits Program

S Key - Saves Surface as PNG file.

N Key - Prompts User to select new sprite to use

E Key - Exports Image To PNG with file prompt

O Key - Opens File With Coordinate data and image path data.

Image Of Root File System: https://i.stack.imgur.com/lUcVR.png

A Few things you should know: This program auto-saves every file position to the file that contains Coords and Image Paths.

The file system is relatively simple to work out by looking at the code, but if you need some assistance, please ask.

  • Use `print` to print out `xcrds` and `ycrds` before the line that throws the exception. Then, when the exception is thrown, you can see which values are wrong. – sloth Nov 27 '18 at 08:28
  • @sloth all values seem correct to me.. https://i.imgur.com/BcNb3sH.png – Mouse Batteries Nov 28 '18 at 06:47

1 Answers1

2

blits((source, dest, area), ...)) -> (Rect, ...) you are missing out the destination. Read here

And if you are making use of coordinates then use square brackets [x-co,y-co] like this:

block.blit(image,[0,0])
HarshitMadhav
  • 4,769
  • 6
  • 36
  • 45
  • You don't need to use `[]`s; it's actually more efficient outside of Python 2 to use `()`s. – wizzwizz4 Nov 27 '18 at 07:34
  • This still doesn't work, but if I change my code to `stamped_image(image, [0,0]` using static INTS (i mean INTS that will never change) it works, and loads in all of the images, except they are all piled on top of each other. If I use my variables (Which are converted to integers) it doesn't work. Interesting. – Mouse Batteries Nov 27 '18 at 07:40
  • 1
    @MouseBatteries Your numbers are probably too big, and it's probably appearing off-screen. – wizzwizz4 Nov 27 '18 at 18:11
  • @wizzwizz4 Possibly. But all of the images are place in the same display space as they were created in. – Mouse Batteries Nov 28 '18 at 05:26
  • @MouseBatteries I don't understand what you mean by "it doesn't work"... – wizzwizz4 Nov 28 '18 at 07:08
  • @wizzwizz4 "It doesn't work" is intended as, functioning, but not correctly. The correct images are place on the screen, just not in the correct position/at the correct coordinates. – Mouse Batteries Nov 28 '18 at 10:15
  • @MouseBatteries can you share any screenshot? – HarshitMadhav Nov 28 '18 at 19:11
  • @HarshitAgrawal Yes. What would you like a screenshot of though? – Mouse Batteries Nov 29 '18 at 05:11