Can't change/append data (integers) from python to .json file
I am currently making a save/load state of my game. I am using dictionaries and .json to save my data to a file. I am trying to add coins to the overall player statistics. Whenever the player collects the coins, they need to be saved to the player stats file. However, once I reload the game, the stats are back to their base ones. I have tried saving and loading back the data, but it doesn't seem to work. Any help is appreciated.
import json
import sys
pygame.init()
DARK_GREY = 58, 58, 58
coins_group = pygame.sprite.Group()
pygame.display.set_caption("My Game")
screen = pygame.display.set_mode((900, 600))
screen.fill(DARK_GREY)
tile_size = 50
class Level:
def __init__(self, data):
# Creating a list for the tiles
self.tile_list = []
# Loading block images
dirt_block = pygame.image.load(r"Blocks\dirt_block.png")
grass_block = pygame.image.load(r"Blocks\grass_block.png")
invisible_block = pygame.image.load(r"Blocks\invisible_barrier.png")
platform1_block = pygame.image.load(r"Blocks\platform_block1.png")
row_count = 0
# Assigns the values in the array with certain properties
for row in data:
col_count = 0
for tile in row:
if tile == 1: # Dirt Block
pass
if tile == 2: # Grass Block
pass
if tile == 3: # Invisible Barrier Block
pass
if tile == 4: # Platform Block
image = pygame.transform.scale(platform1_block, (tile_size, tile_size))
image_rect = image.get_rect()
image_rect.x = col_count * tile_size
image_rect.y = row_count * tile_size
tile = (image, image_rect)
self.tile_list.append(tile)
if tile == 5: # Coin
coin = Coin(col_count * tile_size + (tile_size // 2), row_count * tile_size + (tile_size // 2))
coins_group.add(coin)
col_count += 1
row_count += 1
def draw(self):
for tile in self.tile_list:
screen.blit(tile[0], tile[1])
level_data = [
[3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
[3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3],
[3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3],
[3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3],
[3, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3],
[3, 4, 4, 4, 0, 4, 4, 4, 0, 0, 5, 0, 0, 0, 0, 0, 0, 3],
[3, 0, 0, 0, 0, 4, 4, 4, 0, 0, 4, 4, 4, 4, 0, 0, 0, 3],
[3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 4, 3],
[3, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 4, 4, 3],
[3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 0, 4, 4, 3],
[3, 0, 0, 0, 0, 4, 4, 4, 4, 0, 0, 4, 4, 4, 0, 4, 4, 3],
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
]
world = Level(level_data)
class Sprite(pygame.sprite.Sprite):
def __init__(self, image, x, y):
super().__init__()
self.image = pygame.image.load(image)
self.rect = self.image.get_rect()
def update(self):
pass
def draw(self, display):
display.blit(self.image, self.rect)
class Player(Sprite):
def __init__(self, x, y, level, health, damage, coins, skill_points):
super().__init__(r"Knight\Stand Up\stand_up_10.png", x, y)
# Player stats
self.level = level
self.health = health
self.damage = damage
self.coins = coins
self.skill_points = skill_points
# Health system attributes
self.current_health = 100
self.maximum_health = self.health
self.health_bar_length = 100
self.health_ratio = self.maximum_health // self.health_bar_length
# Idle image setup
self.idle_image = self.image
# Character attributes used when moving left and right, as well as jumping
self.speed = 6
self.jump_speed = 12
self.y_speed = 0
self.jumped = False
def update(self):
dx = 0
dy = 0
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
self.facing_left = True
dx = -self.speed
elif key[pygame.K_RIGHT]:
self.facing_left = False
dx += self.speed
else:
if not self.facing_left:
self.image = self.idle_image
else:
self.image = pygame.transform.flip(self.idle_image, True, False)
if key[pygame.K_UP] and not self.jumped:
self.y_speed = -self.jump_speed
self.jumped = True
# Checks and applies gravity
self.y_speed += 1
if self.y_speed > 15:
self.y_speed = 15
dy += self.y_speed
# Checks and applies collision
for tile in world.tile_list:
# Detection in the x direction
if tile[1].colliderect(self.rect.x + dx, self.rect.y, self.player_width, self.player_height):
dx = 0
# Detection in the y direction
if tile[1].colliderect(self.rect.x, self.rect.y + dy, self.player_width, self.player_height):
if self.y_speed < 0:
dy = tile[1].bottom - self.rect.top
self.y_speed = 0
elif self.y_speed >= 0:
dy = tile[1].top - self.rect.bottom
self.jumped = False
# Updates movement
self.rect.x += dx
self.rect.y += dy
def save_to_json(self, filename):
# Creating a dictionary to store all the data there
player_dictionary = {'level': self.level, 'health': self.health, 'damage': self.damage, 'coins': self.coins, 'skill_points': self.skill_points}
# Writing the data in a file using json
with open(filename, "a+") as f:
f.write(json.dumps(player_dictionary, indent=2))
def load_from_json(self, filename):
# Reading the data in a file using json
with open(filename, 'r') as f:
player_data = json.loads(f.read())
# Updating the attributes (stats) of the player by looking up the data in the dictionary
self.level = player_data['level']
self.health = player_data['health']
self.damage = player_data['damage']
self.coins = player_data['coins']
self.skill_points = player_data['skill_points']
def collect_coin(self, amount):
self.coins += amount
self.save_to_json(r"Player_stats.json")
def execute_player(self):
self.update()
self.draw(screen)
def update_game():
pygame.display.flip()
clock.tick(FPS)
pygame.event.pump()
pygame.display.update()
def demo_level():
player.load_to_json("Player_stats.json")
coin_image = pygame.image.load(r"Blocks\coin.png")
coin_scale = pygame.transform.scale(coin_image, (50, 50))
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if pause_button.is_clicked(event):
navigation(DARK_GREY)
pause_menu()
# Overlay
screen.fill(LIGHT_BLUE)
world.draw()
coins_group.draw(screen)
screen.blit(coin_scale, (10, 80))
coins_text = text(f"{player_stats['coins']}", 60, 80, 85)
if pygame.sprite.spritecollide(player, coins_group, True):
player.coins += 1
player.save_to_json("Player_stats.json")
# Player commands
player.execute_player()
# Updating the screen
update_game()
Replace the a+
with w
in the with open(filename, "a+")
part. a+
instructs python to append to an existing file, which results in an invalid json file after saving twice.