Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
23fc848855 | ||
|
|
5a0e79c403 | ||
|
|
b50ae2c082 | ||
|
|
4a8f3649c8 | ||
|
|
968bb53883 | ||
|
|
45cb5c0467 | ||
|
|
d8dde66d78 | ||
|
|
f4c9c77ad8 | ||
|
|
dc13f917b0 | ||
|
|
bb67b3dc0a | ||
|
|
c346df9f6a | ||
|
|
4592aa6725 | ||
|
|
bb0362ed10 | ||
|
|
1345196ae9 | ||
|
|
965bd61140 | ||
|
|
f66c5d4321 | ||
|
|
3bc93fa3a7 | ||
|
|
49f3c84e60 | ||
|
|
53534ee707 | ||
|
|
1a04f9914c | ||
|
|
5662e87c83 | ||
|
|
3860250e31 |
@@ -1,6 +1,7 @@
|
|||||||
# Nassi-Shneiderman-Diagramm-Generator
|
# Nassi-Shneiderman-Diagramm-Generator
|
||||||
This python code generates a Nassi Shneiderman Diagramm from Java Source Code
|
This python code generates a Nassi Shneiderman Diagramm from Java Source Code.
|
||||||
|
|
||||||
|
Newest Version --> 0.3
|
||||||
|
|
||||||
How it works:
|
How it works:
|
||||||
In the final version, you will just have to execute the nassi.exe and choose your Code, it will display a preview of the Nassi-Shneiderman-Diagramm and give you the path of the created picture.
|
In the final version, you will just have to execute the nassi.exe and choose your Code, it will display a preview of the Nassi-Shneiderman-Diagramm and give you the path of the created picture.
|
||||||
|
|||||||
@@ -1,216 +1,228 @@
|
|||||||
"""Iinstruction.py: #TODO"""
|
"""Interafce for all instruction types"""
|
||||||
|
|
||||||
__author__ = "Weckyy702"
|
__author__ ="Weckyy702"
|
||||||
|
|
||||||
|
|
||||||
from typing import Iterable, List
|
|
||||||
from abc import ABCMeta, abstractmethod
|
from abc import ABCMeta, abstractmethod
|
||||||
from draw import code_to_image as cti
|
from typing import Tuple, List, Optional
|
||||||
|
|
||||||
class Iinstruction(metaclass=ABCMeta):
|
from . import code_to_image as cti
|
||||||
"""Base class for all instructions"""
|
|
||||||
|
|
||||||
|
class instruction(metaclass=ABCMeta):
|
||||||
def __init__(self, instruction_text: str) -> None:
|
def __init__(self, instruction_text: str) -> None:
|
||||||
self.instruction_text = instruction_text
|
self.instruction_text = instruction_text
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def to_image(self, x:int, y:int, x_sz: int) -> Iterable[float]:
|
def convert_to_image(self, x: int, y: int, width: int) -> int:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def getblkheight(self) -> float:
|
def get_block_width(self):
|
||||||
pass
|
return self.get_text_width()
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def getblkwidth(self) -> float:
|
def get_block_height(self):
|
||||||
pass
|
return self.get_text_height()
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def __str__(self) -> str:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def _getblkheight(self) -> float:
|
|
||||||
return cti.get_text_size(self.instruction_text)[1] + cti.PADDING_Y #padding
|
|
||||||
|
|
||||||
def _getblkwidth(self) -> float:
|
|
||||||
return cti.get_text_size(self.instruction_text)[0] + cti.PADDING_X #padding
|
|
||||||
|
|
||||||
|
|
||||||
class generic_instruction(Iinstruction):
|
|
||||||
"""Any instruction that is not a control structure"""
|
|
||||||
|
|
||||||
|
def get_text_width(self):
|
||||||
|
return cti.get_text_size(self.instruction_text)[0]
|
||||||
|
|
||||||
|
def get_text_height(self):
|
||||||
|
return cti.get_text_size(self.instruction_text)[1]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class generic_instruction(instruction):
|
||||||
def __init__(self, instruction_text: str) -> None:
|
def __init__(self, instruction_text: str) -> None:
|
||||||
Iinstruction.__init__(self, instruction_text)
|
super().__init__(instruction_text)
|
||||||
|
|
||||||
def to_image(self, x:int, y:int, x_sz: int) -> Iterable[float]:
|
def convert_to_image(self, x: int, y: int, width: int) -> int:
|
||||||
return cti.draw_generic_instruction(self.instruction_text, x, y, x_sz, self.getblkheight())
|
height = self.get_block_height()
|
||||||
|
return cti.draw_generic_instruction(self.instruction_text, x, y, width, height)
|
||||||
|
|
||||||
def getblkheight(self) -> float:
|
def get_block_width(self):
|
||||||
return self._getblkheight()
|
return super().get_block_width()
|
||||||
|
|
||||||
def getblkwidth(self) -> float:
|
def get_block_height(self):
|
||||||
return self._getblkwidth()
|
return super().get_block_height()
|
||||||
|
|
||||||
def __str__(self) -> str:
|
def __str__(self) -> str:
|
||||||
return self.instruction_text
|
return self.instruction_text
|
||||||
|
|
||||||
class if_instruction(Iinstruction):
|
|
||||||
"""Conditional structure
|
|
||||||
NOT.
|
|
||||||
A.
|
|
||||||
LOOP
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, instruction_text: str, true_case: List[Iinstruction], false_case: List[Iinstruction]=None) -> None:
|
|
||||||
Iinstruction.__init__(self, instruction_text)
|
class if_instruction(instruction):
|
||||||
|
def __init__(self, instruction_text: str, true_case: List[instruction], false_case: Optional[List[instruction]]) -> None:
|
||||||
|
super().__init__(instruction_text)
|
||||||
self.true_case = true_case
|
self.true_case = true_case
|
||||||
self.false_case = false_case
|
self.false_case = false_case
|
||||||
|
|
||||||
def get_trueheight(self) -> float:
|
def convert_to_image(self, x: int, y: int, width: int) -> int:
|
||||||
sz = 0.0
|
true_width = self.get_true_width()
|
||||||
for inst in self.true_case:
|
block_height = self.get_block_height()
|
||||||
sz += inst.getblkheight()
|
|
||||||
return sz
|
|
||||||
|
|
||||||
def get_falseheight(self) -> float:
|
true_x, true_y, false_x, false_y = cti.draw_if_statement(self.instruction_text, x, y, true_width, width, block_height)
|
||||||
sz = 0.0
|
|
||||||
if self.false_case:
|
|
||||||
for inst in self.false_case:
|
|
||||||
sz += inst.getblkwidth()
|
|
||||||
return sz
|
|
||||||
|
|
||||||
def get_truewidth(self) -> float:
|
self.draw_children(true_x, true_y, true_width, false_x, false_y, width-true_width)
|
||||||
w = 200.0
|
|
||||||
|
|
||||||
for inst in self.true_case:
|
return y + self.get_block_height()
|
||||||
w = max(w, inst.getblkwidth())
|
|
||||||
|
|
||||||
return w
|
def draw_children(self, true_x:int, true_y:int, true_width:int, false_x:int, false_y:int, false_width:int):
|
||||||
|
|
||||||
def get_falsewidth(self) -> float:
|
|
||||||
w = 200.0
|
|
||||||
|
|
||||||
if self.false_case:
|
|
||||||
for inst in self.false_case:
|
|
||||||
w = max(w, inst.getblkwidth())
|
|
||||||
|
|
||||||
return w
|
|
||||||
|
|
||||||
def getblkheight(self) -> float:
|
|
||||||
return self._getblkheight() + max(self.get_trueheight(), self.get_falseheight())
|
|
||||||
|
|
||||||
def getblkwidth(self) -> float:
|
|
||||||
return max(self._getblkwidth(), self.get_truewidth() + self.get_falsewidth())
|
|
||||||
|
|
||||||
|
|
||||||
def to_image(self, x:int, y:int, x_sz: int) -> Iterable[float]:
|
|
||||||
true_w = self.get_truewidth()
|
|
||||||
false_w = self.get_falsewidth()
|
|
||||||
true_x, true_y, false_x, false_y = cti.draw_if_statement(
|
|
||||||
self.instruction_text, x, y, true_w, false_w, self.getblkheight()
|
|
||||||
)
|
|
||||||
self.draw_true_case(true_x, true_y, true_w)
|
|
||||||
self.draw_false_case(false_x, false_y, false_w)
|
|
||||||
blk_size = self.getblkheight()
|
|
||||||
return x, y + blk_size
|
|
||||||
|
|
||||||
def draw_true_case(self, x: float, y:float, x_sz:float):
|
|
||||||
for instruction in self.true_case:
|
for instruction in self.true_case:
|
||||||
x, y = instruction.to_image(x, y, x_sz)
|
true_y = instruction.convert_to_image(true_x, true_y, true_width)
|
||||||
|
|
||||||
def draw_false_case(self, x: float, y:float, x_sz:float):
|
|
||||||
if self.false_case:
|
if self.false_case:
|
||||||
for instruction in self.false_case:
|
for instruction in self.false_case:
|
||||||
x, y = instruction.to_image(x, y, x_sz)
|
false_y = instruction.convert_to_image(false_x, false_y, false_width)
|
||||||
|
|
||||||
def __str__(self) -> str:
|
def get_block_width(self) -> int:
|
||||||
res = f"if({self.instruction_text}) {'{'}\n"
|
text_width = self.get_text_width()
|
||||||
for inst in self.true_case:
|
|
||||||
res += '\t'+str(inst)+";\n"
|
true_width = self.get_true_width()
|
||||||
res += "}"
|
false_width = self.get_false_width()
|
||||||
|
|
||||||
|
return max(text_width, true_width + false_width)
|
||||||
|
|
||||||
|
def get_block_height(self):
|
||||||
|
text_height = self.get_text_height()
|
||||||
|
true_height = self.get_true_height()
|
||||||
|
false_height = self.get_false_height()
|
||||||
|
|
||||||
|
return text_height + max(true_height, false_height)
|
||||||
|
|
||||||
|
def get_text_width(self):
|
||||||
|
return int(super().get_text_width() * 1.5)
|
||||||
|
|
||||||
|
def get_true_width(self) -> int:
|
||||||
|
width = 200
|
||||||
|
for instruction in self.true_case:
|
||||||
|
width = max(width, instruction.get_block_width())
|
||||||
|
return width
|
||||||
|
|
||||||
|
def get_false_width(self) -> int:
|
||||||
|
width = 200
|
||||||
if self.false_case:
|
if self.false_case:
|
||||||
res += " else {"
|
for instruction in self.false_case:
|
||||||
for inst in self.true_case:
|
width = max(width, instruction.get_block_width())
|
||||||
res += '\t'+str(inst)+";\n"
|
return width
|
||||||
res += "}"
|
|
||||||
return res
|
|
||||||
|
|
||||||
# class switch_instruction(Iinstruction):
|
def get_true_height(self) -> int:
|
||||||
# """Switch structure"""
|
height = 0
|
||||||
|
|
||||||
# def __init__(self, instruction_text: str, cases: List[List[Iinstruction]]) -> None:
|
for instruction in self.true_case:
|
||||||
# Iinstruction.__init__(self, instruction_text)
|
height += instruction.get_block_height()
|
||||||
# self.child_cases = cases
|
|
||||||
|
|
||||||
# def to_image(self, x:int, y:int, x_sz: int, y_sz: int) -> Iterable[float]:
|
return height
|
||||||
# """TODO: implement"""
|
|
||||||
# return []
|
|
||||||
|
|
||||||
# def draw_children(self, x:float, y:float, x_sz:float, y_sz:float) -> float:
|
def get_false_height(self) -> int:
|
||||||
# """TODO: implement"""
|
height = 0
|
||||||
# return 0.0
|
|
||||||
|
|
||||||
|
if self.false_case:
|
||||||
|
for instruction in self.false_case:
|
||||||
|
height += instruction.get_block_height()
|
||||||
|
|
||||||
|
return height
|
||||||
class while_instruction_front(Iinstruction):
|
|
||||||
|
|
||||||
def __init__(self, condition: str, instructions: List[Iinstruction]) -> None:
|
|
||||||
Iinstruction.__init__(self, condition)
|
|
||||||
self.child_instructions = instructions
|
|
||||||
|
|
||||||
def get_children_height(self) -> float:
|
|
||||||
children_sz = 0
|
|
||||||
for inst in self.child_instructions:
|
|
||||||
children_sz += inst.getblkheight()
|
|
||||||
return children_sz
|
|
||||||
|
|
||||||
def get_children_width(self) -> float:
|
|
||||||
w = 0.0
|
|
||||||
for inst in self.child_instructions:
|
|
||||||
w += inst.getblkheight()
|
|
||||||
return w
|
|
||||||
|
|
||||||
def getblkheight(self) -> float:
|
|
||||||
return self._getblkheight() + self.get_children_height()
|
|
||||||
|
|
||||||
def getblkwidth(self) -> float:
|
|
||||||
return max(self._getblkwidth(), self.get_children_width())
|
|
||||||
|
|
||||||
def to_image(self, x:int, y:int, x_sz: int) -> Iterable[float]:
|
|
||||||
children_x, children_y, children_sz_x = cti.draw_while_loop_front(self.instruction_text, x, y, x_sz, self.getblkheight())
|
|
||||||
self.draw_children(children_x, children_y, children_sz_x)
|
|
||||||
|
|
||||||
return x, y + self.getblkheight()
|
|
||||||
|
|
||||||
|
|
||||||
def draw_children(self, x:float, y:float, x_sz:float):
|
|
||||||
for inst in self.child_instructions:
|
|
||||||
x, y = inst.to_image(x, y, x_sz)
|
|
||||||
return self.get_children_height()
|
|
||||||
|
|
||||||
def __str__(self) -> str:
|
def __str__(self) -> str:
|
||||||
res = "while(" + self.instruction_text + "){\n"
|
res = "if\n"
|
||||||
for inst in self.child_instructions:
|
for instruction in self.true_case:
|
||||||
res += '\t'+str(inst)+";\n"
|
res += '\t' + str(instruction) + '\n'
|
||||||
res += '}'
|
|
||||||
|
if self.false_case:
|
||||||
|
res += "else\n"
|
||||||
|
for instruction in self.false_case:
|
||||||
|
res += '\t' + str(instruction) + '\n'
|
||||||
|
|
||||||
return res
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class while_instruction_front(instruction):
|
||||||
|
def __init__(self, condition_text: str, child_instructions: List[instruction]) -> None:
|
||||||
|
super().__init__(condition_text)
|
||||||
|
self.children = child_instructions
|
||||||
|
|
||||||
|
def convert_to_image(self, x: int, y: int, width: int) -> int:
|
||||||
|
block_height = self.get_block_height()
|
||||||
|
|
||||||
|
children_x, children_y, children_width = cti.draw_while_loop_front(self.instruction_text, x, y, width, block_height)
|
||||||
|
|
||||||
|
self.draw_children(children_x, children_y, children_width)
|
||||||
|
|
||||||
|
return y + block_height
|
||||||
|
|
||||||
|
def draw_children(self, children_x:int, children_y:int, children_width:int):
|
||||||
|
for instruction in self.children:
|
||||||
|
children_y = instruction.convert_to_image(children_x, children_y, children_width)
|
||||||
|
|
||||||
|
def get_block_width(self):
|
||||||
|
width = self.get_text_width()
|
||||||
|
|
||||||
|
for instruction in self.children:
|
||||||
|
width = max(width, instruction.get_block_width() / (1 - cti.BLOCK_OFFSET_RATIO)) #instructions inside a bock take up more space, so compensate for that
|
||||||
|
|
||||||
|
return int(width)
|
||||||
|
|
||||||
|
def get_block_height(self):
|
||||||
|
height = self.get_text_height()
|
||||||
|
|
||||||
|
for instruction in self.children:
|
||||||
|
height += instruction.get_block_height()
|
||||||
|
|
||||||
|
return height
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
res = "while\n"
|
||||||
|
for instruction in self.children:
|
||||||
|
res += '\t' + str(instruction) + '\n'
|
||||||
|
return res
|
||||||
|
|
||||||
class while_instruction_back(while_instruction_front):
|
class while_instruction_back(while_instruction_front):
|
||||||
def __init__(self, condition: str, instructions: List[Iinstruction]) -> None:
|
def __init__(self, condition_text: str, child_instructions: List[instruction]) -> None:
|
||||||
while_instruction_front.__init__(self, condition, instructions)
|
super().__init__(condition_text, child_instructions)
|
||||||
|
|
||||||
def to_image(self, x:int, y:int, x_sz: int):
|
def convert_to_image(self, x: int, y: int, width: int) -> int:
|
||||||
children_x, children_y, children_sz_x = cti.draw_while_loop_back(self.instruction_text, x, y, x_sz, self.getblkheight())
|
block_height = self.get_block_height()
|
||||||
self.draw_children(children_x, children_y, children_sz_x)
|
children_x, children_y, children_width = cti.draw_while_loop_back(self.instruction_text, x, y, width, block_height)
|
||||||
return x, y + self.getblksize()
|
|
||||||
|
self.draw_children(children_x, children_y, children_width)
|
||||||
|
|
||||||
|
return y + block_height
|
||||||
|
|
||||||
def __str__(self) -> str:
|
def __str__(self) -> str:
|
||||||
res = "do{\n"
|
res = "do\n"
|
||||||
for inst in self.child_instructions:
|
for instruction in self.children:
|
||||||
res += '\t' +str(inst) + ";\n"
|
res += '\t' + str(instruction) + '\n'
|
||||||
res += f"{'}'}while({self.instruction_text});"
|
res += "while"
|
||||||
return res
|
return res
|
||||||
|
|
||||||
class for_instruction(while_instruction_front):
|
class for_instruction(while_instruction_front):
|
||||||
pass
|
def __init__(self, variable_text: str, condition_text: str, child_instruction: List[instruction]) -> None:
|
||||||
|
super().__init__(condition_text, child_instruction)
|
||||||
|
self.variable_instruction = generic_instruction(variable_text)
|
||||||
|
|
||||||
|
def convert_to_image(self, x: int, y: int, width: int) -> int:
|
||||||
|
block_height = super().get_block_height()
|
||||||
|
|
||||||
|
y = self.variable_instruction.convert_to_image(x, y, width)
|
||||||
|
|
||||||
|
children_x, children_y, children_width = cti.draw_while_loop_front(self.instruction_text, x, y, width, block_height)
|
||||||
|
self.draw_children(children_x, children_y, children_width)
|
||||||
|
|
||||||
|
return y + block_height
|
||||||
|
|
||||||
|
def get_block_width(self):
|
||||||
|
return max(super().get_block_width(), self.variable_instruction.get_block_width())
|
||||||
|
|
||||||
|
def get_block_height(self):
|
||||||
|
return super().get_block_height() + self.variable_instruction.get_block_height()
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
res = str(self.variable_instruction) + '\n'
|
||||||
|
res += "for\n"
|
||||||
|
|
||||||
|
for instruction in self.children:
|
||||||
|
res += "\t" + str(instruction) + '\n'
|
||||||
|
|
||||||
|
return res
|
||||||
@@ -2,13 +2,16 @@
|
|||||||
|
|
||||||
__author__ = "plexx, Weckyy702"
|
__author__ = "plexx, Weckyy702"
|
||||||
|
|
||||||
from typing import Iterable
|
from typing import Tuple
|
||||||
from PIL import Image, ImageDraw, ImageFont
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
import os
|
import os
|
||||||
|
import random
|
||||||
|
|
||||||
PADDING_X = 100
|
PADDING_X = 50
|
||||||
PADDING_Y = 5
|
PADDING_Y = 5
|
||||||
|
|
||||||
|
BLOCK_OFFSET_RATIO = .1
|
||||||
|
|
||||||
datei_endung = ".png"
|
datei_endung = ".png"
|
||||||
|
|
||||||
img = None
|
img = None
|
||||||
@@ -16,14 +19,17 @@ output_img = None
|
|||||||
|
|
||||||
_bkp_font = ImageFont.truetype("res/fonts/NotoSans-Regular.ttf", 12) # ImageFont.load_default()
|
_bkp_font = ImageFont.truetype("res/fonts/NotoSans-Regular.ttf", 12) # ImageFont.load_default()
|
||||||
|
|
||||||
#in case set_font does funky stuff, backup the original font
|
ERROR_TEXT = "Output image was not initialized! Make sure to call NSD_init first"
|
||||||
|
|
||||||
|
#in case set_font does funky stuff, backup the original font
|
||||||
font = _bkp_font
|
font = _bkp_font
|
||||||
|
|
||||||
|
|
||||||
def NSD_init(x: float, y: float):
|
def NSD_init(x: float, y: float):
|
||||||
#get input_img
|
#get input_img
|
||||||
global img, output_img
|
global img, output_img
|
||||||
#img = Image.open(input_dir + file_name + datei_endung)
|
|
||||||
|
|
||||||
img = Image.new("RGB", (x, y), "white")
|
img = Image.new("RGB", (x, y), "white")
|
||||||
output_img = ImageDraw.Draw(img)
|
output_img = ImageDraw.Draw(img)
|
||||||
|
|
||||||
@@ -38,99 +44,103 @@ def set_font(font_filepath: str):
|
|||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
def get_text_size(text: str):
|
def get_text_size(text: str) -> Tuple[int, int]:
|
||||||
if not font:
|
if not font:
|
||||||
raise Exception("Output image was not initialized! Make sure to call NSD_init first")
|
raise Exception(ERROR_TEXT)
|
||||||
return font.getsize(text)
|
size = font.getsize(text)
|
||||||
|
|
||||||
def draw_debug_tile(x, y, x_sz, y_sz):
|
return (size[0]+PADDING_X, size[1]+PADDING_Y)
|
||||||
from random import randint
|
|
||||||
|
|
||||||
output_img.rectangle((x, y) + (x + x_sz, y + y_sz), fill=(randint(0, 255)))
|
|
||||||
return x, y + y_sz
|
|
||||||
|
|
||||||
def draw_generic_instruction(instruction: str, x, y, xsize, ysize) -> Iterable[float]:
|
|
||||||
|
def draw_debug_tile(x:int, y:int, width:int, height:int) -> int:
|
||||||
|
fill_color = (random.randint(0, 255),random.randint(0, 255), random.randint(0, 255))
|
||||||
|
output_img.rectangle((x,y) + (x+width, y+height), outline=(0), fill=fill_color)
|
||||||
|
|
||||||
|
return y + height
|
||||||
|
|
||||||
|
def draw_generic_instruction(instruction: str, x: int, y: int, width:int, height:int) -> int:
|
||||||
if not output_img:
|
if not output_img:
|
||||||
raise Exception("Output image was not initialized! Make sure to call NSD_init first")
|
raise Exception(ERROR_TEXT)
|
||||||
|
|
||||||
#draw shit
|
#draw shit
|
||||||
output_img.rectangle((x,y) + (x + xsize, y + ysize), outline=(0), width=1)
|
output_img.rectangle((x,y) + (x + width, y + height), outline=(0), width=1)
|
||||||
|
|
||||||
#text shit
|
#text shit
|
||||||
output_img.multiline_text((x + xsize * .5, y + ysize * .5), instruction, font=font, anchor="mm", align="right", fill=(0))
|
output_img.multiline_text((x + width * .5, y + height * .5), instruction, font=font, anchor="mm", align="right", fill=(0))
|
||||||
|
|
||||||
return x, y + ysize
|
return y + height
|
||||||
|
|
||||||
def draw_if_statement(condition: str, x: int, y: int, true_w: int, false_w: int, ysize: int):
|
|
||||||
|
|
||||||
|
def draw_if_statement(condition: str, x: int, y: int, true_width: int, block_width:int, block_height: int) -> Tuple[int, int, int, int]:
|
||||||
"""Draw an if statement into the NSD"""
|
"""Draw an if statement into the NSD"""
|
||||||
if not output_img:
|
if not output_img:
|
||||||
raise Exception("Output image was not initialized! Make sure to call NSD_init first")
|
raise Exception(ERROR_TEXT)
|
||||||
|
|
||||||
text_sz = font.getsize(condition)
|
text_height = get_text_size(condition)[1]
|
||||||
text_h = text_sz[1] + PADDING_Y
|
|
||||||
text_w = text_sz[0] + PADDING_X
|
|
||||||
|
|
||||||
box_w = max(text_w, true_w + false_w)
|
#condition
|
||||||
|
output_img.rectangle((x, y) + (x + block_width, y + text_height), outline=(0), width=1) #Box around condition text
|
||||||
|
output_img.multiline_text((x + true_width, y + text_height / 2), condition, fill=(0), font=font, anchor="mm", spacing=4, align='right')
|
||||||
|
|
||||||
output_img.line((x,y) + (x + box_w/2, y + text_h), fill=(0))
|
#fancy lines for the "true" and "false" labels
|
||||||
output_img.line((x + box_w, y) + (x + box_w/2, y + text_h), fill=(0))
|
output_img.line((x,y) + (x + true_width, y + text_height), fill=(0))
|
||||||
output_img.rectangle((x, y + text_h) + (x + box_w, y + ysize), outline=(0), width=1)
|
output_img.line((x + block_width, y) + (x + true_width, y + text_height), fill=(0))
|
||||||
output_img.rectangle((x, y) + (x + box_w, y + text_h), outline=(0), width=1)
|
# "true" and "false" labels
|
||||||
output_img.line((x + true_w, y + text_h) + (x + true_w, y + ysize), fill=(0))
|
output_img.text((x + 5, y + text_height), "true", font = font, fill = (0), anchor="ld")
|
||||||
|
output_img.text((x + block_width - 5, y + text_height), "false", font = font, fill = (0), anchor="rd")
|
||||||
|
|
||||||
# condition text
|
output_img.line((x + true_width, y + text_height) + (x + true_width, y + block_height), fill=(0))
|
||||||
output_img.multiline_text((x + box_w / 2, y + text_h / 2), condition, fill=(0), font=font, anchor="mm", spacing=4, align='right')
|
|
||||||
|
|
||||||
# true / false
|
#x and y of "true" and "false" label
|
||||||
output_img.text((x + 5, y + text_h), "true", font = font, fill = (0), anchor="ld")
|
return x, y + text_height, x + true_width, y + text_height
|
||||||
output_img.text((x + box_w - 5, y + text_h), "false", font = font, fill = (0), anchor="rd")
|
|
||||||
|
|
||||||
#x, and y of "true" and "false" label
|
def draw_while_loop_front(condition: str, x: int, y: int, block_width: int, block_height: int) -> Tuple[int, int, int]:
|
||||||
return x, y + text_h, x + true_w, y + text_h
|
|
||||||
|
|
||||||
def draw_while_loop_front(condition: str, x: int, y: int, xsize: int, ysize: int):
|
|
||||||
|
|
||||||
if not output_img:
|
if not output_img:
|
||||||
raise Exception("Output image was not initialized! Make sure to call NSD_init first")
|
raise Exception(ERROR_TEXT)
|
||||||
|
|
||||||
text_y_sz = font.getsize(condition)[1]
|
text_height = get_text_size(condition)[1]
|
||||||
|
|
||||||
|
block_offset = int(block_width * BLOCK_OFFSET_RATIO)
|
||||||
|
|
||||||
#the box
|
#the box
|
||||||
output_img.line((x,y) + (x + xsize, y), fill=(0))
|
output_img.line((x,y) + (x + block_width, y), fill=(0))
|
||||||
output_img.line((x,y) + (x, y + ysize), fill=(0))
|
output_img.line((x,y) + (x, y + block_height), fill=(0))
|
||||||
output_img.line((x + xsize * .1, y + text_y_sz) + (x + xsize, y + text_y_sz), fill=(0))
|
output_img.line((x + block_offset, y + text_height) + (x + block_width, y + text_height), fill=(0))
|
||||||
output_img.line((x + xsize, y) + (x + xsize, y + text_y_sz), fill=(0))
|
output_img.line((x + block_width, y) + (x + block_width, y+text_height), fill=(0))
|
||||||
output_img.line((x, y + ysize) + (x + xsize * .1, y + ysize ), fill=(0))
|
|
||||||
output_img.line((x + xsize * .1, y + ysize) + (x + xsize * .1, y + text_y_sz), fill=(0))
|
|
||||||
|
|
||||||
#the text
|
#the text
|
||||||
output_img.text((x + xsize * .1, y + text_y_sz * .5), condition, font = font, fill = (0), anchor="lm")
|
output_img.text((x + block_offset, y + text_height * .5), condition, font = font, fill = (0), anchor="lm")
|
||||||
|
|
||||||
#the x, y offset then the x,y draw size (the canvas)
|
#the x, y offset then the children width
|
||||||
return x + xsize * .1, y + text_y_sz, xsize * .9
|
return x + block_offset, y + text_height, block_width - block_offset
|
||||||
|
|
||||||
def draw_while_loop_back(condition: str, x: int, y: int, xsize: int, ysize: int):
|
def draw_while_loop_back(condition: str, x: int, y: int, block_width: int, block_height: int):
|
||||||
|
|
||||||
if not output_img:
|
if not output_img:
|
||||||
raise Exception("Output image was not initialized! Make sure to call NSD_init first")
|
raise Exception(ERROR_TEXT)
|
||||||
|
|
||||||
text_y_sz = get_text_size(condition)[1]
|
text_height = get_text_size(condition)[1]
|
||||||
|
|
||||||
|
block_offset = int(block_width * BLOCK_OFFSET_RATIO)
|
||||||
|
|
||||||
#the box
|
#the box
|
||||||
output_img.line((x,y) + (x + xsize * .1, y), fill=0)
|
output_img.line((x,y) + (x + block_offset, y), fill=0)
|
||||||
output_img.line((x + xsize * .1, y) + (x + xsize * .1, y + ysize - text_y_sz), fill=0)
|
output_img.line((x + block_offset, y) + (x + block_offset, y + block_height - text_height), fill=0)
|
||||||
output_img.line((x + xsize * .1, y + ysize - text_y_sz) + (x + xsize, y + ysize - text_y_sz), fill=0)
|
output_img.line((x + block_offset, y + block_height - text_height) + (x + block_width, y + block_height - text_height), fill=0)
|
||||||
output_img.line((x + xsize, y + ysize - text_y_sz) + (x + xsize, y + ysize), fill=0)
|
output_img.line((x + block_width, y + block_height - text_height) + (x + block_width, y + block_height), fill=0)
|
||||||
output_img.line((x,y + ysize) + (x + xsize, y + ysize), fill=0)
|
output_img.line((x,y + block_height) + (x + block_width, y + block_height), fill=0)
|
||||||
output_img.line((x,y) + (x, y + ysize), fill=0)
|
output_img.line((x,y) + (x, y + block_height), fill=0)
|
||||||
|
|
||||||
#the text
|
#the text
|
||||||
output_img.text((x + xsize * .1, y + ysize - text_y_sz * .5), condition, font = font, fill = (0), anchor="lm")
|
output_img.multiline_text((x + block_offset, y + block_height - text_height * .5), condition, font = font, fill = (0), anchor="lm")
|
||||||
|
|
||||||
#the x, y offset then the x,y draw size (the canvas)
|
#x, y and width of children
|
||||||
return x + xsize * .1, y, xsize * .9
|
return x + block_offset, y, block_width - block_offset
|
||||||
|
|
||||||
def NSD_save(filepath: str):
|
def NSD_save(filepath: str):
|
||||||
"""Save the created file"""
|
"""Save the created file"""
|
||||||
filepath = filepath.removesuffix(".png")
|
filepath = filepath.removesuffix(datei_endung)
|
||||||
img.save(filepath + datei_endung ,"PNG")
|
img.save(filepath + datei_endung ,"PNG")
|
||||||
@@ -104,7 +104,7 @@ class Gui:
|
|||||||
if output_name is None:
|
if output_name is None:
|
||||||
sg.popup_auto_close(
|
sg.popup_auto_close(
|
||||||
'You didn\'t set a name for the image, it will be named randomly.')
|
'You didn\'t set a name for the image, it will be named randomly.')
|
||||||
output_name = secrets.token_hex(16)
|
output_name = "Nassi ist geil: " + secrets.token_hex(2)
|
||||||
|
|
||||||
path, file_is_empty = nassi_file(input_path=file_path, output_path=output_path, outputname=output_name, gui=self,
|
path, file_is_empty = nassi_file(input_path=file_path, output_path=output_path, outputname=output_name, gui=self,
|
||||||
font_filepath=font_filepath, behaviour=exists_choice, types=types, remove_tags=modifier, comments=comments)
|
font_filepath=font_filepath, behaviour=exists_choice, types=types, remove_tags=modifier, comments=comments)
|
||||||
|
|||||||
403
interpreter/Lexer.py
Normal file
403
interpreter/Lexer.py
Normal file
@@ -0,0 +1,403 @@
|
|||||||
|
"""Lexer.py: Definition for Lexer class"""
|
||||||
|
from interpreter.Tokenizer import Tokenizer
|
||||||
|
from os import linesep
|
||||||
|
from draw.Iinstruction import *
|
||||||
|
from typing import List, Optional, Union, Tuple
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from interpreter.function_scope import Function_scope
|
||||||
|
from interpreter._token import Token, Token_type
|
||||||
|
from errors.custom import JavaSyntaxError
|
||||||
|
|
||||||
|
def print_arr(arr):
|
||||||
|
print("[")
|
||||||
|
for elem in arr:
|
||||||
|
if isinstance(elem, List):
|
||||||
|
print_arr(elem)
|
||||||
|
else:
|
||||||
|
print(elem)
|
||||||
|
print("]")
|
||||||
|
|
||||||
|
class Lexer:
|
||||||
|
def __init__(self, tokens: List[Token]) -> None:
|
||||||
|
self._tokens = tokens
|
||||||
|
self._token_index = 0
|
||||||
|
|
||||||
|
self._scopes: List[Function_scope] = []
|
||||||
|
|
||||||
|
#in case the tokenizer finds valid tokens in the global scope, they will be saved here
|
||||||
|
self._global_instructions = []
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _peek(self, offset:int=0) -> Optional[Token]:
|
||||||
|
if (self._token_index+offset) >= len(self._tokens):
|
||||||
|
return None
|
||||||
|
return self._tokens[self._token_index+offset]
|
||||||
|
|
||||||
|
def _consume(self):
|
||||||
|
token = self._peek()
|
||||||
|
self._token_index+=1
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def get_instructions(self):
|
||||||
|
|
||||||
|
scopes = []
|
||||||
|
|
||||||
|
while self._peek():
|
||||||
|
line_tokens = self.get_line_tokens()
|
||||||
|
|
||||||
|
if self._is_function_def(line_tokens):
|
||||||
|
|
||||||
|
func_name, func_return_type, func_args = self._construct_function_header_from_tokens(line_tokens)
|
||||||
|
current_scope = Function_scope(func_name, func_return_type, func_args)
|
||||||
|
|
||||||
|
instructions = self._get_instructions_in_scope()
|
||||||
|
current_scope._add_instructions(instructions)
|
||||||
|
|
||||||
|
scopes.append(current_scope)
|
||||||
|
|
||||||
|
else:
|
||||||
|
#something was declared in global scope
|
||||||
|
self._global_instructions.append(self._construct_instruction_from_tokens(line_tokens))
|
||||||
|
|
||||||
|
self.add_globals_to_scope_list(scopes)
|
||||||
|
return scopes
|
||||||
|
|
||||||
|
def _get_instructions_in_scope(self):
|
||||||
|
|
||||||
|
instructions = []
|
||||||
|
|
||||||
|
while self._peek():
|
||||||
|
|
||||||
|
line_tokens = self.get_line_tokens()
|
||||||
|
instruction = self._construct_instruction_from_tokens(line_tokens)
|
||||||
|
if instruction:
|
||||||
|
instructions.append(instruction)
|
||||||
|
|
||||||
|
delimiter_token = line_tokens[-1]
|
||||||
|
if delimiter_token.type == Token_type.RIGHT_CURLY:
|
||||||
|
return instructions
|
||||||
|
|
||||||
|
raise JavaSyntaxError(f"{self._peek(-1).location}: Missing right curly!")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def get_tokens_until(self, delimiter_types: List[Token_type]) -> List[Token]:
|
||||||
|
tokens = []
|
||||||
|
while token := self._consume():
|
||||||
|
tokens.append(token)
|
||||||
|
if token.type in delimiter_types:
|
||||||
|
break
|
||||||
|
return tokens
|
||||||
|
|
||||||
|
def get_line_tokens(self):
|
||||||
|
return self.get_tokens_until([Token_type.SEMICOLON, Token_type.LEFT_CURLY, Token_type.RIGHT_CURLY])
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def add_globals_to_scope_list(self, scope_list: List[Function_scope]):
|
||||||
|
global_scope = Function_scope("<Global scope>", "void", [])
|
||||||
|
global_scope._add_instructions(self._global_instructions)
|
||||||
|
|
||||||
|
scope_list.append(global_scope)
|
||||||
|
|
||||||
|
|
||||||
|
def _is_function_def(self, tokens: List[Token]) -> bool:
|
||||||
|
#if token list is of shape TYPE_NAME IDENTIFIER ( ... {
|
||||||
|
return tokens[0].type == Token_type.TYPE_NAME and tokens[1].type == Token_type.UNKNOWN and tokens[2].type == Token_type.LEFT_PAREN and tokens[-1].type == Token_type.LEFT_CURLY
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _construct_instruction_from_tokens(self, tokens: List[Token]):
|
||||||
|
instruction_token = tokens[0]
|
||||||
|
|
||||||
|
if instruction_token.type == Token_type.IF_STATEMENT:
|
||||||
|
return self._handle_if_construct(tokens)
|
||||||
|
|
||||||
|
elif instruction_token.type == Token_type.WHILE_STATEMENT:
|
||||||
|
return self._handle_while_construct(tokens)
|
||||||
|
|
||||||
|
elif instruction_token.type == Token_type.DO_WHILE_STATEMENT:
|
||||||
|
return self._handle_do_while_construct(tokens)
|
||||||
|
|
||||||
|
elif instruction_token.type == Token_type.FOR_STATEMENT:
|
||||||
|
return self._handle_for_construct(tokens)
|
||||||
|
|
||||||
|
elif instruction_token.type == Token_type.TYPE_NAME:
|
||||||
|
return self._handle_type_name_construct(tokens)
|
||||||
|
|
||||||
|
elif instruction_token.type == Token_type.UNKNOWN:
|
||||||
|
return self._handle_generic_construct(tokens)
|
||||||
|
|
||||||
|
def _construct_function_header_from_tokens(self, tokens: List[Token]) -> Tuple[str, str, List[str]]:
|
||||||
|
|
||||||
|
_ensure_correct_function_structure(tokens)
|
||||||
|
|
||||||
|
function_return_type = tokens[0].content
|
||||||
|
|
||||||
|
function_name = tokens[1].content
|
||||||
|
|
||||||
|
argument_list = _get_function_argument_list_from_tokens(tokens[3:-2])
|
||||||
|
|
||||||
|
return function_name, function_return_type, argument_list
|
||||||
|
|
||||||
|
def _construct_variable_def_from_tokens(self, tokens: List[Token]) -> str:
|
||||||
|
_ensure_correct_variable_structure(tokens)
|
||||||
|
|
||||||
|
variable_type = tokens[0].content
|
||||||
|
variable_name = tokens[1].content
|
||||||
|
|
||||||
|
if tokens[2].type == Token_type.SEMICOLON:
|
||||||
|
return f"declare variable '{variable_name}' of type {variable_type}"
|
||||||
|
|
||||||
|
variable_value = self._construct_source_line_from_tokens(tokens[3:])
|
||||||
|
|
||||||
|
return f"declare variable '{variable_name}' of type {variable_type} with value {variable_value}"
|
||||||
|
|
||||||
|
def _construct_source_line_from_tokens(self, tokens: List[Token]) -> str:
|
||||||
|
"""TODO: make this function smarter"""
|
||||||
|
line = ""
|
||||||
|
|
||||||
|
for token in tokens:
|
||||||
|
if token.type == Token_type.SEMICOLON:
|
||||||
|
break
|
||||||
|
line += token.content + ' '
|
||||||
|
|
||||||
|
return line[:-1] #ignore the space after the last instruction text
|
||||||
|
|
||||||
|
"""Handler functions for different types of language structures"""
|
||||||
|
|
||||||
|
def _handle_if_construct(self, tokens: List[Token]):
|
||||||
|
logging.debug("Found if construct")
|
||||||
|
|
||||||
|
_ensure_correct_if_structure(tokens)
|
||||||
|
|
||||||
|
condition_str = self._construct_source_line_from_tokens(tokens[2:-2])
|
||||||
|
|
||||||
|
true_case = self._get_instructions_in_scope()
|
||||||
|
false_case = self._handle_else_construct()
|
||||||
|
|
||||||
|
return if_instruction(condition_str, true_case, false_case)
|
||||||
|
|
||||||
|
def _handle_else_construct(self):
|
||||||
|
if self._peek().type == Token_type.ELSE_STATEMENT:
|
||||||
|
if self._peek(1).type == Token_type.IF_STATEMENT:
|
||||||
|
logging.debug("Found if-else construct")
|
||||||
|
else_if_tokens = self.get_line_tokens()[1:]
|
||||||
|
return [self._handle_if_construct(else_if_tokens)]
|
||||||
|
else:
|
||||||
|
logging.debug("Found else construct")
|
||||||
|
self.get_line_tokens()
|
||||||
|
return self._get_instructions_in_scope()
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _handle_while_construct(self, tokens: List[Token]):
|
||||||
|
logging.debug("Found while construct")
|
||||||
|
|
||||||
|
_ensure_correct_while_structure(tokens)
|
||||||
|
|
||||||
|
condtion_str = self._construct_source_line_from_tokens(tokens[2:-2])
|
||||||
|
|
||||||
|
loop_instructions = self._get_instructions_in_scope()
|
||||||
|
|
||||||
|
return while_instruction_front(condtion_str, loop_instructions)
|
||||||
|
|
||||||
|
def _handle_do_while_construct(self, tokens: List[Token]):
|
||||||
|
logging.debug("Found do-while construct")
|
||||||
|
|
||||||
|
_ensure_correct_do_while_structure_part_1(tokens)
|
||||||
|
|
||||||
|
|
||||||
|
loop_instructions = self._get_instructions_in_scope()
|
||||||
|
|
||||||
|
|
||||||
|
while_tokens = self.get_line_tokens()
|
||||||
|
_ensure_correct_do_while_structure_part_2(while_tokens)
|
||||||
|
condtion_str = self._construct_source_line_from_tokens(while_tokens[2:-2])
|
||||||
|
|
||||||
|
return while_instruction_back(condtion_str, loop_instructions)
|
||||||
|
|
||||||
|
def _handle_for_construct(self, tokens: List[Token]):
|
||||||
|
logging.debug("Found for construct")
|
||||||
|
tokens.extend(self.get_tokens_until([Token_type.LEFT_CURLY]))
|
||||||
|
|
||||||
|
_ensure_correct_for_structure(tokens)
|
||||||
|
|
||||||
|
variable_tokens, condition_tokens, increment_tokens = _get_for_arguments_from_tokens(tokens[2:])
|
||||||
|
|
||||||
|
variable_str = ""
|
||||||
|
if len(variable_tokens) > 1: #if we got more than just a semicolon
|
||||||
|
variable_str = self._construct_variable_def_from_tokens(variable_tokens)
|
||||||
|
|
||||||
|
condition_str = "true"
|
||||||
|
if condition_tokens:
|
||||||
|
condition_str = self._construct_source_line_from_tokens(condition_tokens)
|
||||||
|
|
||||||
|
increment_instruction = None
|
||||||
|
if increment_tokens:
|
||||||
|
increment_instruction = generic_instruction(self._construct_source_line_from_tokens(increment_tokens))
|
||||||
|
|
||||||
|
loop_instructions = self._get_instructions_in_scope()
|
||||||
|
|
||||||
|
if increment_instruction:
|
||||||
|
loop_instructions.append(increment_instruction)
|
||||||
|
|
||||||
|
return for_instruction(variable_str, condition_str, loop_instructions)
|
||||||
|
|
||||||
|
def _handle_type_name_construct(self, tokens: List[Token]):
|
||||||
|
logging.debug("Found Type name construct")
|
||||||
|
|
||||||
|
return generic_instruction(self._construct_variable_def_from_tokens(tokens))
|
||||||
|
|
||||||
|
def _handle_generic_construct(self, tokens: List[Token]):
|
||||||
|
logging.debug("Found generic instruction")
|
||||||
|
|
||||||
|
return generic_instruction(self._construct_source_line_from_tokens(tokens))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _ensure_correct_function_structure(tokens: List[Token]):
|
||||||
|
#function structure: TYPE_NAME IDENTIFIER ( ... ) {
|
||||||
|
if len(tokens) < 5:
|
||||||
|
raise JavaSyntaxError(f"{tokens[0].location}: Ill-formed function declaration! Expected at least 5 tokens, got {len(tokens)}")
|
||||||
|
if tokens[-1].type != Token_type.LEFT_CURLY:
|
||||||
|
raise JavaSyntaxError(f"{tokens[-1].location}: Ill-formed function declaration! Expected last token to be LEFT_CURLY, got {str(tokens[-1].type)}")
|
||||||
|
if tokens[1].type != Token_type.UNKNOWN:
|
||||||
|
raise JavaSyntaxError(f"{tokens[1].location}: Illegal token after function return type! Expected UNKNWON, got {str(tokens[1].type)}")
|
||||||
|
if tokens[2].type != Token_type.LEFT_PAREN:
|
||||||
|
raise JavaSyntaxError(f"{tokens[2].location}: Illegal token after funtion name! Expected LEFT_CURLY, got {str(tokens[2].type)}")
|
||||||
|
if tokens[-2].type != Token_type.RIGTH_PAREN:
|
||||||
|
raise JavaSyntaxError(f"{tokens[-2].location}: Illegal token after function parameter list! Expected RIGHT_PAREN, got {str(tokens[-2].type)}")
|
||||||
|
|
||||||
|
def _ensure_correct_variable_structure(tokens: List[Token]):
|
||||||
|
#variable structure: TYPE_NAME IDENTIFIER ;|( = EXPRESSION;)
|
||||||
|
if len(tokens) < 3:
|
||||||
|
raise JavaSyntaxError(f"{tokens[0].location}: Ill-formed type construct! Expected at least 3 tokens, got {len(tokens)}")
|
||||||
|
if tokens[1].type != Token_type.UNKNOWN:
|
||||||
|
raise JavaSyntaxError(f"{tokens[1].location}: Illegal token after type name! Expected UNKNOWN, got {str(tokens[1].type)}")
|
||||||
|
if not tokens[2].type in [Token_type.SEMICOLON, Token_type.EQUAL_SIGN]:
|
||||||
|
raise JavaSyntaxError(f"{tokens[2].location}: Illegal token after variable name! Expected SEMICOLON or EQUAL_SIGN, got {str(tokens[2].type)}")
|
||||||
|
if tokens[2].type == Token_type.EQUAL_SIGN and len(tokens) < 5:
|
||||||
|
raise JavaSyntaxError(f"{tokens[2].location}: Ill-formed assignment expression! Expected at least 5 tokens, got {len(tokens)}")
|
||||||
|
|
||||||
|
def _ensure_correct_if_structure(tokens: List[Token]):
|
||||||
|
#if structure: IF ( ... ) { <-- the opening curly is technically not needed, but we require it anyways
|
||||||
|
if len(tokens) < 5:
|
||||||
|
raise JavaSyntaxError(f"{tokens[0].location}: Ill-formed if construct! Expected at least 5 tokens, got {len(tokens)}")
|
||||||
|
if tokens[-1].type != Token_type.LEFT_CURLY:
|
||||||
|
raise JavaSyntaxError(f"{tokens[-1].location}: Ill-formed if construct! Expected last token to be LEFT_CURLY, got {str(tokens[-1].type)}")
|
||||||
|
if tokens[1].type != Token_type.LEFT_PAREN:
|
||||||
|
raise JavaSyntaxError(f"{tokens[1].location}: Illegal token after if token! Expected LEFT_PAREN, got {str(tokens[1].type)}")
|
||||||
|
if tokens[-2].type != Token_type.RIGTH_PAREN:
|
||||||
|
raise JavaSyntaxError(f"{tokens[-2].location}: Illegal token after conditional expression! Expected RIGHT_PAREN, got {str(tokens[-2].type)}")
|
||||||
|
|
||||||
|
def _ensure_correct_while_structure(tokens: List[Token]):
|
||||||
|
#while structure: WHILE ( ... ) { <-- might not be required by the standard, but is required by us
|
||||||
|
if len(tokens) < 5:
|
||||||
|
raise JavaSyntaxError(f"{tokens[0].location}: Ill-formed while construct! Expected at least 5 tokens, got {len(tokens)}")
|
||||||
|
if tokens[-1].type != Token_type.LEFT_CURLY:
|
||||||
|
raise JavaSyntaxError(f"{tokens[-1].location}: Ill-formed while construct! Expected last token to be LEFT_CURLY, got {str(tokens[-1].type)}")
|
||||||
|
if tokens[1].type != Token_type.LEFT_PAREN:
|
||||||
|
raise JavaSyntaxError(f"{tokens[1].location}: Illegal token after while token! Expected LEFT_PAREN, got {str(tokens[1].type)}")
|
||||||
|
if tokens[-2].type != Token_type.RIGTH_PAREN:
|
||||||
|
raise JavaSyntaxError(f"{tokens[-2].location}: Illegal token after while condition! Expected RIGHT_PAREN, got {str(tokens[-2].type)}")
|
||||||
|
|
||||||
|
def _ensure_correct_do_while_structure_part_1(tokens: List[Token]):
|
||||||
|
#do-while structure: do{
|
||||||
|
if len(tokens) != 2:
|
||||||
|
raise JavaSyntaxError(f"{tokens[0].location}: Ill-formed do-while construct! Expected 2 tokens, got {len(tokens)}")
|
||||||
|
if tokens[1].type != Token_type.LEFT_CURLY:
|
||||||
|
raise JavaSyntaxError(f"Illegal token after do token! Expected LEFT_CURLY, got {str(tokens[1].type)}")
|
||||||
|
|
||||||
|
def _ensure_correct_do_while_structure_part_2(tokens: List[Token]):
|
||||||
|
#do-while structure: while( ... );
|
||||||
|
if len(tokens) < 5:
|
||||||
|
raise JavaSyntaxError(f"{tokens[0].location}: Ill-formed do while contruct! Expected at least 5 tokens, got {len(tokens)}")
|
||||||
|
if tokens[0].type != Token_type.WHILE_STATEMENT:
|
||||||
|
raise JavaSyntaxError(f"{tokens[0].location}: Illegal token after do block! Expected WHILE_STATEMENT, got {str(tokens[1].type)}")
|
||||||
|
if tokens[-1].type != Token_type.SEMICOLON:
|
||||||
|
raise JavaSyntaxError(f"{tokens[-1].location}: Ill-formed do-while construct! Expected last token to be SEMICOLON, got {str(tokens[-1].type)}")
|
||||||
|
if tokens[1].type != Token_type.LEFT_PAREN:
|
||||||
|
raise JavaSyntaxError(f"{tokens[1].location}: Illegal token after while token! Expected LEFT_PAREN, got {str(tokens[1].type)}")
|
||||||
|
if tokens[-2].type != Token_type.RIGTH_PAREN:
|
||||||
|
raise JavaSyntaxError(f"{tokens[-2].location}: Illegal token after do-while condition! Expected RIGHT_PAREN, got {str(tokens[-2].type)}")
|
||||||
|
|
||||||
|
def _ensure_correct_for_structure(tokens: List[Token]):
|
||||||
|
#for structure: for(...?;...?;...?) {
|
||||||
|
if len(tokens) < 6:
|
||||||
|
raise JavaSyntaxError(f"{tokens[0].location}: Illf-formed for loop construct! Expected at least 6 tokens, got {len(tokens)}")
|
||||||
|
if tokens[-1].type != Token_type.LEFT_CURLY:
|
||||||
|
raise JavaSyntaxError(f"{tokens[-1].location}: Ill-formed for loop construct! Expected last token to be LEFT_CURLY, got {str(tokens[-1].type)}")
|
||||||
|
if tokens[1].type != Token_type.LEFT_PAREN:
|
||||||
|
raise JavaSyntaxError(f"{tokens[1].location}: Illegal token after for token! Expected LEFT_PAREN, got {str(tokens[1].type)}")
|
||||||
|
if tokens[-2].type != Token_type.RIGTH_PAREN:
|
||||||
|
raise JavaSyntaxError(f"{tokens[-2].location}: Illegal token after for loop increment! Expected RIGHT_PAREN, got {str(tokens[-2].type)}")
|
||||||
|
if ( semicolon_count := tokens.count(Token(Token_type.SEMICOLON)) ) != 2:
|
||||||
|
raise JavaSyntaxError(f"Ill-formed for loop construct! Expected exactly 2 SEMICOLON tokens, got {semicolon_count}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _get_function_argument_list_from_tokens(tokens: List[Token]) -> List[str]:
|
||||||
|
arg_tokens = _get_seperated_token_list(tokens, [Token_type.COMMA])
|
||||||
|
|
||||||
|
args = []
|
||||||
|
|
||||||
|
for arg in arg_tokens:
|
||||||
|
arg_str = ""
|
||||||
|
for token in arg:
|
||||||
|
arg_str += token.content + ' '
|
||||||
|
arg_str = arg_str[:-1]
|
||||||
|
args.append(arg_str)
|
||||||
|
|
||||||
|
return args
|
||||||
|
|
||||||
|
def _get_seperated_token_list(tokens: List[Token], seperator_types: List[Token_type]) -> List[List[Token]]:
|
||||||
|
token_segments = []
|
||||||
|
tokens_in_segment = []
|
||||||
|
|
||||||
|
for token in tokens:
|
||||||
|
if token.type in seperator_types:
|
||||||
|
token_segments.append(tokens_in_segment)
|
||||||
|
tokens_in_segment = []
|
||||||
|
continue
|
||||||
|
tokens_in_segment.append(token)
|
||||||
|
|
||||||
|
token_segments.append(tokens_in_segment)
|
||||||
|
|
||||||
|
return token_segments
|
||||||
|
|
||||||
|
|
||||||
|
def _get_for_arguments_from_tokens(tokens: List[Token]) -> Tuple[List[Token], List[Token], List[Token]]:
|
||||||
|
variable_tokens = []
|
||||||
|
condition_tokens = []
|
||||||
|
increment_tokens = []
|
||||||
|
|
||||||
|
token_index = 0
|
||||||
|
|
||||||
|
while True:
|
||||||
|
token = tokens[token_index]
|
||||||
|
token_index += 1
|
||||||
|
|
||||||
|
variable_tokens.append(token)
|
||||||
|
if token.type == Token_type.SEMICOLON:
|
||||||
|
break
|
||||||
|
|
||||||
|
while True:
|
||||||
|
token = tokens[token_index]
|
||||||
|
token_index += 1
|
||||||
|
|
||||||
|
if token.type == Token_type.SEMICOLON:
|
||||||
|
break
|
||||||
|
condition_tokens.append(token)
|
||||||
|
|
||||||
|
while True:
|
||||||
|
token = tokens[token_index]
|
||||||
|
token_index += 1
|
||||||
|
|
||||||
|
if token.type == Token_type.LEFT_CURLY:
|
||||||
|
break
|
||||||
|
increment_tokens.append(token)
|
||||||
|
|
||||||
|
return variable_tokens, condition_tokens, increment_tokens[:-1]
|
||||||
@@ -10,7 +10,8 @@ from enum import IntEnum
|
|||||||
import os.path
|
import os.path
|
||||||
import secrets
|
import secrets
|
||||||
|
|
||||||
from interpreter.interpret_source import JavaInterpreter
|
from interpreter.Tokenizer import Tokenizer
|
||||||
|
from interpreter.Lexer import Lexer
|
||||||
from interpreter.function_scope import Function_scope
|
from interpreter.function_scope import Function_scope
|
||||||
from draw.code_to_image_wrapper import NSD_writer
|
from draw.code_to_image_wrapper import NSD_writer
|
||||||
import draw.code_to_image as cti
|
import draw.code_to_image as cti
|
||||||
@@ -38,12 +39,13 @@ class NassiShneidermanDiagram:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _save_scope(scope: Function_scope, output_path: str):
|
def _save_scope(scope: Function_scope, output_path: str):
|
||||||
y_size = scope.get_height()
|
width = scope.get_width()
|
||||||
x_size = scope.get_width()
|
height = scope.get_height()
|
||||||
with NSD_writer(output_path, x_size, y_size):
|
with NSD_writer(output_path, width, height):
|
||||||
x, y = 0, 0
|
y = 0
|
||||||
for instruction in scope:
|
for instruction in scope:
|
||||||
x, y = instruction.to_image(x, y, x_size)
|
print(instruction.instruction_text)
|
||||||
|
y = instruction.convert_to_image(0, y, width)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def check_conflicts(filepath:str, behavoiur: Overwrite_behaviour):
|
def check_conflicts(filepath:str, behavoiur: Overwrite_behaviour):
|
||||||
@@ -64,6 +66,7 @@ class NassiShneidermanDiagram:
|
|||||||
|
|
||||||
filepath = f"{output_path}/{scope.name}"
|
filepath = f"{output_path}/{scope.name}"
|
||||||
filepath = self.check_conflicts(filepath, on_conflict)
|
filepath = self.check_conflicts(filepath, on_conflict)
|
||||||
|
|
||||||
if filepath is not None:
|
if filepath is not None:
|
||||||
logging.info(f"Saving NSD to {filepath}.png...")
|
logging.info(f"Saving NSD to {filepath}.png...")
|
||||||
|
|
||||||
@@ -81,9 +84,14 @@ class NassiShneidermanDiagram:
|
|||||||
i+=1
|
i+=1
|
||||||
|
|
||||||
def load_from_file(self, filepath:str, itp_custom_tags: Optional[Dict[str, List[str]]]):
|
def load_from_file(self, filepath:str, itp_custom_tags: Optional[Dict[str, List[str]]]):
|
||||||
itp = JavaInterpreter(filepath)
|
|
||||||
itp.reset_tags(itp_custom_tags)
|
tokenizer = Tokenizer(filepath)
|
||||||
self.function_scopes = itp.load_instruction_scopes()
|
|
||||||
|
tokens = tokenizer.get_tokens()
|
||||||
|
|
||||||
|
lexer = Lexer(tokens)
|
||||||
|
|
||||||
|
self.function_scopes = lexer.get_instructions()[:-1]
|
||||||
|
|
||||||
if not self.function_scopes:
|
if not self.function_scopes:
|
||||||
return True
|
return True
|
||||||
|
|||||||
112
interpreter/Tokenizer.py
Normal file
112
interpreter/Tokenizer.py
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
"""Tokenizer.py: Definition for Tokenizer class"""
|
||||||
|
|
||||||
|
from errors.custom import JavaSyntaxError
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
from interpreter._token import Token, make_token, SourceLocation
|
||||||
|
|
||||||
|
class Tokenizer:
|
||||||
|
"""This class will take the provided source file and convert it to a list of tokens"""
|
||||||
|
|
||||||
|
TOKEN_MATCH = re.compile(r"""\(|\)|\{|\}|;|(\n)|\+|-|\*|/|<|>|,| """)
|
||||||
|
|
||||||
|
def __init__(self, file_name: str) -> None:
|
||||||
|
with open(file_name) as f:
|
||||||
|
self.source_text = f.read()
|
||||||
|
self.source_index = 0
|
||||||
|
self.line_number = 1
|
||||||
|
self.column_number = 0
|
||||||
|
|
||||||
|
self.source_text = re.sub("(private)|(public)|(protected)|(final)", "", self.source_text)
|
||||||
|
|
||||||
|
self.type_name_pattern = re.compile('(char)|(int)|(void)|(double)|(boolean)|(Pixel)|(String)') #TODO: make this modular
|
||||||
|
|
||||||
|
self._filename = file_name
|
||||||
|
|
||||||
|
self._left_curly_number=0
|
||||||
|
self._right_curly_number=0
|
||||||
|
|
||||||
|
def get_tokens(self) -> List[Token]:
|
||||||
|
|
||||||
|
tokens = []
|
||||||
|
|
||||||
|
while char := self._consume():
|
||||||
|
|
||||||
|
if char.isspace():
|
||||||
|
continue
|
||||||
|
|
||||||
|
if self._handle_comments(char):
|
||||||
|
continue
|
||||||
|
|
||||||
|
tag = self._get_token(char)
|
||||||
|
logging.debug(f"found tag \"{tag}\" on line {self.line_number}")
|
||||||
|
|
||||||
|
if tag == "{":
|
||||||
|
self._left_curly_number+=1
|
||||||
|
elif tag == "}":
|
||||||
|
self._right_curly_number+=1
|
||||||
|
|
||||||
|
tokens.append(make_token(tag, SourceLocation(self._filename, self.line_number, self.column_number), self.type_name_pattern))
|
||||||
|
|
||||||
|
if self._left_curly_number != self._right_curly_number:
|
||||||
|
raise JavaSyntaxError(f"Ill-formed Java program! Expected equal number of '{'{'}' and '{'}'}' tokens, got {self._left_curly_number} and {self._right_curly_number}")
|
||||||
|
|
||||||
|
return tokens
|
||||||
|
|
||||||
|
def _get_token(self, char: str) -> str:
|
||||||
|
token = char
|
||||||
|
|
||||||
|
if not re.match(Tokenizer.TOKEN_MATCH, token):
|
||||||
|
|
||||||
|
while (token_char := self._peek()):
|
||||||
|
if re.match(Tokenizer.TOKEN_MATCH, token_char):
|
||||||
|
break
|
||||||
|
token += self._consume()
|
||||||
|
|
||||||
|
return token
|
||||||
|
|
||||||
|
def _handle_comments(self, char: str) -> bool:
|
||||||
|
if char == '/' and self._peek() == '/':
|
||||||
|
self._get_line() #skip the entire line
|
||||||
|
return True
|
||||||
|
elif char == '/' and self._peek() == '*':
|
||||||
|
self._consume()
|
||||||
|
self._consume_multiline_comment()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _get_line(self) -> str:
|
||||||
|
return self._consume_until('\n')
|
||||||
|
|
||||||
|
def _peek(self, offset:int = 0) -> str:
|
||||||
|
if (self.source_index + offset) >= len(self.source_text):
|
||||||
|
return ''
|
||||||
|
char = self.source_text[self.source_index]
|
||||||
|
|
||||||
|
return char
|
||||||
|
|
||||||
|
def _consume(self) -> str:
|
||||||
|
char = self._peek()
|
||||||
|
|
||||||
|
if char == '\n':
|
||||||
|
self.line_number += 1
|
||||||
|
self.column_number = 1
|
||||||
|
|
||||||
|
self.source_index += 1
|
||||||
|
self.column_number += 1
|
||||||
|
return char
|
||||||
|
|
||||||
|
def _consume_multiline_comment(self):
|
||||||
|
while self._peek():
|
||||||
|
if self._consume() == '*' and self._peek() == '/':
|
||||||
|
self._consume()
|
||||||
|
break
|
||||||
|
|
||||||
|
def _consume_until(self, end_tag: str) -> str:
|
||||||
|
res = ""
|
||||||
|
while self._peek() and (char:= self._consume()) != end_tag:
|
||||||
|
res += char
|
||||||
|
|
||||||
|
return res
|
||||||
91
interpreter/_token.py
Normal file
91
interpreter/_token.py
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
"""Private definitions for Token class used by the Lexer"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from enum import IntEnum
|
||||||
|
from typing import Union
|
||||||
|
|
||||||
|
NUMERIC_CONSTANT_PATTERN = re.compile(r"""([0-9]+)|(true)|(false)""")
|
||||||
|
KEYWORD_PATTERN = re.compile(r"""(return)$|(continue)$|(break)$|(new)$""")
|
||||||
|
STRING_LITERAL_PATTERN = re.compile(r"""('|\")(.*)(\"|')""")
|
||||||
|
MATH_OP_PATTERN = re.compile(r"""\+|-|\*|/|<|>""")
|
||||||
|
|
||||||
|
class Token_type(IntEnum):
|
||||||
|
UNKNOWN=-1 #maybe this should be renamed to IDENTIFIER
|
||||||
|
LEFT_PAREN=0,
|
||||||
|
RIGTH_PAREN=1,
|
||||||
|
LEFT_CURLY=2,
|
||||||
|
RIGHT_CURLY=3,
|
||||||
|
LEFT_BRACKET=4,
|
||||||
|
RIGHT_BRACKET=5,
|
||||||
|
COMMA=6,
|
||||||
|
EQUAL_SIGN=7,
|
||||||
|
SEMICOLON=8
|
||||||
|
MATH_OP=9
|
||||||
|
NUMERIC_CONSTANT=10,
|
||||||
|
IF_STATEMENT=11,
|
||||||
|
ELSE_STATEMENT=12,
|
||||||
|
WHILE_STATEMENT=13,
|
||||||
|
DO_WHILE_STATEMENT=14,
|
||||||
|
FOR_STATEMENT=15,
|
||||||
|
KEY_WORD=16,
|
||||||
|
STRING_LITERAL=17
|
||||||
|
TYPE_NAME=18
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class SourceLocation:
|
||||||
|
file: str
|
||||||
|
line: int
|
||||||
|
column: int
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return f"File {self.file} {self.line}:{self.column}"
|
||||||
|
|
||||||
|
@dataclass(frozen=True, eq=True)
|
||||||
|
class Token:
|
||||||
|
type: Token_type
|
||||||
|
location: SourceLocation = field(compare=False, default=SourceLocation("", 0, 0))
|
||||||
|
content: str = field(compare=False, default="")
|
||||||
|
|
||||||
|
def make_token(tag: str, location: SourceLocation, type_name_pattern:re.Pattern) -> Token:
|
||||||
|
"""Construct a token object with the provided tag and source location"""
|
||||||
|
if tag == '(':
|
||||||
|
return Token(Token_type.LEFT_PAREN, location, tag)
|
||||||
|
elif tag == ')':
|
||||||
|
return Token(Token_type.RIGTH_PAREN, location, tag)
|
||||||
|
elif tag == '{':
|
||||||
|
return Token(Token_type.LEFT_CURLY, location, tag)
|
||||||
|
elif tag == '}':
|
||||||
|
return Token(Token_type.RIGHT_CURLY, location, tag)
|
||||||
|
elif tag == '[':
|
||||||
|
return Token(Token_type.LEFT_BRACKET, location, tag)
|
||||||
|
elif tag == ']':
|
||||||
|
return Token(Token_type.RIGHT_BRACKET, location, tag)
|
||||||
|
elif tag == ',':
|
||||||
|
return Token(Token_type.COMMA, location, tag)
|
||||||
|
elif tag == '=':
|
||||||
|
return Token(Token_type.EQUAL_SIGN, location, tag)
|
||||||
|
elif tag == ';':
|
||||||
|
return Token(Token_type.SEMICOLON, location, tag)
|
||||||
|
elif MATH_OP_PATTERN.match(tag):
|
||||||
|
return Token(Token_type.MATH_OP, location, tag)
|
||||||
|
elif NUMERIC_CONSTANT_PATTERN.match(tag):
|
||||||
|
return Token(Token_type.NUMERIC_CONSTANT, location, tag)
|
||||||
|
elif tag == "if":
|
||||||
|
return Token(Token_type.IF_STATEMENT, location, tag)
|
||||||
|
elif tag == "else":
|
||||||
|
return Token(Token_type.ELSE_STATEMENT, location, tag)
|
||||||
|
elif tag == "while":
|
||||||
|
return Token(Token_type.WHILE_STATEMENT, location, tag)
|
||||||
|
elif tag == "do":
|
||||||
|
return Token(Token_type.DO_WHILE_STATEMENT, location, tag)
|
||||||
|
elif tag == "for":
|
||||||
|
return Token(Token_type.FOR_STATEMENT, location, tag)
|
||||||
|
elif KEYWORD_PATTERN.match(tag):
|
||||||
|
return Token(Token_type.KEY_WORD, location, tag)
|
||||||
|
elif STRING_LITERAL_PATTERN.match(tag):
|
||||||
|
return Token(Token_type.STRING_LITERAL, location, tag)
|
||||||
|
elif type_name_pattern.match(tag):
|
||||||
|
return Token(Token_type.TYPE_NAME, location, tag)
|
||||||
|
else:
|
||||||
|
return Token(Token_type.UNKNOWN, location, tag)
|
||||||
@@ -1,29 +1,36 @@
|
|||||||
"""function_scope.py: #TODO"""
|
"""function_scope.py: Class for Function scopes"""
|
||||||
|
|
||||||
__author__ = "Weckyy702"
|
__author__ = "Weckyy702"
|
||||||
|
|
||||||
from typing import Iterable, List
|
from typing import Iterable, List
|
||||||
from draw.Iinstruction import Iinstruction
|
from draw.Iinstruction import instruction
|
||||||
|
|
||||||
|
|
||||||
class Function_scope(Iterable):
|
class Function_scope(Iterable):
|
||||||
def __init__(self, child_instructions: List[Iinstruction], name: str, return_type: str, args: List[str]) -> None:
|
"""This class serves as a container for Instructions"""
|
||||||
self.contents = child_instructions
|
|
||||||
|
def __init__(self, name: str, return_type: str, args: List[str]) -> None:
|
||||||
|
self.contents = []
|
||||||
self.name = name
|
self.name = name
|
||||||
self.return_type = return_type
|
self.return_type = return_type
|
||||||
self.args = args
|
self.args = args
|
||||||
|
|
||||||
def get_height(self) -> int:
|
def get_height(self) -> int:
|
||||||
h = 0.0
|
h = 0
|
||||||
for inst in self.contents:
|
for inst in self.contents:
|
||||||
h += inst.getblkheight()
|
h += inst.get_block_height()
|
||||||
return int(h)
|
return max(h, 5) #a NSD has to be at least 5 pixels tall
|
||||||
|
|
||||||
def get_width(self) -> int:
|
def get_width(self) -> int:
|
||||||
w = 200.0 #minimum width for every block
|
w = 200 #minimum width for every block
|
||||||
for inst in self.contents:
|
for inst in self.contents:
|
||||||
w = max(w, inst.getblkwidth())
|
w = max(w, inst.get_block_width())
|
||||||
return int(w)
|
return w
|
||||||
|
|
||||||
|
def _add_instruction(self, inst: instruction):
|
||||||
|
self.contents.append(inst)
|
||||||
|
|
||||||
|
def _add_instructions(self, inst: List[instruction]):
|
||||||
|
self.contents.extend(inst)
|
||||||
|
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
return self.contents.__iter__()
|
return self.contents.__iter__()
|
||||||
@@ -211,7 +211,7 @@ class JavaInterpreter:
|
|||||||
return generic_instruction(f"declare variable '{var_name}' of type {var_type}"), idx
|
return generic_instruction(f"declare variable '{var_name}' of type {var_type}"), idx
|
||||||
return generic_instruction(f"declare variable '{var_name}' of type {var_type} with value {var_value}"), idx
|
return generic_instruction(f"declare variable '{var_name}' of type {var_type} with value {var_value}"), idx
|
||||||
|
|
||||||
def _handle_instruction(self, line: str, idx:int) -> Tuple[Union[Iinstruction, List[Iinstruction]], int]:
|
def _handle_instruction(self, line: str, idx:int) -> Tuple[Union[instruction, List[instruction]], int]:
|
||||||
if line.startswith("while("):
|
if line.startswith("while("):
|
||||||
logging.debug("Found while construct in line: %i", idx+1)
|
logging.debug("Found while construct in line: %i", idx+1)
|
||||||
return self._handle_while(line, idx)
|
return self._handle_while(line, idx)
|
||||||
@@ -236,8 +236,8 @@ class JavaInterpreter:
|
|||||||
logging.debug("Found generic instruction in line %i", idx+1)
|
logging.debug("Found generic instruction in line %i", idx+1)
|
||||||
return generic_instruction(line), idx
|
return generic_instruction(line), idx
|
||||||
|
|
||||||
def _get_instructions_in_scope(self, idx: int=0) -> Tuple[List[Iinstruction], int]:
|
def _get_instructions_in_scope(self, idx: int=0) -> Tuple[List[instruction], int]:
|
||||||
scope: List[Iinstruction] = []
|
scope: List[instruction] = []
|
||||||
i = idx
|
i = idx
|
||||||
while i < len(self._lines):
|
while i < len(self._lines):
|
||||||
line = self._lines[i]
|
line = self._lines[i]
|
||||||
@@ -267,7 +267,7 @@ class JavaInterpreter:
|
|||||||
fname = groups["name"]
|
fname = groups["name"]
|
||||||
return ftype, fname, fargs
|
return ftype, fname, fargs
|
||||||
|
|
||||||
def _get_function_instructions(self, function_header: str) -> List[Iinstruction]:
|
def _get_function_instructions(self, function_header: str) -> List[instruction]:
|
||||||
idx = self._lines.index(function_header)
|
idx = self._lines.index(function_header)
|
||||||
brace_offset = self._get_scope_start_offset(idx)
|
brace_offset = self._get_scope_start_offset(idx)
|
||||||
return self._get_instructions_in_scope(idx+brace_offset)[0]
|
return self._get_instructions_in_scope(idx+brace_offset)[0]
|
||||||
|
|||||||
@@ -1,380 +0,0 @@
|
|||||||
// import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
|
|
||||||
|
|
||||||
// //Comment that the interpreter may never know of
|
|
||||||
|
|
||||||
// public class Rover extends Actor
|
|
||||||
// {
|
|
||||||
// private Display anzeige;
|
|
||||||
|
|
||||||
// /**
|
|
||||||
// * this function is to be implemented by the user
|
|
||||||
// * depending on the needed actions
|
|
||||||
// */
|
|
||||||
|
|
||||||
// public Display getDisplay()
|
|
||||||
// {
|
|
||||||
// return anzeige;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// public void act()
|
|
||||||
// {
|
|
||||||
// S66Nr3(7);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// private void fahreUmHuegel(String richtung)
|
|
||||||
// {
|
|
||||||
// String pri;
|
|
||||||
// String sec;
|
|
||||||
// if(richtung.equals("Hoch")) {
|
|
||||||
// pri = "links";
|
|
||||||
// sec = "rechts";
|
|
||||||
// } else if (richtung.equals("Runter")) {
|
|
||||||
// pri = "rechts";
|
|
||||||
// sec = "links";
|
|
||||||
// } else {
|
|
||||||
// nachricht("JUNGE DU SPAST!");
|
|
||||||
// return;
|
|
||||||
// }
|
|
||||||
// drehe(pri);
|
|
||||||
// fahre();
|
|
||||||
// drehe(sec);
|
|
||||||
// fahre();
|
|
||||||
// fahre();
|
|
||||||
// drehe(sec);
|
|
||||||
// fahre();
|
|
||||||
// drehe(pri);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// private void fahreBisHuegel()
|
|
||||||
// {
|
|
||||||
// while(!huegelVorhanden("vorne"))
|
|
||||||
// {
|
|
||||||
// fahre();
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// private void fahreZeileDreheHoch()
|
|
||||||
// {
|
|
||||||
// fahreBisHuegel();
|
|
||||||
// fahreUmHuegel("Hoch");
|
|
||||||
// fahreBisHuegel();
|
|
||||||
// drehe("um");
|
|
||||||
|
|
||||||
// fahreBisHuegel();
|
|
||||||
// fahreUmHuegel("Runter");
|
|
||||||
// fahreBisHuegel();
|
|
||||||
// drehe("rechts");
|
|
||||||
// fahre();
|
|
||||||
// drehe("rechts");
|
|
||||||
// }
|
|
||||||
|
|
||||||
// private void fahreZeileDreheRunter(boolean geheInNächsteZeile)
|
|
||||||
// {
|
|
||||||
// fahreBisHuegel();
|
|
||||||
// fahreUmHuegel("Runter");
|
|
||||||
// fahreBisHuegel();
|
|
||||||
// drehe("um");
|
|
||||||
|
|
||||||
// fahreBisHuegel();
|
|
||||||
// fahreUmHuegel("Hoch");
|
|
||||||
// fahreBisHuegel();
|
|
||||||
// if(geheInNächsteZeile) {
|
|
||||||
// drehe("rechts");
|
|
||||||
// fahre();
|
|
||||||
// drehe("rechts");
|
|
||||||
// } else {
|
|
||||||
// drehe("um");
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// private void S66Nr3(int anzahlZeilen)
|
|
||||||
// {
|
|
||||||
// if(anzahlZeilen < 3) {
|
|
||||||
// nachricht("Ich muss mindestens drei Zeilen fahren! :(");
|
|
||||||
// return;
|
|
||||||
// }
|
|
||||||
// int i = 1;
|
|
||||||
// fahreZeileDreheHoch();
|
|
||||||
// for(; i < anzahlZeilen-1; i++) {
|
|
||||||
// fahreZeileDreheRunter(true);
|
|
||||||
// }
|
|
||||||
// fahreZeileDreheRunter(false);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// /**
|
|
||||||
// * Der Rover bewegt sich ein Feld in Fahrtrichtung weiter.
|
|
||||||
// * Sollte sich in Fahrtrichtung ein Objekt der Klasse Huegel befinden oder er sich an der Grenze der Welt befinden,
|
|
||||||
// * dann erscheint eine entsprechende Meldung auf dem Display.
|
|
||||||
// */
|
|
||||||
// public void fahre()
|
|
||||||
// {
|
|
||||||
// int posX = getX();
|
|
||||||
// int posY = getY();
|
|
||||||
|
|
||||||
// if(huegelVorhanden("vorne"))
|
|
||||||
// {
|
|
||||||
// nachricht("Zu steil!");
|
|
||||||
// }
|
|
||||||
// else if(getRotation()==270 && getY()==1)
|
|
||||||
// {
|
|
||||||
// nachricht("Ich kann mich nicht bewegen");
|
|
||||||
// }
|
|
||||||
// else
|
|
||||||
// {
|
|
||||||
// move(1);
|
|
||||||
// Greenfoot.delay(1);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// if(posX==getX()&&posY==getY()&&!huegelVorhanden("vorne"))
|
|
||||||
// {
|
|
||||||
// nachricht("Ich kann mich nicht bewegen");
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// /**
|
|
||||||
// * Der Rover dreht sich um 90 Grad in die Richtung, die mit richtung (ᅵlinksᅵ oder ᅵrechtsᅵ) ᅵbergeben wurde.
|
|
||||||
// * Sollte ein anderer Text (String) als "rechts" oder "links" ᅵbergeben werden, dann erscheint eine entsprechende Meldung auf dem Display.
|
|
||||||
// */
|
|
||||||
// public void drehe(String richtung)
|
|
||||||
// {
|
|
||||||
// if(richtung.equals("rechts")){
|
|
||||||
// setRotation(getRotation()+90);
|
|
||||||
// }else if(richtung.equals("links")){
|
|
||||||
// setRotation(getRotation()-90);
|
|
||||||
// } else if(richtung.equals("um")) {
|
|
||||||
// setRotation(getRotation()+180);
|
|
||||||
// }else {
|
|
||||||
// nachricht("Keinen Korrekte Richtung gegeben!");
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// /**
|
|
||||||
// * Der Rover gibt durch einen Wahrheitswert (true oder false )zurᅵck, ob sich auf seiner Position ein Objekt der Klasse Gestein befindet.
|
|
||||||
// * Eine entsprechende Meldung erscheint auch auf dem Display.
|
|
||||||
// */
|
|
||||||
// public boolean gesteinVorhanden()
|
|
||||||
// {
|
|
||||||
// if(getOneIntersectingObject(Gestein.class)!=null)
|
|
||||||
// {
|
|
||||||
// nachricht("Gestein gefunden!");
|
|
||||||
// return true;
|
|
||||||
|
|
||||||
// }
|
|
||||||
|
|
||||||
// return false;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// /**
|
|
||||||
// * Der Rover ᅵberprᅵft, ob sich in richtung ("rechts", "links", oder "vorne") ein Objekt der Klasse Huegel befindet.
|
|
||||||
// * Das Ergebnis wird auf dem Display angezeigt.
|
|
||||||
// * Sollte ein anderer Text (String) als "rechts", "links" oder "vorne" ᅵbergeben werden, dann erscheint eine entsprechende Meldung auf dem Display.
|
|
||||||
// */
|
|
||||||
// public boolean huegelVorhanden(String richtung)
|
|
||||||
// {
|
|
||||||
// int rot = getRotation();
|
|
||||||
|
|
||||||
// if (richtung=="vorne" && rot==0 || richtung=="rechts" && rot==270 || richtung=="links" && rot==90)
|
|
||||||
// {
|
|
||||||
// if(getOneObjectAtOffset(1,0,Huegel.class)!=null && ((Huegel)getOneObjectAtOffset(1,0,Huegel.class)).getSteigung() >30)
|
|
||||||
// {
|
|
||||||
// return true;
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// if (richtung=="vorne" && rot==180 || richtung=="rechts" && rot==90 || richtung=="links" && rot==270)
|
|
||||||
// {
|
|
||||||
// if(getOneObjectAtOffset(-1,0,Huegel.class)!=null && ((Huegel)getOneObjectAtOffset(-1,0,Huegel.class)).getSteigung() >30)
|
|
||||||
// {
|
|
||||||
// return true;
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// if (richtung=="vorne" && rot==90 || richtung=="rechts" && rot==0 || richtung=="links" && rot==180)
|
|
||||||
// {
|
|
||||||
// if(getOneObjectAtOffset(0,1,Huegel.class)!=null && ((Huegel)getOneObjectAtOffset(0,1,Huegel.class)).getSteigung() >30)
|
|
||||||
// {
|
|
||||||
// return true;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// }
|
|
||||||
|
|
||||||
// if (richtung=="vorne" && rot==270 || richtung=="rechts" && rot==180 || richtung=="links" && rot==0)
|
|
||||||
// {
|
|
||||||
// if(getOneObjectAtOffset(0,-1,Huegel.class)!=null && ((Huegel)getOneObjectAtOffset(0,-1,Huegel.class)).getSteigung() >30)
|
|
||||||
// {
|
|
||||||
// return true;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// }
|
|
||||||
|
|
||||||
// if(richtung!="vorne" && richtung!="links" && richtung!="rechts")
|
|
||||||
// {
|
|
||||||
// nachricht("Befehl nicht korrekt!");
|
|
||||||
// }
|
|
||||||
|
|
||||||
// return false;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// /**
|
|
||||||
// * Der Rover ermittelt den Wassergehalt des Gesteins auf seiner Position und gibt diesen auf dem Display aus.
|
|
||||||
// * Sollte kein Objekt der Klasse Gestein vorhanden sein, dann erscheint eine entsprechende Meldung auf dem Display.
|
|
||||||
// */
|
|
||||||
// public void analysiereGestein()
|
|
||||||
// {
|
|
||||||
// if(gesteinVorhanden())
|
|
||||||
// {
|
|
||||||
// nachricht("Gestein untersucht! Wassergehalt ist " + ((Gestein)getOneIntersectingObject(Gestein.class)).getWassergehalt()+"%.");
|
|
||||||
// Greenfoot.delay(1);
|
|
||||||
// removeTouching(Gestein.class);
|
|
||||||
// }
|
|
||||||
// else
|
|
||||||
// {
|
|
||||||
// nachricht("Hier ist kein Gestein");
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// /**
|
|
||||||
// * Der Rover erzeugt ein Objekt der Klasse ᅵMarkierungᅵ auf seiner Position.
|
|
||||||
// */
|
|
||||||
// public void setzeMarke()
|
|
||||||
// {
|
|
||||||
// getWorld().addObject(new Marke(), getX(), getY());
|
|
||||||
// }
|
|
||||||
|
|
||||||
// /**
|
|
||||||
// * *Der Rover gibt durch einen Wahrheitswert (true oder false )zurᅵck, ob sich auf seiner Position ein Objekt der Marke befindet.
|
|
||||||
// * Eine entsprechende Meldung erscheint auch auf dem Display.
|
|
||||||
// */
|
|
||||||
// public boolean markeVorhanden()
|
|
||||||
// {
|
|
||||||
// if(getOneIntersectingObject(Marke.class)!=null)
|
|
||||||
// {
|
|
||||||
// return true;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// return false;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// public void entferneMarke()
|
|
||||||
// {
|
|
||||||
// if(markeVorhanden())
|
|
||||||
// {
|
|
||||||
// removeTouching(Marke.class);
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// private void nachricht(String pText)
|
|
||||||
// {
|
|
||||||
// if(anzeige!=null)
|
|
||||||
// {
|
|
||||||
// anzeige.anzeigen(pText);
|
|
||||||
// Greenfoot.delay(1);
|
|
||||||
// anzeige.loeschen();
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// private void displayAusschalten()
|
|
||||||
// {
|
|
||||||
// getWorld().removeObject(anzeige);
|
|
||||||
|
|
||||||
// }
|
|
||||||
|
|
||||||
// protected void addedToWorld(World world)
|
|
||||||
// {
|
|
||||||
// setImage("images/rover.png");
|
|
||||||
// world = getWorld();
|
|
||||||
// anzeige = new Display();
|
|
||||||
// anzeige.setImage("images/nachricht.png");
|
|
||||||
// world.addObject(anzeige, 7, 0);
|
|
||||||
// if(getY()==0)
|
|
||||||
// {
|
|
||||||
// setLocation(getX(),1);
|
|
||||||
// }
|
|
||||||
// anzeige.anzeigen("Ich bin bereit");
|
|
||||||
// }
|
|
||||||
|
|
||||||
// class Display extends Actor
|
|
||||||
// {
|
|
||||||
// GreenfootImage bild;
|
|
||||||
|
|
||||||
// public Display()
|
|
||||||
// {
|
|
||||||
// bild = getImage();
|
|
||||||
// }
|
|
||||||
|
|
||||||
// public void act()
|
|
||||||
// {
|
|
||||||
|
|
||||||
// }
|
|
||||||
|
|
||||||
// public void anzeigen(String pText)
|
|
||||||
// {
|
|
||||||
// loeschen();
|
|
||||||
// getImage().drawImage(new GreenfootImage(pText, 25, Color.BLACK, new Color(0, 0, 0, 0)),10,10);
|
|
||||||
|
|
||||||
// }
|
|
||||||
|
|
||||||
// public void loeschen()
|
|
||||||
// {
|
|
||||||
// getImage().clear();
|
|
||||||
// setImage("images/nachricht.png");
|
|
||||||
// }
|
|
||||||
|
|
||||||
// }
|
|
||||||
|
|
||||||
// public class Direction {
|
|
||||||
// Direction(int val){
|
|
||||||
// this.value = val;
|
|
||||||
// }
|
|
||||||
// final int value;
|
|
||||||
// };
|
|
||||||
// }
|
|
||||||
|
|
||||||
class Testing {
|
|
||||||
|
|
||||||
public void test_function() {
|
|
||||||
int rot = getRotation();
|
|
||||||
|
|
||||||
//if (richtung=="vorne" && rot==0 || richtung=="rechts" && rot==270 || richtung=="links" && rot==90)
|
|
||||||
//{
|
|
||||||
if(getOneObjectAtOffset(1,0,Huegel.class)!=null && ((Huegel)getOneObjectAtOffset(1,0,Huegel.class)).getSteigung() >30)
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
//}
|
|
||||||
|
|
||||||
//if (richtung=="vorne" && rot==180 || richtung=="rechts" && rot==90 || richtung=="links" && rot==270)
|
|
||||||
//{
|
|
||||||
// if(getOneObjectAtOffset(-1,0,Huegel.class)!=null && ((Huegel)getOneObjectAtOffset(-1,0,Huegel.class)).getSteigung() >30)
|
|
||||||
// {
|
|
||||||
// return true;
|
|
||||||
// }
|
|
||||||
//}
|
|
||||||
|
|
||||||
// if (richtung=="vorne" && rot==90 || richtung=="rechts" && rot==0 || richtung=="links" && rot==180)
|
|
||||||
// {
|
|
||||||
// if(getOneObjectAtOffset(0,1,Huegel.class)!=null && ((Huegel)getOneObjectAtOffset(0,1,Huegel.class)).getSteigung() >30)
|
|
||||||
// {
|
|
||||||
// return true;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// }
|
|
||||||
|
|
||||||
// if (richtung=="vorne" && rot==270 || richtung=="rechts" && rot==180 || richtung=="links" && rot==0)
|
|
||||||
// {
|
|
||||||
// if(getOneObjectAtOffset(0,-1,Huegel.class)!=null && ((Huegel)getOneObjectAtOffset(0,-1,Huegel.class)).getSteigung() >30)
|
|
||||||
// {
|
|
||||||
// return true;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// }
|
|
||||||
|
|
||||||
// if(richtung!="vorne" && richtung!="links" && richtung!="rechts")
|
|
||||||
// {
|
|
||||||
// nachricht("Befehl nicht korrekt!");
|
|
||||||
// }
|
|
||||||
|
|
||||||
// return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,281 +0,0 @@
|
|||||||
importgreenfoot.*;//(World,Actor,GreenfootImage,GreenfootandMouseInfo)
|
|
||||||
classRoverextendsActor
|
|
||||||
{
|
|
||||||
Displayanzeige;
|
|
||||||
/**
|
|
||||||
*thisfunctionistobeimplementedbytheuser
|
|
||||||
*dependingontheneededactions
|
|
||||||
*/
|
|
||||||
voidact()
|
|
||||||
{
|
|
||||||
S66Nr3(7);
|
|
||||||
}
|
|
||||||
voidfahreUmHuegel(Stringrichtung)
|
|
||||||
{
|
|
||||||
Stringpri;
|
|
||||||
Stringsec;
|
|
||||||
if(richtung.equals("Hoch")){
|
|
||||||
pri="links";
|
|
||||||
sec="rechts";
|
|
||||||
}else{
|
|
||||||
if(richtung.equals("Runter")){
|
|
||||||
pri="rechts";
|
|
||||||
sec="links";
|
|
||||||
}else{
|
|
||||||
nachricht("JUNGEDUSPAST!");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
drehe(pri);
|
|
||||||
fahre();
|
|
||||||
drehe(sec);
|
|
||||||
fahre();
|
|
||||||
fahre();
|
|
||||||
drehe(sec);
|
|
||||||
fahre();
|
|
||||||
drehe(pri);
|
|
||||||
}
|
|
||||||
voidfahreBisHuegel()
|
|
||||||
{
|
|
||||||
while(!huegelVorhanden("vorne"))
|
|
||||||
{
|
|
||||||
fahre();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
voidfahreZeileDreheHoch()
|
|
||||||
{
|
|
||||||
fahreBisHuegel();
|
|
||||||
fahreUmHuegel("Hoch");
|
|
||||||
fahreBisHuegel();
|
|
||||||
drehe("um");
|
|
||||||
fahreBisHuegel();
|
|
||||||
fahreUmHuegel("Runter");
|
|
||||||
fahreBisHuegel();
|
|
||||||
drehe("rechts");
|
|
||||||
fahre();
|
|
||||||
drehe("rechts");
|
|
||||||
}
|
|
||||||
voidfahreZeileDreheRunter(booleangeheInNächsteZeile)
|
|
||||||
{
|
|
||||||
fahreBisHuegel();
|
|
||||||
fahreUmHuegel("Runter");
|
|
||||||
fahreBisHuegel();
|
|
||||||
drehe("um");
|
|
||||||
fahreBisHuegel();
|
|
||||||
fahreUmHuegel("Hoch");
|
|
||||||
fahreBisHuegel();
|
|
||||||
if(geheInNächsteZeile){
|
|
||||||
drehe("rechts");
|
|
||||||
fahre();
|
|
||||||
drehe("rechts");
|
|
||||||
}else{
|
|
||||||
drehe("um");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
voidS66Nr3(intanzahlZeilen)
|
|
||||||
{
|
|
||||||
if(anzahlZeilen<3){
|
|
||||||
nachricht("IchmussmindestensdreiZeilenfahren!:(");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
fahreZeileDreheHoch();
|
|
||||||
for(inti=1;i<anzahlZeilen-1;i++){
|
|
||||||
fahreZeileDreheRunter(true);
|
|
||||||
}
|
|
||||||
fahreZeileDreheRunter(false);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
*DerRoverbewegtsicheinFeldinFahrtrichtungweiter.
|
|
||||||
*SolltesichinFahrtrichtungeinObjektderKlasseHuegelbefindenoderersichanderGrenzederWeltbefinden,
|
|
||||||
*dannerscheinteineentsprechendeMeldungaufdemDisplay.
|
|
||||||
*/
|
|
||||||
voidfahre()
|
|
||||||
{
|
|
||||||
intposX=getX();
|
|
||||||
intposY=getY();
|
|
||||||
if(huegelVorhanden("vorne"))
|
|
||||||
{
|
|
||||||
nachricht("Zusteil!");
|
|
||||||
}
|
|
||||||
elseif(getRotation()==270&&getY()==1)
|
|
||||||
{
|
|
||||||
nachricht("Ichkannmichnichtbewegen");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
move(1);
|
|
||||||
Greenfoot.delay(1);
|
|
||||||
}
|
|
||||||
if(posX==getX()&&posY==getY()&&!huegelVorhanden("vorne"))
|
|
||||||
{
|
|
||||||
nachricht("Ichkannmichnichtbewegen");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
*DerRoverdrehtsichum90GradindieRichtung,diemitrichtung(ᅵlinksᅵoderᅵrechtsᅵ)ᅵbergebenwurde.
|
|
||||||
*SollteeinandererText(String)als"rechts"oder"links"ᅵbergebenwerden,dannerscheinteineentsprechendeMeldungaufdemDisplay.
|
|
||||||
*/
|
|
||||||
voiddrehe(Stringrichtung)
|
|
||||||
{
|
|
||||||
if(richtung.equals("rechts")){
|
|
||||||
setRotation(getRotation()+90);
|
|
||||||
}elseif(richtung.equals("links")){
|
|
||||||
setRotation(getRotation()-90);
|
|
||||||
}elseif(richtung.equals("um")){
|
|
||||||
setRotation(getRotation()+180);
|
|
||||||
}else{
|
|
||||||
nachricht("KeinenKorrekteRichtunggegeben!");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
*DerRovergibtdurcheinenWahrheitswert(trueoderfalse)zurᅵck,obsichaufseinerPositioneinObjektderKlasseGesteinbefindet.
|
|
||||||
*EineentsprechendeMeldungerscheintauchaufdemDisplay.
|
|
||||||
*/
|
|
||||||
booleangesteinVorhanden()
|
|
||||||
{
|
|
||||||
if(getOneIntersectingObject(Gestein.class)!=null)
|
|
||||||
{
|
|
||||||
nachricht("Gesteingefunden!");
|
|
||||||
returntrue;
|
|
||||||
}
|
|
||||||
returnfalse;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
*DerRoverᅵberprᅵft,obsichinrichtung("rechts","links",oder"vorne")einObjektderKlasseHuegelbefindet.
|
|
||||||
*DasErgebniswirdaufdemDisplayangezeigt.
|
|
||||||
*SollteeinandererText(String)als"rechts","links"oder"vorne"ᅵbergebenwerden,dannerscheinteineentsprechendeMeldungaufdemDisplay.
|
|
||||||
*/
|
|
||||||
booleanhuegelVorhanden(Stringrichtung)
|
|
||||||
{
|
|
||||||
introt=getRotation();
|
|
||||||
if(richtung=="vorne"&&rot==0||richtung=="rechts"&&rot==270||richtung=="links"&&rot==90)
|
|
||||||
{
|
|
||||||
if(getOneObjectAtOffset(1,0,Huegel.class)!=null&&((Huegel)getOneObjectAtOffset(1,0,Huegel.class)).getSteigung()>30)
|
|
||||||
{
|
|
||||||
returntrue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if(richtung=="vorne"&&rot==180||richtung=="rechts"&&rot==90||richtung=="links"&&rot==270)
|
|
||||||
{
|
|
||||||
if(getOneObjectAtOffset(-1,0,Huegel.class)!=null&&((Huegel)getOneObjectAtOffset(-1,0,Huegel.class)).getSteigung()>30)
|
|
||||||
{
|
|
||||||
returntrue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if(richtung=="vorne"&&rot==90||richtung=="rechts"&&rot==0||richtung=="links"&&rot==180)
|
|
||||||
{
|
|
||||||
if(getOneObjectAtOffset(0,1,Huegel.class)!=null&&((Huegel)getOneObjectAtOffset(0,1,Huegel.class)).getSteigung()>30)
|
|
||||||
{
|
|
||||||
returntrue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if(richtung=="vorne"&&rot==270||richtung=="rechts"&&rot==180||richtung=="links"&&rot==0)
|
|
||||||
{
|
|
||||||
if(getOneObjectAtOffset(0,-1,Huegel.class)!=null&&((Huegel)getOneObjectAtOffset(0,-1,Huegel.class)).getSteigung()>30)
|
|
||||||
{
|
|
||||||
returntrue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if(richtung!="vorne"&&richtung!="links"&&richtung!="rechts")
|
|
||||||
{
|
|
||||||
nachricht("Befehlnichtkorrekt!");
|
|
||||||
}
|
|
||||||
returnfalse;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
*DerRoverermitteltdenWassergehaltdesGesteinsaufseinerPositionundgibtdiesenaufdemDisplayaus.
|
|
||||||
*SolltekeinObjektderKlasseGesteinvorhandensein,dannerscheinteineentsprechendeMeldungaufdemDisplay.
|
|
||||||
*/
|
|
||||||
voidanalysiereGestein()
|
|
||||||
{
|
|
||||||
if(gesteinVorhanden())
|
|
||||||
{
|
|
||||||
nachricht("Gesteinuntersucht!Wassergehaltist"+((Gestein)getOneIntersectingObject(Gestein.class)).getWassergehalt()+"%.");
|
|
||||||
Greenfoot.delay(1);
|
|
||||||
removeTouching(Gestein.class);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
nachricht("HieristkeinGestein");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
*DerRovererzeugteinObjektderKlasseᅵMarkierungᅵaufseinerPosition.
|
|
||||||
*/
|
|
||||||
voidsetzeMarke()
|
|
||||||
{
|
|
||||||
getWorld().addObject(newMarke(),getX(),getY());
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
**DerRovergibtdurcheinenWahrheitswert(trueoderfalse)zurᅵck,obsichaufseinerPositioneinObjektderMarkebefindet.
|
|
||||||
*EineentsprechendeMeldungerscheintauchaufdemDisplay.
|
|
||||||
*/
|
|
||||||
booleanmarkeVorhanden()
|
|
||||||
{
|
|
||||||
if(getOneIntersectingObject(Marke.class)!=null)
|
|
||||||
{
|
|
||||||
returntrue;
|
|
||||||
}
|
|
||||||
returnfalse;
|
|
||||||
}
|
|
||||||
voidentferneMarke()
|
|
||||||
{
|
|
||||||
if(markeVorhanden())
|
|
||||||
{
|
|
||||||
removeTouching(Marke.class);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
voidnachricht(StringpText)
|
|
||||||
{
|
|
||||||
if(anzeige!=null)
|
|
||||||
{
|
|
||||||
anzeige.anzeigen(pText);
|
|
||||||
Greenfoot.delay(1);
|
|
||||||
anzeige.loeschen();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
voiddisplayAusschalten()
|
|
||||||
{
|
|
||||||
getWorld().removeObject(anzeige);
|
|
||||||
}
|
|
||||||
voidaddedToWorld(Worldworld)
|
|
||||||
{
|
|
||||||
setImage("images/rover.png");
|
|
||||||
world=getWorld();
|
|
||||||
anzeige=newDisplay();
|
|
||||||
anzeige.setImage("images/nachricht.png");
|
|
||||||
world.addObject(anzeige,7,0);
|
|
||||||
if(getY()==0)
|
|
||||||
{
|
|
||||||
setLocation(getX(),1);
|
|
||||||
}
|
|
||||||
anzeige.anzeigen("Ichbinbereit");
|
|
||||||
}
|
|
||||||
classDisplayextendsActor
|
|
||||||
{
|
|
||||||
GreenfootImagebild;
|
|
||||||
Display()
|
|
||||||
{
|
|
||||||
bild=getImage();
|
|
||||||
}
|
|
||||||
voidact()
|
|
||||||
{
|
|
||||||
}
|
|
||||||
voidanzeigen(StringpText)
|
|
||||||
{
|
|
||||||
loeschen();
|
|
||||||
getImage().drawImage(newGreenfootImage(pText,25,Color.BLACK,newColor(0,0,0,0)),10,10);
|
|
||||||
}
|
|
||||||
voidloeschen()
|
|
||||||
{
|
|
||||||
getImage().clear();
|
|
||||||
setImage("images/nachricht.png");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
classDirection{
|
|
||||||
Direction(intval){
|
|
||||||
this.value=val;
|
|
||||||
}
|
|
||||||
intvalue;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user