如何在pygame中为关卡编辑器创建保存文件?

时间:2018-09-10 17:22:25

标签: python pygame save

所以我有一个我最近生气过的关卡编辑器,我正试图添加一个功能来保存您的工作。我尝试了酸洗,但是没用,所以我想出了一个更复杂的方法,您将在下面的代码中看到它,但是我不知道为什么它不起作用。为此编辑器创建保存功能,请添加答案,并在可能的情况下添加修改后的代码。 无论如何,这是完整的代码:

import winsound
import pygame
import time
import json

total_squares = 0
locx = []
locy = []
ctype = ['red', 'red', 'yellow']
gotkey = False
keycolor = 'yellow'
kdsw = 50
kdsh = 50
kx = 0
ky = 0
kx2 = 0
ky2 = 0
kable = False
drawingkey = False
swidth = 800
slength = 500
tx = 0
ty = 0
leftmode = False
gtl = True
drawingbadguy = False
locationx = 0
locationy = 0
bgx = 0
bgy = 0
hyes = False
hastimer = False
start_time = 0
upmode = False
tstate = 'normal'
no_transformed = 0
t_able = False
thisx = 0
thisy = 0
elapsed_time2 = 0
st = False
deg = False
egx = 400
egy = 250
endgoal = 0
lm = 0
sizex = 30
sizey = 30
playing = False
pozx = 0
pozy = 0
pxy = pozy
pxc = 0
color = 'red'
cube_list_red = []
cube_list_green = []
cube_list_purple = []
cube_list_brown = []
red_squares = []
green_squares = []
purple_squares_down = []
brown_squares_right = []
purple_squares_up = []
brown_squares_left = []
running = True

screenq = input('How big should the screen be? (mini, normal, big, large): ')
print('OK! There will be a text tutorial in 3.. 2.. 1..')
print('Welcome to pyEditor! This is the tutorial.')
print('Press E to place or move the end goal. When you are done, press E again.')
print('Press J to modify where the player spawns. Press J again when you are done.')
print('Press C to switch trough colors (Each color does something different) and click to place the color')
print('Here is the color table: ')
print('Red: You die when you touch it')
print('Green: You are teleported to a selected location (Press SHIFT while the color green is selected)')
print('Purple: You can go up it but not down / you can go down but not up (Press Z to place purple blocks that go up not down and press Z again to place purple blocks that go down)')
print('Brown: You can go left / right but no right / left (The same as purple but with X')
print('Keydoor: Press somewhere to put the keydoor and somewhere to put the key. You cannot go trough the keydoor without the key!')
print('You can press M to enable transformation ( If you press "T" while playing you can transform )')
print('You can press H to place a "Bad Guy" that goes after you (You can set Its speed with SHIFT)')
print('WIP: Press RSHIFT to place checkpoints')
print('And That IS about it!')


if screenq == 'mini':
    swidth = 500
    slength = 300
elif screenq == 'normal':
    swidth = 800
    slength = 500
elif screenq == 'big':
    swidth = 1000
    slength = 600
elif screenq == 'large':
    swidth = 1200
    slength = 700
else:
    print('Invalid Response! Screen size set to {"normal"}!')
    swidth = 800
    slength = 500

pygame.init()
screen = pygame.display.set_mode((swidth, slength))

def stop():
    playing = False
    pozx = 0
    pozy = 0

drawing_cube = False
dsp = False
jy = False
egm = False

