Compare commits

...

37 Commits

Author SHA1 Message Date
Shadow15510 bb382622bc Merge branch 'dev' 2023-01-05 15:51:55 +01:00
Shadow15510 28d9eb5231 Minor fix 2023-01-05 15:26:10 +01:00
Shadow15510 77d99659a9 Merge branch 'dev' 2022-12-20 11:32:48 +01:00
Shadow15510 f2c74bbea5 Minor modification on the gestion of the screen's size 2022-12-20 11:27:59 +01:00
Shadow15510 1b0a3a3500 Merge branch 'dev' 2022-12-11 23:15:57 +01:00
Shadow15510 a2e02f3030 Update README 2022-07-16 11:11:31 +02:00
Shadow15510 a42aceeeab Merge branch 'dev' 2022-07-15 22:40:06 +02:00
Shadow15510 af27d031be Enhance behavior gestion 2022-07-15 22:33:57 +02:00
Shadow15510 bf7bad73b7 Revision of 'follow' behavior 2022-07-13 10:30:16 +02:00
Shadow15510 2d670448b2 Fix deadlock with 'follow' 2022-07-12 12:58:21 +02:00
Shadow15510 a8e0d374ac Merge branch 'dev' 2022-07-12 11:05:59 +02:00
Shadow15510 3ad286dd5a Add some extra functions 2022-07-12 11:00:46 +02:00
Shadow15510 088c29a6e3 Add customisable screen size 2022-04-18 12:07:51 +02:00
Shadow15510 0fb38d9fd7 Add a customisable low bar 2022-04-17 22:24:07 +02:00
Shadow15510 7a3388fa76 Add a customisable low bar 2022-04-17 22:16:46 +02:00
Shadow15510 d4af0f34f1 Merge branch 'dev' 2022-02-28 14:40:34 +01:00
Shadow15510 1e26a80982 Add some new animations 2022-02-28 14:39:18 +01:00
Shadow15510 377be90983 Merge branch 'dev' 2022-02-27 13:54:17 +01:00
Shadow15510 b74816619b Fix version 2022-02-27 13:53:49 +01:00
Shadow15510 ced6c831d3 Merge branch 'dev' 2022-02-27 13:43:57 +01:00
Shadow15510 1984d7ce6c Improve new entity gestion 2022-02-27 11:58:37 +01:00
Shadow15510 8eb6ff15cc Merge branch 'dev' 2022-02-27 09:58:40 +01:00
Shadow15510 02c7af8007 Changes on entities gestion 2022-02-27 09:38:05 +01:00
Shadow15510 782a17ca6c Merge branch 'dev' 2022-01-30 13:40:49 +01:00
Shadow15510 b652c1fabe Improve entities' behaviors, redesign print_text function for an iterative version and other minor fixes 2022-01-30 13:18:19 +01:00
Shadow15510 ce8cd99f3c fix bug on multi-move 2022-01-29 11:54:54 +01:00
Shadow15510 f21fefddf9 fix bug on multi-move 2022-01-29 11:50:15 +01:00
Shadow15510 527dc376eb Simplify syntax 2022-01-29 11:26:55 +01:00
Shadow15510 faf1500ddc Cleaning asci and simplify syntax 2022-01-29 11:18:53 +01:00
Shadow15510 70e9a1a3a0 Add an automap.sh script to automatically convert *.tmx into asci-friendly *.py files 2022-01-29 10:55:46 +01:00
Shadow15510 07601114c4 Merge branch 'dev' 2022-01-28 23:14:03 +01:00
Shadow15510 faa5ffa23e Minor fixes 2022-01-28 23:12:59 +01:00
Shadow15510 b5dc823078 Add entities gestion and basic animations. Unify the coordinates system 2022-01-28 19:18:41 +01:00
Shadow15510 134393ec60 Update samples with new entities system 2022-01-28 19:17:48 +01:00
Shadow15510 92d27edc3d Update the Tiled converter to support the new map format 2022-01-28 19:17:10 +01:00
Shadow15510 453b916db9 minor fix on samples 2022-01-28 12:36:05 +01:00
Shadow15510 a529038ee2 Change on entities system and update samples 2022-01-28 12:33:28 +01:00
9 changed files with 561 additions and 241 deletions

View File