while running:

    class Cube:
        def update(self):
            self.cx, self.cy = pygame.mouse.get_pos()
            self.square = pygame.Rect(self.cx, self.cy, 50, 50)
            locx.append(self.cx)
            locy.append(self.cy)
            if color == 'red':
                red_squares.append(self.square)
                ctype.append('red')
            elif color == 'green':
                green_squares.append(self.square)
                ctype.append('green')
            elif color == 'purple':
                if upmode:
                    purple_squares_up.append(self.square)
                    ctype.append('upPurple')
                else:
                    purple_squares_down.append(self.square)
                    ctype.append('downPurple')
            elif color == 'brown':
                if leftmode:
                    brown_squares_left.append(self.square)
                    ctype.append('leftBrown')
                else:
                    brown_squares_right.append(self.square)
                    ctype.append('rightBrown')

        def lupdate(self):
            global locx
            global locy
            global ctype

            self.cx = locx[0]
            self.cy = locy[0]
            self.square = pygame.Rect(self.cx, self.cy, 50, 50)
            print(self.square)
            if ctype == 'red':
                red_squares.append(self.square)
            else:
                print('')
            ctype.pop(0)
            locx.pop(0)
            locy.pop(0)

        def draw_red(self): 
            pygame.draw.rect(screen, (255, 0, 0), self.square)
            print(cube_list_red)
        def draw_green(self):
            pygame.draw.rect(screen, (0, 255, 0), self.square)
        def draw_purple(self):
            pygame.draw.rect(screen, (238, 130, 238), self.square)
        def draw_brown(self):
            pygame.draw.rect(screen, (165, 42, 42), self.square)

        def check_collide_red(self):
           for red_square in red_squares:
               if player.colliderect(red_square):
                   winsound.Beep(2000, 300)
                   time.sleep(0.7)
                   global playing
                   global pozx
                   global pozy
                   pozx = thisx
                   pozy = thisy
                   keycolor = 'yellow'
                   gotkey = False
                   playing = False
                   no_transformed = 0
                   tstate = 'normal'
                   print('You lost!')

        def check_collide_green(self):
            for green_square in green_squares:
                if player.colliderect(green_square):
                    global pozx
                    global pozy
                    pozx = pxc
                    pozy = pxy

        def check_collide_purple(self):
            for purple_square in purple_squares_down:
                if player.colliderect(purple_square):
                    global pozy
                    pozy = pozy + 0.40
            for purple_square in purple_squares_up:
                if player.colliderect(purple_square):
                    pozy = pozy - 0.40

        def check_collide_brown(self):
            for brown_square in brown_squares_right:
                if player.colliderect(brown_square):
                    global pozx
                    pozx = pozx + 0.40
            for brown_square in brown_squares_left:
                if player.colliderect(brown_square):
                    pozx = pozx - 0.40

    cube = Cube()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if not playing:
                total_squares = total_squares + 1
                if not jy:
                    if not egm:
                        if not hyes:
                            if color != 'keydoor':
                                cube = Cube()
                                cube.update()
                                if color == 'red':
                                    cube_list_red.append(cube)
                                elif color == 'green':
                                    cube_list_green.append(cube)
                                elif color == 'purple':
                                    cube_list_purple.append(cube)
                                elif color == 'brown':
                                    cube_list_brown.append(cube)
                                drawing_cube = True
                            else:
                                if not kable:
                                    try:
                                        ctype.remove('keydoor')
                                    except:
                                        print('')
                                    kx, ky = pygame.mouse.get_pos()
                                    locx.append(kx)
                                    locy.append(ky)
                                    ctype.append('keydoor')
                                    print('Press where you want the key to be!')
                                    kable = True
                                    time.sleep(0.3)
                                else:
                                    try:
                                        ctype.remove('key')
                                    except:
                                        print('')
                                    kable = False
                                    kx2, ky2 = pygame.mouse.get_pos()
                                    locx.append(kx2)
                                    locy.append(ky2)
                                    ctype.append('key')
                                    drawingkey = True
                                    time.sleep(0.3)
                        else:
                            bgx, bgy = pygame.mouse.get_pos()
                            locx.append(bgx)
                            locy.append(bgy)
                            ctype.append('badguy')
                            tx, ty = pygame.mouse.get_pos()
                            drawingbadguy = True
                            hyes = False
                            time.sleep(0.5)
                    else:
                        egx, egy = pygame.mouse.get_pos()
                        locx.append(egx)
                        locy.append(egy)
                        ctype.append('endgoal')
                        endgoal = pygame.Rect(egx, egy, 50, 50)
                        deg = True
                        print('End Goal set at '+str(egx)+', '+str(egy))
                        time.sleep(0.5)
                else:
                    thisx, thisy = pygame.mouse.get_pos()
                    pozx, pozy = thisx, thisy
                    time.sleep(0.5)
                    print('Set spawnPoint at '+str(thisx)+', '+str(thisy))

    key = pygame.key.get_pressed()
    if key[pygame.K_c]:
        if not playing:
            if color == 'red':
                color = 'green'
                time.sleep(0.5)
                print(color)
            elif color == 'green':
                color = 'purple'
                time.sleep(0.5)
                print(color)
            elif color == 'purple':
                color = 'brown'
                time.sleep(0.5)
                print(color)
            elif color == 'brown':
                color = 'keydoor'
                time.sleep(0.5)
                print(color)
            elif color == 'keydoor':
                color = 'red'
                time.sleep(0.5)
                print(color)

    elif key[pygame.K_r]:
        cube_list_red.clear()
        cube_list_green.clear()
        cube_list_purple.clear()
        cube_list_brown.clear()
        red_squares.clear()
        green_squares.clear()
        purple_squares_up.clear()
        purple_squares_down.clear()
        brown_squares_left.clear()
        brown_squares_right.clear()
        ctype.clear()
        locx.clear()
        locy.clear()
        total_squares = 0
        drawingkey = False
    elif key[pygame.K_u]:
        if not playing:
            total_squares = total_squares - 1
            if color == 'red':
                if len(cube_list_red) > 0:
                    ctype.remove('red')
                    cube_list_red.pop()
                    red_squares.pop()
                    time.sleep(0.5)
            elif color == 'green':
                if len(cube_list_green) > 0:
                    ctype.remove('green')
                    cube_list_green.pop()
                    green_squares.pop()
                    time.sleep(0.5)
            elif color == 'purple':
                if len(cube_list_purple) > 0:
                    cube_list_purple.pop()
                    if upmode:
                        ctype.remove(upPurple)
                        purple_squares_up.pop()
                    else:
                        ctype.remove(downPurple)
                        purple_squares_down.pop()
                    time.sleep(0.5)
            elif color == 'brown':
                if len(cube_list_brown) > 0:
                    cube_list_brown.pop()
                    if leftmode:
                        ctype.remove('leftBrown')
                        brown_squares_left.pop()
                    else:
                        ctype.remove('rightBrown')
                        brown_squares_right.pop()
                time.sleep(0.5)
            elif color == 'keydoor':
                ctype.remove('keydoor')
                ctype.remove('key')
                drawingkey = False
                time.sleep(0.5)
    elif key[pygame.K_p]:
        bgx, bgy = tx, ty
        playing = True
        start_time = time.time()
    elif key[pygame.K_9]:
        playing = False
        pozx = thisx
        pozy = thisy
        no_transformed = 0
        tstate = 'normal'
        keycolor = 'yellow'
        gotkey = False
    if key[pygame.K_w] == True:
        if pozy >= 0 and playing != False:
            pozy = pozy - 0.40
            lm = 1
    if key[pygame.K_a] == True:
        if pozx >= 0 and playing != False:
            pozx = pozx - 0.40
            lm = 0
    if key[pygame.K_s] == True:
        if pozy <= slength - sizey and playing != False:
            pozy = pozy + 0.40
            lm = 0
    if key[pygame.K_d] == True and playing != False:
        if pozx <= swidth - sizex:
            pozx = pozx + 0.40
            lm = 0
    elif key[pygame.K_LSHIFT] and not playing:
        if color == 'green':
            cht = input('Where do you want the player to teleport when touching a green block? (type "middle", "middle top", "middle down", "middle left", "middle right", "top left", "top right", "down right", "down left"): ')
            if cht == 'middle':
                pxc = swidth/2
                pxy = slength/2
            elif cht == 'middle top':
                pxc = swidth/2
                pxy = 0
            elif cht == 'middle down':
                pxc = swidth/2
                pxy = slength
            elif cht == 'middle left':
                pxc = swidth
                pxy = slength/2
            elif cht == 'middle right':
                pxc = swidth
                pxy = slength/2
            elif cht == 'top left':
                pxc = 0
                pxy = 0
            elif cht == 'top right':
                pxc = swidth
                pxy = 0
            elif cht == 'down left':
                pxc = 0
                pxy = slength
            elif cht == 'down right':
                pxc = swidth
                pxy = slength
            else:
                print('Invalid Syntax!')
        elif color == 'keydoor':
            kdsw = input('How many pixels wide should the keydoor be? (default is 50): ')
            kdsh = input('How many pixels long should the keydoor be? (default is 50): ')
            print('All Set!')

    elif key[pygame.K_j]:
        if jy == False and not playing:
            jy = True
            print('Spawn Point mode activated')
            time.sleep(0.5)
        else:
            if not playing:
                jy = False
                print('Spawn Point mode deactivated')
                time.sleep(0.5)
    elif key[pygame.K_e]:
        if not jy and not playing:
            if egm == False:
                egm = True
                print('End Goal mode activated')
                time.sleep(0.5)
            else:
                egm = False
                print('End Goal mode deactivated')
                time.sleep(0.5)
    elif key[pygame.K_m]:
        if not playing:
            question = input('Should the player be able to transform? (Y / N): ')
            if question == 'Y':
                t_able = True
                q2 = input('Ok! How many times can they do that?: ')
                print('All set!')
            elif question == 'N':
                t_able = False
                print('Ok!')
            else:
                print('Invalid Syntax!')
                t_able = False
    elif key[pygame.K_t]:
        if playing and t_able:
            if no_transformed < int(q2):
                if tstate == 'normal':
                    tstate = 'transformed'
                    sizex = 10
                    sizey = 50
                    no_transformed = no_transformed + 1
                    time.sleep(0.2)
                else:
                    tstate = 'normal'
                    sizex = 30
                    sizey = 30
                    no_transformed = no_transformed + 1
                    time.sleep(0.2)
            else:
                print('You reached the limit of transforming!')
                time.sleep(0.5)
    elif key[pygame.K_z] == True and not playing:
        if upmode == False:
            print('Purple UpMode has been activated!')
            upmode = True
            time.sleep(0.5)
        else:
            print('Purple UpMode has been deactivated!')
            upmode = False
            time.sleep(0.5)
    elif key[pygame.K_0] and not playing:
        seconds = input('How much should the timer last in seconds?: ')
        hastimer = True
    elif key[pygame.K_h]:
        print('Press where you want to place the bad & moving guy')
        hyes = True
        time.sleep(0.3)
    elif key[pygame.K_x]:
        if not playing:
            if leftmode == False:
                print('Brown LeftMode has been activated!')
                leftmode = True
                time.sleep(0.3)
            else:
                print('Brown LeftMode has been deactivated!')
                leftmode = False
                time.sleep(0.3)

    elif key[pygame.K_1] and not playing:
        saveorload = input('Would you like to save or load?: ')
        if saveorload == 'save':
            with open('thisfile.txt', 'w+') as filehandler:
                json.dump([locx, locy, ctype, thisx, thisy, total_squares], filehandler)
                print('Saved!')
        elif saveorload == 'load':
            with open('thisfile.txt', 'r') as filehandler:
                locx, locy, ctype, thisx, thisy, total_squares = json.load(filehandler)
                print('Variables loaded! Drawing cubes.. Please wait!')
                pozx = thisx
                pozy = thisy
                print(total_squares)
                for i in range(total_squares):
                    cube.lupdate()
                    if ctype[0] == 'red':
                        cube_list_red.append(cube)
                        print(cube_list_red)


    if drawingbadguy and playing:
        if pozx > bgx:
            bgx = bgx + 0.20
        if pozx < bgx:
            bgx = bgx - 0.20
        if pozy > bgy:
            bgy = bgy + 0.20
        if pozy < bgy:
            bgy = bgy - 0.20

    screen.fill((0, 0, 255))
    player = pygame.Rect(pozx, pozy, sizex, sizey)
    if drawing_cube: 
        for cube in cube_list_red:
            cube.draw_red()
        for cube in cube_list_green:
            cube.draw_green()
        for cube in cube_list_purple:
            cube.draw_purple()
        for cube in cube_list_brown:
            cube.draw_brown()

    if deg:
        pygame.draw.rect(screen, (0, 0, 0), endgoal)
    if drawingbadguy:
        badguy = pygame.Rect(bgx, bgy, 40, 40)
        pygame.draw.rect(screen, (255, 99, 71), badguy)
    if drawingkey:
        keydoor = pygame.Rect(kx, ky, int(kdsw), int(kdsh))
        key = pygame.Rect(kx2, ky2, 10, 10)
        pygame.draw.rect(screen, (243, 239, 224), keydoor)
        if keycolor == 'yellow':
            pygame.draw.rect(screen, (255, 255, 0), key)
        else:
            pygame.draw.rect(screen, (0, 0, 255), key)

    if playing:
        elapsed_time = time.time() - start_time
        if hastimer:
            if int(elapsed_time) >= int(seconds):
                print("Time's Up!")
                playing = False
                pozx = thisx
                pozy = thisy
                time.sleep(0.5)

        pygame.draw.rect(screen, (0, 0, 0), player)
        cube.check_collide_red()
        cube.check_collide_green()
        cube.check_collide_purple()
        cube.check_collide_brown()
        if drawingbadguy:
            if player.colliderect(badguy):
                playing = False
                pozx = thisx
                pozy = thisy
        if drawingkey and keycolor == 'yellow':
            if player.colliderect(key):
                keycolor = 'blue'
                gotkey = True
                print('You got the key!')
        if drawingkey and player.colliderect(keydoor):
            if gotkey:
                gotkey = True
            else:
                print('Nope')
                pozx = thisx
                pozy = thisy
        try:
            if player.colliderect(endgoal):
                print('You won!')
                gotkey = False
                keycolor = 'yellow'
                time.sleep(0.7)
                playing = False
                pozx = thisx
                pozy = thisy
                no_transformed = 0
                tstate = 'normal'
        except:
            print('Could not find end goal!')
            playing = False

    pygame.display.flip()



pygame.quit()

如果您能帮助我直到星期四,将不胜感激!谢谢!

0 个答案:

没有答案