@ -18,7 +18,7 @@ Tout le projet est soumis à la licence GNU General Public Licence v3.0.
### Utilisation
Tout est détaillé dans [le wiki du projet](https://gitea.planet-casio.com/Shadow15510/Asci/wiki/Cr%C3%A9ation-d%27un-jeu-de-r%C3%B4le-avec-Asci).
Tout est détaillé dans [le wiki du projet](https://gitea.planet-casio.com/Shadow15510/Asci/wiki/Home).
### Exemples

477
asci.py
View File

@ -1,101 +1,68 @@
# Asci (version 1.6.3)
# Asci (1.9.3)
from math import floor, ceil
class Screen:
def __init__(self, screen_width=21, screen_height=6):
# Screen configuration
self.screen_width = screen_width
self.screen_height = screen_height
self._data = [[" " for _ in range(screen_width)] for _ in range(screen_height)]
def clear(self):
print("\n" * self.screen_height)
def set_world(self, world):
self._world = [[char for char in line] for line in world.split("\n")[1:]]
self.map_width = max([len(line) for line in self._world])
self.map_height = len(self._world)
def set_data(self, coords):
x, y = coords
for x_map in range(x, x + self.screen_width):
for y_map in range(y, y + self.screen_height):
self._data[y_map - y][x_map - x] = " "
if 0 <= x_map < self.map_width and 0 <= y_map < self.map_height:
try: self._data[y_map - y][x_map - x] = self._world[y_map][x_map]
except: pass
def set_cell(self, x, y, value):
self._data[y][x] = value
def display(self, return_input=True):
for line in self._data:
print("".join(line))
if return_input: return input(">")
def display_text(self, string):
paragraphs = [i for i in text_formater(string) if i]
nb_par = len(paragraphs)
for index in range(nb_par):
self.clear()
print(paragraphs[index])
if index + 1 == nb_par: return input(">")
else: input()
def get_cell(self, x, y):
return self._data[y][x]
def get_map_size(self):
return self.map_width, self.map_height
SCREEN_WIDTH = 21
SCREEN_HEIGHT = 7
class Asci:
def __init__(self, maps, events_mapping, keys_mapping, screen_width=21, screen_height=6):
# Load maps
def __init__(self, maps, entities, events_mapping, keys_mapping, behaviors=None):
# Load maps and entities
self.maps = [Map(*i) for i in maps]
self.entities = {}
entity_id = 0
for i in entities:
if not i[0]:
i[0] = entity_id
entity_id += 1
if i[0] in self.entities: raise KeyError("'{}' is already a registered entities".format(i[0]))
else: self.entities[i[0]] = Entity(*i)
# Custom functions
self.legend = list(events_mapping.keys())
self._game_events_mapping = [events_mapping[i] for i in self.legend]
self._legend = list(events_mapping.keys())
self._game_events_mapping = [events_mapping[i] for i in self._legend]
self._game_keys_mapping = {key: keys_mapping[key] for key in keys_mapping if not key in (1, 2, 3, 5)}
# Custom entities behavior
self._behaviors = {"permanent": permanent, "stand by": stand_by, "follow": follow, "walk between": walk_between, "walk to": walk_to, "follow by player": follow_by_player}
if behaviors:
for i in behaviors: self._behaviors[i] = behaviors[i]
# Screen initialisation
self.screen = Screen(screen_width, screen_height)
self.screen = Screen()
self.current_map = None
def _looked_case(self, direction):
# Left
if direction == 1:
return self.data[2] + 9, self.data[3] + 3
if direction == 1: # Left
return self.data[2] - 1, self.data[3]
# Right
elif direction == 3:
return self.data[2] + 11, self.data[3] + 3
elif direction == 3: # Right
return self.data[2] + 1, self.data[3]
# Up
elif direction == 5:
return self.data[2] + 10, self.data[3] + 2
elif direction == 5: # Up
return self.data[2], self.data[3] - 1
# Down
elif direction == 2:
return self.data[2] + 10, self.data[3] + 4
elif direction == 2: # Down
return self.data[2], self.data[3] + 1
return self.data[2] + 10, self.data[3] + 3
return self.data[2], self.data[3]
def _cell_test(self, direction):
if direction == 1:
if self.data[-2] + 9 < 0: return -1
else: cell = self.screen.get_cell(9, 3)
if self.data[2] - 1 < 0: return -1
else: cell = self.screen.get_cell(self.data[2] - 1, self.data[3])
if direction == 3:
if self.data[-2] + 11 >= self.map_width: return -1
else: cell = self.screen.get_cell(11, 3)
if self.data[2] + 1 >= self.map_width: return -1
else: cell = self.screen.get_cell(self.data[2] + 1, self.data[3])
if direction == 5:
if self.data[-1] + 2 < 0: return -1
else: cell = self.screen.get_cell(10, 2)
if self.data[3] - 1 < 0: return -1
else: cell = self.screen.get_cell(self.data[2], self.data[3] - 1)
if direction == 2:
if self.data[-1] + 4 >= self.map_height: return -1
else: cell = self.screen.get_cell(10, 4)
if self.data[3] + 1 >= self.map_height: return -1
else: cell = self.screen.get_cell(self.data[2], self.data[3] + 1)
cell_patterns = self.legend
cell_patterns = self._legend
for pattern_index in range(len(cell_patterns)):
if cell in cell_patterns[pattern_index]: return pattern_index
@ -107,18 +74,16 @@ class Asci:
cell_test = self._cell_test(key)
# Move
if cell_test == len(self.legend) - 1:
if cell_test == len(self._legend) - 1:
if key == 1: self.data[2] -= 1
if key == 3: self.data[2] += 1
if key == 5: self.data[3] -= 1
if key == 2: self.data[3] += 1
# Change map
elif interaction and cell_test == len(self.legend) - 2: # or (self.data[1] and cell_test < 0):
self.data[1], self.data[2], self.data[3] = self._get_map(key)
self.screen.set_world(self.maps[self.data[1]].map_data)
self.map_width, self.map_height = self.screen.get_map_size()
if key == 2: self.data[3] += 1
# Change map
elif interaction and cell_test == len(self._legend) - 2:
new_map, self.data[2], self.data[3] = self._get_map(key)
if self.data[1] != new_map: self._change_map(new_map)
# Interaction
elif interaction and cell_test >= 0: self._interaction(key, cell_test)
@ -128,12 +93,39 @@ class Asci:
self.screen.clear()
self._game_keys_mapping[key](self.data, self.stat)
def _get_map(self, direction):
current_coords = self._looked_case(direction)
for coords in self.current_map.coords:
if coords[:2] == current_coords:
return coords[2], coords[3], coords[4]
return self.data[1], self.data[2], self.data[3]
def _change_map(self, new_map):
# Update map id and data
old_map, self.data[1] = self.data[1], new_map
self.current_map = self.maps[self.data[1]]
self.current_map.entities = {}
# Update entities
for i in self.entities:
entity = self.entities[i]
if entity.map_id == old_map and entity.behavior == "follow":
entity.pos_x = entity.pos_y = -1
entity.map_id = new_map
if entity.map_id == new_map: self.current_map.entities[i] = entity
# Update screen configuration
self.screen.set_world(self.current_map.map_data)
self.map_width, self.map_height = self.screen.get_map_size()
def _interaction(self, direction, cell_content):
x, y = self._looked_case(direction)
data_copy = [self.data[0], self.data[1], x, y]
data_copy = [self.data[0], self.data[1], x, y, self.data[4]]
# Get the event
event = self._game_events_mapping[cell_content](data_copy, self.stat)
event = self._game_events_mapping[cell_content](data_copy, self.stat, self.current_map.entities, self._get_entity_id(x, y))
if type(event) == tuple:
quest, event = event
else:
@ -142,12 +134,10 @@ class Asci:
# data modification
self.data[0] = data_copy[0]
if self.data[1] != data_copy[1]:
self.data[1] = data_copy[1]
self.screen.set_world(self.maps[self.data[1]].map_data)
self.map_width, self.map_height = self.screen.get_map_size()
self._change_map(data_copy[1])
if data_copy[2] != x: self.data[2] = data_copy[2] - 10
if data_copy[3] != y: self.data[3] = data_copy[3] - 3
if data_copy[2] != x: self.data[2] = data_copy[2]
if data_copy[3] != y: self.data[3] = data_copy[3]
if not event: return
event = read_event(self.data, event, quest)
@ -164,17 +154,13 @@ class Asci:
self.data[0][quest] += answer_selected
self._interaction(direction, cell_content)
def _get_map(self, direction):
current_coords = self._looked_case(direction)
current_map = self.data[1]
def _get_entity_id(self, x, y):
for entity in self.current_map.entities.values():
if entity.pos_x == x and entity.pos_y == y:
return entity.entity_id
for coords in self.maps[current_map].coords:
if coords[:2] == current_coords:
return coords[2], coords[3] - 10, coords[4] - 3
return current_map, self.data[2], self.data[3]
def mainloop(self, end_game, stat=None, data=None, routine=None, player="@", door="^", walkable=" ", exit_key=9, multi_move="."):
# Mainloop
def mainloop(self, end_game, stat=None, data=None, routine=None, low_bar=None, player="@", door="^", walkable=" ", exit_key=9, multi_move="."):
if exit_key in self._game_keys_mapping:
raise ValueError("'{}' is already assigned to a function.".format(exit_key))
@ -182,40 +168,121 @@ class Asci:
if not stat or type(stat) != list: self.stat = [100]
else: self.stat = stat
if not data: self.data = [{"main": 0}, 0, 0, 0]
else: self.data = [data[0], data[1], data[2] - 10, data[3] - 3]
if not data: self.data = [{"main": 0}, 0, 0, 0, 0]
else: self.data = [data[0], data[1], data[2], data[3], 0]
self.legend.append(door)
self.legend.append(walkable)
# Configuration
self._legend.append(door)
self._legend.append(walkable)
self._change_map(self.data[1])
self.screen.load_data(self.data)
# Screen and map configuration
self.screen.set_world(self.maps[self.data[1]].map_data)
self.map_width, self.map_height = self.screen.get_map_size()
key = key_buffer = 0
key = 0
while key != exit_key and self.stat[0] > 0 and self.data[0]["main"] < end_game:
self.screen.set_data(self.data[-2:])
# Update the map
self.screen.set_screen()
# Compute the player's and entities' positions
data_copy = self.data[:]
for entity in self.current_map.entities.values():
self._behaviors[entity.behavior](entity, data_copy, self.stat, self.screen, walkable)
if entity.map_id == self.data[1] and (0 <= entity.pos_x - self.data[2] + self.screen.pos_player[0] < SCREEN_WIDTH) and (0 <= entity.pos_y - self.data[3] + self.screen.pos_player[1] < SCREEN_HEIGHT):
self.screen.set_cell(entity.pos_x, entity.pos_y, entity.symbol)
self.screen.set_cell(10, 3, player)
key = convert(self.screen.display())
if not key: key = key_buffer
else: key_buffer = key
self.screen.set_cell(self.data[2], self.data[3], player)
# Display map, low bar, get the key and update key buffer
if low_bar: bar = low_bar(self.data[:], self.stat[:])
else: bar = None
key = convert(self.screen.display(low_bar=bar))
if not key: key = self.data[4]
else: self.data[4] = key
# Multi-move and key gestion
if type(key) == str and key[0] == multi_move:
for i in list(key[1:]):
self._keyboard(convert(i), False)
key = key[1:]
for k, r in get_multi_move(key):
for _ in range(r):
self._keyboard(k, False)
self.screen.set_screen()
self.data[4] = k
else:
self._keyboard(key)
# Launching the game routine
if routine: routine(self.data, self.stat)
if routine:
data_copy = self.data[:]
routine(data_copy, self.stat)
if self.stat[0] <= 0: self.stat[0] = 100
self.data[2] += 10
self.data[3] += 3
return self.stat, self.data
return self.stat, self.data[:-1]
# Classes used by Asci
class Screen:
def __init__(self):
# Screen configuration
self.pos_player = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
self._on_screen = [[" " for _ in range(SCREEN_WIDTH)] for _ in range(SCREEN_HEIGHT)]
self._asci_data = []
def load_data(self, data):
self._asci_data = data
def get_map_size(self):
return self.map_width, self.map_height
def set_world(self, world):
self._world = [[char for char in line] for line in world.split("\n")[1:]]
self.map_width = max([len(line) for line in self._world])
self.map_height = len(self._world)
def set_screen(self):
x = self._asci_data[2] - self.pos_player[0] ; y = self._asci_data[3] - self.pos_player[1]
for x_map in range(x, x + SCREEN_WIDTH):
for y_map in range(y, y + SCREEN_HEIGHT):
self._on_screen[y_map - y][x_map - x] = " "
if 0 <= x_map < self.map_width and 0 <= y_map < self.map_height:
try: self._on_screen[y_map - y][x_map - x] = self._world[y_map][x_map]
except: pass
def display(self, return_input=True, low_bar=None):
for line_no in range(len(self._on_screen)):
line = "".join(self._on_screen[line_no])
if line_no + 1 == SCREEN_HEIGHT and return_input:
if not low_bar: line = line[:-6] + ">"
else: line = low_bar + ">"
print(line, end="")
return input()
else:
print(line)
def clear(self):
print("\n" * SCREEN_HEIGHT)
def display_text(self, string):
paragraphs = [i for i in text_formater(string) if i]
nb_par = len(paragraphs)
for index in range(nb_par):
self.clear()
print(paragraphs[index])
if index + 1 == nb_par: return input(">")
else: input()
def set_cell(self, x, y, value):
x = x - (self._asci_data[2] - self.pos_player[0])
y = y - (self._asci_data[3] - self.pos_player[1])
if 0 <= x < SCREEN_WIDTH and 0 <= y < SCREEN_HEIGHT:
self._on_screen[y][x] = value
def get_cell(self, x, y):
x = x - (self._asci_data[2] - self.pos_player[0])
y = y - (self._asci_data[3] - self.pos_player[1])
if 0 <= x < SCREEN_WIDTH and 0 <= y < SCREEN_HEIGHT:
return self._on_screen[y][x]
else: return " "
class Event:
@ -230,8 +297,29 @@ class Map:
def __init__(self, map_data, *coords):
self.map_data = map_data
self.coords = coords
self.entities = {}
class Entity:
def __init__(self, entity_id, symbol, map_id, x, y, behavior, *args):
self.entity_id = entity_id
self.symbol = symbol
self.map_id = map_id
self.pos_x = x
self.pos_y = y
self.behavior = behavior
self.args = list(args)
def change_behavior(self, new_behavior, *args):
if self.behavior != "permanent":
self.behavior = new_behavior
self.args = list(args)
def teleport(self, map_id, x, y):
if self.behavior != "permanent": self.map_id, self.pos_x, self.pos_y = map_id, x, y
# Functions used by Asci
def convert(string, force_int=False):
try: return int(string)
except:
@ -239,28 +327,35 @@ def convert(string, force_int=False):
else: return string
def text_formater(string, screen_width=21, screen_height=6):
def text_formater(string):
screen_displayable_height = SCREEN_HEIGHT - 1
def line_formater(string, screen_width):
if len(string) <= screen_width: return string
def line_formater(string):
string_result = ""
while len(string) > SCREEN_WIDTH:
stop_index = SCREEN_WIDTH
while stop_index > 0 and not string[stop_index].isspace(): stop_index -= 1
if not stop_index: stop_index = SCREEN_WIDTH
stop_index = screen_width
while stop_index > 0 and not string[stop_index].isspace(): stop_index -= 1
if not stop_index: stop_index = screen_width
return string[:stop_index].strip() + "\n" + line_formater(string[stop_index:].strip(), screen_width)
string_result += string[:stop_index].strip() + "\n"
string = string[stop_index:].strip()
def paragraph_formater(lines, screen_height):
if len(lines) < screen_height: return "\n".join(lines)
return string_result + string
return "\n".join(lines[:screen_height]) + "\n\n" + paragraph_formater(lines[screen_height:], screen_height)
def paragraph_formater(lines):
paragraphs = ""
while len(lines) >= screen_displayable_height:
paragraphs += "\n".join(lines[:screen_displayable_height]) + "\n\n"
lines = lines[screen_displayable_height:]
return paragraphs + "\n".join(lines)
lines = []
for line in string.split("\n"):
for formated_line in line_formater(line, screen_width).split("\n"):
for formated_line in line_formater(line).split("\n"):
lines.append(formated_line)
return paragraph_formater(lines, screen_height).split("\n\n")
return paragraph_formater(lines).split("\n\n")
def read_event(data, event, quest):
@ -277,6 +372,109 @@ def read_event(data, event, quest):
return Event(*event)
def get_multi_move(key):
if "," in key:
result = []
for k in key.split(","):
if "*" in k:
k = k.split("*")
result.append((convert(k[0]), convert(k[1])))
else:
result.append((convert(k), 1))
return result
elif "*" in key:
key = key.split("*")
return [(convert(key[0]), convert(key[1]))]
else:
return [(convert(k), 1) for k in key]
# Motions functions
def stand_by(entity, data, stat, screen, walkable):
pass
def permanent(entity, data, stat, screen, walkable):
pass
def follow(entity, data, stat, screen, walkable):
if entity.pos_x == entity.pos_y == -1:
entity.pos_x, entity.pos_y = data[2], data[3]
elif data[4] in (1, 2, 3, 5):
direction = (data[4] - 1) if data[4] != 5 else 3
if entity.args: walkable += entity.args[0]
cases = [(data[2] + 1, data[3]), (data[2], data[3] - 1), (data[2] - 1, data[3]), (data[2], data[3] + 1)]
pos = cases[direction]
if not (0 <= pos[0] < screen.map_width and 0 <= pos[1] < screen.map_height) or (not screen.get_cell(pos[0], pos[1]) in walkable):
find = False
cases.remove(cases[(direction + 2) % 4])
for pos in cases:
if (0 <= pos[0] < screen.map_width and 0 <= pos[1] < screen.map_height) and (screen.get_cell(pos[0], pos[1]) in walkable):
find = True
entity.pos_x, entity.pos_y = pos
break
if not find:
entity.pos_x, entity.pos_y = data[2], data[3]
else:
entity.pos_x, entity.pos_y = pos
def walk_between(entity, data, stat, screen, walkable):
frame = (entity.args[0] + 1) % len(entity.args[1])
new_x, new_y = _walk_engine(entity, frame)
if screen.get_cell(new_x, new_y) in walkable:
entity.pos_x, entity.pos_y = new_x, new_y
if (entity.pos_x, entity.pos_y) == entity.args[1][frame]: entity.args[0] = frame
def walk_to(entity, data, stat, screen, walkable):
frame = entity.args[0]
print(frame, len(entity.args[1]), entity.args)
if len(entity.args[1]) == frame:
entity.behavior = "stand by"
entity.args = []
return
new_x, new_y = _walk_engine(entity, frame)
if screen.get_cell(new_x, new_y) in walkable:
entity.pos_x, entity.pos_y = new_x, new_y
if (entity.pos_x, entity.pos_y) == entity.args[1][frame]: entity.args[0] += 1
def follow_by_player(entity, data, stat, screen, walkable):
frame = entity.args[0]
if len(entity.args[1]) == frame:
entity.behavior = "stand by"
entity.args = []
return
new_x, new_y = _walk_engine(entity, frame)
if abs(data[2] - new_x) < 5 and abs(data[3] - new_y) < 3 and screen.get_cell(new_x, new_y) in walkable:
entity.pos_x, entity.pos_y = new_x, new_y
if (new_x, new_y) == entity.args[1][frame]: entity.args[0] += 1
def _walk_engine(entity, frame):
delta_x, delta_y = list(map(lambda x,y: y - x, (entity.pos_x, entity.pos_y), entity.args[1][frame]))
new_x = entity.pos_x
new_y = entity.pos_y
if delta_x: new_x += abs(delta_x) // delta_x
if delta_y: new_y += abs(delta_y) // delta_y
return new_x, new_y
# Extra functions
def print_text(text, min_value=0, max_value=0, default_value=0):
paragraphs = [i for i in text_formater(text) if i]
nb = len(paragraphs)
@ -293,3 +491,14 @@ def print_text(text, min_value=0, max_value=0, default_value=0):
return result
else: input()
def center(string, total_length, symbol):
left = floor((total_length - len(string)) / 2)
right = ceil((total_length - len(string)) / 2)
return left * symbol + string + right * symbol
def enumerate(data):
return [(i, data[i]) for i in range(len(data))]

View File

@ -1,29 +1,57 @@
from asci import *
carte_monde = ((
r"""
exterieur = (r"""
_ ###
/o\__ #####
| <>\ ###
|____| /_\
*
|_ <>\ ###
|^|__| /_\
|==|==|==|==|==|==|==|""",),)
|==|==|==|==|==|==|==|""",
# Points de passage
(1, 3, 1, 3, 5))
interieur = (r"""
+----------+
| |
| |
| |
| |
+-|^|------+
""",
# Points de passage
(3, 5, 0, 1, 3))
def pnj(data, stat):
xp, carte_actuelle, x, y = data
coords = (x, y)
if carte_actuelle == 0:
if coords == (2, 5): return {
0: [0, "Mon bon monsieur, vous n'auriez pas quelques sous pour moi ? 1. He non mon brave... 2. Mais si, bien sur, tenez.", 2],
1: [2, "Radin !"],
# 0 réponse possibles, -1 Argent
2: [1, "Merci !", 0, (1, -1)],
carte_monde = (exterieur, interieur)
entites = (
["sdf", "*", 0, 2, 5, "stand by"],
)
def pnj(data, stat, entites, identifiant):
xp = data[0]["main"]
if identifiant == "sdf":
if xp in (2, 7): entites["sdf"].change_behavior("follow")
elif xp == 4: entites["sdf"].change_behavior("stand by")
elif xp == 6:
entites["sdf"].change_behavior("stand by")
entites["sdf"].teleport(1, 2, 2)
return {
0: [0, "Mon bon monsieur, vous n'auriez pas quelques sous pour moi ?\n1. He non mon brave...\n2. Mais si, bien sur, tenez.", 2],
1: [5, "Radin !"],
2: [1, "Merci !", 0, (1, -1)], # 0 réponse possibles, -1 Argent
3: [0, "Hmm ?\n1.Arretez de me suivre !\n2.Non rien.\n3.Attendez-moi a l'intérieur, j'en ai pour une minute.", 3],
4: [2, "Soit..."],
5: [-2, "Bien."],
6: [1, "Soit."],
7: [-4, "Je vous suis !"],
"base": [0, "Hmm ?"]
}
@ -31,6 +59,7 @@ def pnj(data, stat):
return [0, "Hmm ?"]
def affichage_stat(data, stat):
pv, argent = stat
print("Statistiques")
@ -44,5 +73,5 @@ touche = {6: affichage_stat}
def mon_jeu():
rpg_python = Asci(carte_monde, evenements, touche)
rpg_python.mainloop(4, stat=[100, 5])
rpg_python = Asci(carte_monde, entites, evenements, touche)
rpg_python.mainloop(10, stat=[100, 5], data=[{"main": 0}, 0, 10, 3])

View File

@ -8,7 +8,7 @@ cartes = (
|_ <>\ ###
|^|__| /_\
?
|==|==|==|==|==|==|==|""",
@ -16,7 +16,7 @@ cartes = (
(r"""
+--+--+--------+--+--+
| | | ? | | ?|
| | | | | |
| + + + + |
| |
| + + + + |
@ -26,39 +26,44 @@ cartes = (
(5, 7, 0, 1, 3))
)
entites = (
[1, "*", 0, 2, 5, "stand by"],
["habitant", "?", 1, 9, 1, "stand by"],
["voleur", "?", 1, 20, 1, "stand by"]
)
def pnj(data, stat):
xp, carte_actuelle, x, y = data
coords = (x, y)
def pnj(data, stat, entites, identifiant):
carte_actuelle = data[1]
if carte_actuelle == 0:
if coords == (2, 5): return {
if identifiant == 1: return {
0: [0, "Hey ! J'ai entendu du bruit dans la maison, mais je n'ose pas rentrer... 1. Rien entendu. 2. Je vais jeter un oeil.", 2],
1: [3, "Etes-vous sourd ?"],
2: [1, "J'etais sur que vous m'ecouteriez !"],
3: [2, "C'est la maison juste au nord."],
3: [2, "C'est la maison juste au nord. Soyez prudent !"],
4: [0, "Enfin, vous entendez bien du bruit la ? Et si c'etait un voleur ? 1. Bon ok j'y vais. 2. Mais foutez moi la paix !", 2],
6: [0, "..."],
5: [2, "Soyez prudent !"],
5: [0, "Alors ?"],
12: [1, "J'etais sur d'avoir entendu un truc !"],
10: [1, "J'etais sur d'avoir entendu un truc !"],
"base": [0, "Vous avez entendu quelque chose ?"]
}
elif carte_actuelle == 1:
if coords == (9, 1): return {
7: [0, "Je crois que le voleur est dans la piece d'a cote... 1. Je vais regarder. 2. Debrouillez-vous !", 2],
8: [2, "Merci !"],
9: [0, "Pleutre ! Hors de ma vue !"],
if identifiant == "habitant": return {
5: [0, "Je crois que le voleur est dans la piece d'a cote... 1. Je vais regarder. 2. Debrouillez-vous !", 2],
6: [2, "Merci !"],
7: [0, "Pleutre ! Hors de ma vue !"],
11: [1, "Ah, merci !"],
9: [1, "Ah, merci !"],
"base": [0, "J'ai peur de sortir de cette piece"]
}
elif coords == (20, 1): return {
10: [1, "Ciel, je suis fait !"],
elif identifiant == "voleur": return {
8: [1, "Ciel, je suis fait !"],
9: [0, "Je pars, je pars !"],
"base": [0, "File avant que je ne te detrousse !"]
}
@ -76,5 +81,5 @@ touche = {8: affichage_statistique}
def mon_jeu():
rpg_python = Asci(cartes, evenements, touche)
rpg_python.mainloop(13, [100])
rpg_python = Asci(cartes, entites, evenements, touche)
rpg_python.mainloop(11, [100], [{"main": 0}, 0, 10, 3])

View File

@ -5,13 +5,13 @@ from random import randint
cartes = (
(r"""
__
/ \___ ### *
/ \___ ###
|<> \ ##### _
|^|____| ### / \
/_\ |^| *
/_\ |^|
__ __
$ ## / \___/ \ ##
## / \___/ \ ##
#### |<> <>| ####
## |_________| ##
|| ||""",
@ -24,7 +24,7 @@ cartes = (
| + + + + |
| |
| + + + + |
+--/ *\--------/ \--+
+--/ \--------/ \--+
| |
+---|^|--------------+""",
(5, 7, 0, 1, 3)),
@ -39,48 +39,43 @@ cartes = (
(4, 4, 0, 19, 4))
)
entites = (
["medecin", "*", 0, 24, 4, "stand by"],
["ami", "*", 0, 16, 1, "stand by"],
["bandit", "$", 0, 4, 7, "walk", 0, ((4, 7), (3, 7), (3, 6), (4, 6))],
[0, "*", 1, 5, 5, "stand by"]
)
def pnj(data, stat):
def pnj(data, stat, entites, identifiant):
carte_actuelle = data[1]
coords = data[2], data[3]
xp = data[0]["main"]
if carte_actuelle == 0:
if coords == (24, 4):
if identifiant == "medecin":
if stat[0] < 100: return [0, "Oh, mais tu es blesse !", 0, (0, 50)]
else: return [0, "Reviens me voir quand tu seras blesse."]
elif coords == (16, 1): return {
elif identifiant == "ami": return {
"base": [0, "Alors ? T'en sorts-tu ?"],
0: [0, "J'ai une quete pour toi ! Un ami a moi a des problemes : un personnage louche traine autour de sa maison... Si tu pouvais l'en debarasser, il t'en serai reconnaissant. 1. Je m'en charge ! 2. Trouve quelqu'un d'autre.", 2],
1: [2, "J'etais sur que je pouvais compter sur toi ! Tiens, voila une dague et une petit bouclier.", 0, 0, 10, 10],
1: [2, "J'etais sur que je pouvais compter sur toi ! Tiens, voila une dague et une petit bouclier.", 0, (1, 10), (2, 10)],
2: [3, "Si un jour tu as besoin de moi, tu seras sympa de m'oublier."],
3: [0, "Alors ? Il est mort ce bandit ?"],
4: [1, "Merci, tu as rendu un grand service a mon ami !"]
}
elif coords == (4, 7):
# Si le bandit vient d'être tué
if xp == 3: return [1, "Vous avez reussi la quete !"]
# Si le bandit est encore vivant
elif xp < 3: return [0, "Qu'est-ce que tu regardes toi ? Casses-toi !"]
# Si le bandit est déjà mort
else: return [0, "Vous regardez le cadavre froid du bandit."]
return [0, "Hmm ?"]
def ennemi(data, stat):
def ennemi(data, stat, entites, identifiant):
carte_actuelle = data[1]
coords = data[2], data[3]
xp = data[0]["main"]
if carte_actuelle == 0:
if coords == (4, 7):
if identifiant == "bandit":
# Bandit vivant
if xp == 3:
if combat(stat, [75, randint(5, 10), randint(5, 10)]):
@ -133,7 +128,7 @@ touche = {7: affichage_stat}
def mon_jeu(stat=[100, 0, 0], data=[{"main": 0}, 0, 10, 3]):
rpg_python = Asci(cartes, evenements, touche)
rpg_python = Asci(cartes, entites, evenements, touche)
stat, data = rpg_python.mainloop(5, stat, data=data)
print("Pour reprendre :")
print("mon_jeu({}, {})".format(stat, data))

View File

@ -8,7 +8,7 @@ cartes = (
|_ <>\ ###
|^|__| /_\
?
|==|==|==|==|==|==|==|""",
@ -16,7 +16,7 @@ cartes = (
(r"""
+--+--+--------+--+--+
| | | ? | | ?|
| | | | | |
| + + + + |
| |
| + + + + |
@ -26,43 +26,42 @@ cartes = (
(5, 7, 0, 1, 3))
)
entites = (
["pnj", "?", 0, 2, 5, "stand by"],
["boulanger", "?", 1, 9, 1, "stand by"],
["kiosque", "?", 1, 20, 1, "stand by"]
)
def pnj(data, stat):
xp, carte_actuelle, x, y = data
coords = (x, y)
def pnj(data, stat, entites, identifiant):
if identifiant == "pnj":
# Si les deux quêtes annexes sont terminées, on incrémente la quête principale
if "pain" in data[0] and "journal" in data[0] and data[0]["pain"] == 3 and data[0]["journal"] == 3:
data[0]["main"] += 1
if carte_actuelle == 0:
if coords == (2, 5):
# Si les deux quêtes annexes sont terminées, on incrémente la quête principale
if "pain" in xp and "journal" in xp and xp["pain"] == 3 and xp["journal"] == 3:
data[0]["main"] += 1
# Si le joueur accepte la quête, on initialise les deux quêtes annexes
if data[0]["main"] == 1:
data[0]["pain"] = 1
data[0]["journal"] = 1
return [2, "Tu es un ange !"] # data[0]["main"] = 3
# Si le joueur accepte la quête, on initialise les deux quêtes annexes
if xp["main"] == 1:
data[0]["pain"] = 1
data[0]["journal"] = 1
return [2, "Tu es un ange !"] # data[0]["main"] = 3
elif "pain" in data[0] and data[0]["pain"] == 2: return "pain", [1, "Ah merci pour le pain."] # Si joueur a été chercher le pain
elif "journal" in data[0] and data[0]["journal"] == 2: return "journal", [1, "Aha enfin de la lecture !"] # Si le joueur a été chercher le journal
elif "pain" in xp and xp["pain"] == 2: return "pain", [1, "Ah merci pour le pain."] # Si joueur a été chercher le pain
elif "journal" in xp and xp["journal"] == 2: return "journal", [1, "Aha enfin de la lecture !"] # Si le joueur a été chercher le journal
else:
return {
0: [0, "J'aimerais que que tu ailles m'acheter un journal et du pain.\n1. J'y vais m'sieur !\n2. Humm... Non.", 2],
2: [-2, "Vilain garnement !"], # Si le joueur refuse la quête
3: [0, "Alors ? J'attend moi !"], # Si le joueur a accepté la quête, mais n'a été cherché ni le pain, ni le journal
4: [1, "Merci, pour ces commissions !"] # Si le joueur a terminé la quête
}
else:
return {
0: [0, "J'ai que tu ailles m'acheter un journal et du pain.\n1. J'y vais m'sieur !\n2. Humm... Non.", 2],
2: [-2, "Vilain garnement !"], # Si le joueur refuse la quête
3: [0, "Alors ? J'attend moi !"], # Si le joueur a accepté la quête, mais n'a été cherché ni le pain, ni le journal
4: [1, "Merci, pour ces commissions !"] # Si le joueur a terminé la quête
}
elif identifiant == "boulanger":
if "pain" in data[0] and data[0]["pain"] == 1: return "pain", [1, "Tient voila pour toi ! [+PAIN]"]
else: return [0, "Je suis boulanger mon jeune ami !"]
elif carte_actuelle == 1:
if coords == (9, 1):
if "pain" in xp and xp["pain"] == 1: return "pain", [1, "Tient voila pour toi ! [+PAIN]"]
else: return [0, "Je suis boulanger mon jeune ami !"]
elif coords == (20, 1):
if "journal" in xp and xp["journal"] == 1: return "journal", [1, "Voila ton journal"]
else: return [0, "Ce kiosque est dans la famille depuis plusieurs générations !"]
elif identifiant == "kiosque":
if "journal" in data[0] and data[0]["journal"] == 1: return "journal", [1, "Voila ton journal"]
else: return [0, "Ce kiosque est dans la famille depuis plusieurs générations !"]
return [0, "Hmm ?"]
@ -79,6 +78,5 @@ touche = {8: affichage_statistique}
def mon_jeu():
rpg_python = Asci(cartes, evenements, touche)
stat, data = rpg_python.mainloop(5, [100])
print(stat, data)
rpg_python = Asci(cartes, entites, evenements, touche)
stat, data = rpg_python.mainloop(5, [100], [{"main": 0}, 0, 10, 3])

69
samples/sample_5.py Normal file
View File

@ -0,0 +1,69 @@
from asci import *
exterieur = (r"""
_ ###
/o\__ #####
|_ <>\ ###
|^|__| /_\
|==|==|==|==|==|==|==|""",
# Points de passage
(1, 3, 1, 3, 5))
interieur = (r"""
+----------+
| |
| |
| |
| |
+-|^|------+""",
# Points de passage
(3, 5, 0, 1, 3))
carte_monde = (exterieur, interieur)
entites = (
["pnj", "*", 0, 2, 5, "stand by"],
)
def pnj(data, stat, entites, identifiant):
xp = data[0]["main"]
if identifiant == "pnj":
if xp == 1:
entites["pnj"].change_behavior("follow by player")
entites["pnj"].args = [0, ((3, 5), (16, 5), (16, 2))]
return {
"base": [0, "Moui ?"],
0: [0, "Tu me suis ?\n1.Oui\n2.Non", 2],
1: [2, "Parfait ! C'est parti !"],
2: [-2, "Rhoo alleezz..."],
3: [1, "Hehe"]
}
return [0, "Hmm ?"]
def affichage_stat(data, stat):
pv, argent = stat
print("Statistiques")
print("PV : {}".format(pv))
print("Argent : {}".format(argent))
input()
evenements = {"*": pnj}
touche = {6: affichage_stat}
def mon_jeu():
rpg_python = Asci(carte_monde, entites, evenements, touche)
rpg_python.mainloop(10, stat=[100, 5], data=[{"main": 0}, 0, 10, 3])

12
tiled/automap.sh Normal file
View File

@ -0,0 +1,12 @@
#!/bin/bash
mkdir map_python
for i in *.tmx
do
echo "$i -> ${i%.*}.py"
python converter "$i" doors=^ entities=?*
cp "${i%.*}.py" map_python/
rm "${i%.*}.py"
done

View File

@ -3,7 +3,7 @@ from sys import argv
import xmltodict
def convert_to_string(filename, doors, misc):
def convert_to_string(filename, doors, entities):
output_filename, extension = filename.split('.')
char_list = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ "
@ -18,32 +18,35 @@ def convert_to_string(filename, doors, misc):
data = [[int(char_id) for char_id in line.split(",") if char_id] for line in data]
doors_coords = []
misc_coords = []
entities_data = []
output = r""
for line_index, line in enumerate(data):
for char_index, char_id in enumerate(line):
output += char_list[char_id]
if char_list[char_id] not in entities:
output += char_list[char_id]
else:
output += " "
entities_data.append(f"[None, '{char_list[char_id]}', , {char_index}, {line_index}, 'stand_by'],")
if char_list[char_id] in doors:
doors_coords.append(f"\t({char_index}, {line_index}, , 0, 0),")
if char_list[char_id] in misc:
misc_coords.append(f"# {char_list[char_id]} : ({char_index}, {line_index})")
output += "\n"
doors_coords = "\n".join(doors_coords)
misc_coords = "\n".join(misc_coords)
entities_data = "(\n\t" + "\n\t".join(entities_data) + "\n)"
with open(f"{output_filename}.py", "w") as file:
file.write(f"{output_filename} = (r\"\"\"\n{output[:-1]}\"\"\",\n{doors_coords}\n)\n\n{misc_coords}")
file.write(f"{output_filename} = (r\"\"\"\n{output[:-1]}\"\"\",\n{doors_coords}\n)\n\n{output_filename}_entities = {entities_data}")
filename, doors, misc = argv[1], "", ""
for arg in argv[2:]:
if arg.startswith("door"):
doors = arg.split("=", 1)[1]
elif arg.startswith("misc"):
misc = arg.split("=", 1)[1]
elif arg.startswith("entities"):
entities = arg.split("=", 1)[1]
convert_to_string(filename, doors, misc)
convert_to_string(filename, doors, entities)