Skip to content

Commit

Permalink
Merge branch 'master' into fix-frontend-background-image
Browse files Browse the repository at this point in the history
  • Loading branch information
PalumboN authored Mar 20, 2024
2 parents 6771e34 + cbdfda2 commit d4e215a
Show file tree
Hide file tree
Showing 18 changed files with 90 additions and 128 deletions.
4 changes: 4 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[*]
indent_type = space
indent_size = 2
trim_trailing_whitespace = true
4 changes: 3 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
{
"files.trimTrailingWhitespace": true
"files.trimTrailingWhitespace": true,
"typescript.preferences.quoteStyle": "single",
"typescript.format.semicolons": "remove"
}
14 changes: 7 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
"pkg": "^5.8.1",
"socket.io": "^4.5.1",
"winston": "^3.11.0",
"wollok-ts": "4.0.9"
"wollok-ts": "4.1.0"
},
"devDependencies": {
"@types/chai": "^4.3.9",
Expand Down
9 changes: 9 additions & 0 deletions public/game/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@
type="text/javascript"
src="./sketch.js"
></script>
<style>
main {
display: flex;
height: calc(100vh - 20px);
}
.p5Canvas {
margin: auto;
}
</style>
</head>

<body>
Expand Down
18 changes: 8 additions & 10 deletions public/game/sketch.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
var wko
var backgroundImage
var messageError
var widthGame = 0
var gameWidth = 0
var gameHeight = 0
const sizeFactor = 50
var cellPixelSize
var images = new Array()
Expand All @@ -13,7 +14,9 @@ function preload() {
wko = loadImage("./wko.png")
defaultBackground = loadImage("./background.jpg")
socket.on("sizeCanvasInic", (size) => {
widthGame = size[0]
gameWidth = size[0]
gameHeight = size[1]
resizeCanvas(gameWidth, gameHeight)
})
socket.on("cellPixelSize", (size) => {
cellPixelSize = size
Expand All @@ -37,10 +40,6 @@ function draw() {
checkError()
}

function windowResized() {
resizeCanvas(windowWidth - 20, windowHeight - 20)
}

function checkError() {
socket.on("errorDetected", (errorM) => {
messageError = errorM
Expand Down Expand Up @@ -86,9 +85,8 @@ function loadVisuals() {
function drawVisuals() {
if (visuals) {
for (i = 0 ; i < visuals.length ; i++) {
var positionX =
visuals[i].position.x * cellPixelSize * (windowWidth / widthGame)
var y = windowHeight - 20 - visuals[i].position.y * cellPixelSize
var positionX = visuals[i].position.x * cellPixelSize
var y = gameHeight - visuals[i].position.y * cellPixelSize
var img = images.find((img) => img.name == visuals[i].image)
var positionY = img ? y - img.url.height : y - wko.height
if (img) image(img.url, positionX, positionY)
Expand Down Expand Up @@ -172,7 +170,7 @@ function messageXPosition(message) {
}

function xPositionIsOutOfCanvas(xPosition, width) {
return xPosition + width > windowWidth
return xPosition + width > gameWidth
}

function yPositionIsOutOfCanvas(yPosition) {
Expand Down
3 changes: 1 addition & 2 deletions src/commands/extrasGame.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { RuntimeObject } from 'wollok-ts'
import { Interpreter } from 'wollok-ts/dist/interpreter/interpreter'
import { Interpreter, RuntimeObject } from 'wollok-ts'

const { round } = Math

Expand Down
9 changes: 5 additions & 4 deletions src/commands/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { existsSync, writeFileSync } from 'node:fs'
import { basename, join } from 'node:path'
import { userInfo } from 'os'
import { ENTER, createFolderIfNotExists } from '../utils'
import { PROGRAM_FILE_EXTENSION, TEST_FILE_EXTENSION, WOLLOK_FILE_EXTENSION } from 'wollok-ts'

export type Options = {
project: string,
Expand Down Expand Up @@ -31,17 +32,17 @@ export default function ({ project, name, noTest = false, noCI = false, game = f

// Creating files
const exampleName = name ?? 'example'
logger.info(`Creating definition file ${exampleName}.wlk`)
writeFileSync(join(project, `${exampleName}.wlk`), wlkDefinition)
logger.info(`Creating definition file ${exampleName}.${WOLLOK_FILE_EXTENSION}`)
writeFileSync(join(project, `${exampleName}.${WOLLOK_FILE_EXTENSION}`), wlkDefinition)

if (!noTest) {
const testFile = `test${capitalizeFirstLetter(exampleName)}.wtest`
const testFile = `test${capitalizeFirstLetter(exampleName)}.${TEST_FILE_EXTENSION}`
logger.info(`Creating test file ${testFile}`)
writeFileSync(join(project, testFile), testDefinition(exampleName))
}

if (game) {
const gameFile = `main${capitalizeFirstLetter(exampleName)}.wpgm`
const gameFile = `main${capitalizeFirstLetter(exampleName)}.${PROGRAM_FILE_EXTENSION}`
logger.info(`Creating program file ${gameFile}`)
writeFileSync(join(project, `${gameFile}`), gameDefinition(exampleName))
}
Expand Down
26 changes: 15 additions & 11 deletions src/commands/repl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,9 @@ import http from 'http'
import logger from 'loglevel'
import { CompleterResult, Interface, createInterface as Repl } from 'readline'
import { Server, Socket } from 'socket.io'
import { Entity, Environment, Evaluation, Import, Package, Reference, Sentence, WollokException, parse } from 'wollok-ts'
import { notEmpty } from 'wollok-ts/dist/extensions'
import { Interpreter } from 'wollok-ts/dist/interpreter/interpreter'
import link from 'wollok-ts/dist/linker'
import { ParseError } from 'wollok-ts/dist/parser'
import natives from 'wollok-ts/dist/wre/wre.natives'
import { Entity, Environment, Evaluation, Import, link, notEmpty, Package, Reference, Sentence, WollokException, parse, TO_STRING_METHOD, RuntimeObject, linkSentenceInNode, Interpreter, ParseError, WRENatives as natives } from 'wollok-ts'
import { getDataDiagram } from '../services/diagram-generator'
import { buildEnvironmentForProject, failureDescription, getFQN, linkSentence, publicPath, successDescription, valueDescription, validateEnvironment, handleError, ENTER, serverError, stackTrace, replIcon } from '../utils'
import { buildEnvironmentForProject, failureDescription, getFQN, publicPath, successDescription, valueDescription, validateEnvironment, handleError, ENTER, serverError, stackTrace, replIcon } from '../utils'
import { logger as fileLogger } from '../logger'
import { TimeMeasurer } from '../time-measurer'

Expand Down Expand Up @@ -194,14 +189,16 @@ function defineCommands(autoImportPath: string | undefined, options: Options, re
// EVALUATION
// ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════

// TODO WOLLOK-TS: check if we should decouple the function
export function interprete(interpreter: Interpreter, line: string): string {
try {
const sentenceOrImport = parse.Import.or(parse.Variable).or(parse.Assignment).or(parse.Expression).tryParse(line)
const error = [sentenceOrImport, ...sentenceOrImport.descendants].flatMap(_ => _.problems ?? []).find(_ => _.level === 'error')
if (error) throw error

if (sentenceOrImport.is(Sentence)) {
linkSentence(sentenceOrImport, interpreter.evaluation.environment)
const environment = interpreter.evaluation.environment
linkSentenceInNode(sentenceOrImport, replNode(environment))
const unlinkedNode = [sentenceOrImport, ...sentenceOrImport.descendants].find(_ => _.is(Reference) && !_.target)

if (unlinkedNode) {
Expand All @@ -213,9 +210,7 @@ export function interprete(interpreter: Interpreter, line: string): string {

const result = interpreter.exec(sentenceOrImport)
const stringResult = result
? typeof result.innerValue === 'string'
? `"${result.innerValue}"`
: interpreter.send('toString', result)!.innerString!
? showInnerValue(interpreter, result)
: ''
return successDescription(stringResult)
}
Expand All @@ -242,6 +237,13 @@ export function interprete(interpreter: Interpreter, line: string): string {
}
}

function showInnerValue(interpreter: Interpreter, obj: RuntimeObject) {
if (obj!.innerValue === null) return 'null'
return typeof obj.innerValue === 'string'
? `"${obj.innerValue}"`
: interpreter.send(TO_STRING_METHOD, obj)!.innerString!
}

async function autocomplete(input: string): Promise<CompleterResult> {
const completions = ['fafafa', 'fefefe', 'fofofo']
const hits = completions.filter((c) => c.startsWith(input))
Expand Down Expand Up @@ -300,6 +302,8 @@ export async function initializeClient(options: Options, repl: Interface, interp
}
}

// TODO WOLLOK-TS: migrate it? Maybe it could be part of Environment
// Environment.newImportFor(baseNode, importNode)
function newImport(importNode: Import, environment: Environment) {
const node = replNode(environment)
const imported = node.scope.resolve<Package | Entity>(importNode.entity.name)!
Expand Down
19 changes: 11 additions & 8 deletions src/commands/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ import http from 'http'
import logger from 'loglevel'
import { join, relative } from 'path'
import { Server, Socket } from 'socket.io'
import { Environment, link, Name, Package, parse, RuntimeObject, WollokException } from 'wollok-ts'
import interpret, { Interpreter } from 'wollok-ts/dist/interpreter/interpreter'
import natives from 'wollok-ts/dist/wre/wre.natives'
import { Environment, GAME_MODULE, link, Name, Package, parse, RuntimeObject, WollokException, interpret, Interpreter, WRENatives as natives } from 'wollok-ts'
import { ENTER, buildEnvironmentForProject, buildEnvironmentIcon, failureDescription, folderIcon, gameIcon, handleError, isImageFile, programIcon, publicPath, readPackageProperties, serverError, stackTrace, successDescription, validateEnvironment, valueDescription } from '../utils'
import { buildKeyPressEvent, canvasResolution, Image, queueEvent, visualState, VisualState, wKeyCode } from './extrasGame'
import { getDataDiagram } from '../services/diagram-generator'
Expand All @@ -26,7 +24,6 @@ type Options = {
startDiagram: boolean
}

// TODO: Decouple io from getInterpreter
let timer = 0

const DEFAULT_PORT = '4200'
Expand Down Expand Up @@ -116,7 +113,7 @@ export const getGameInterpreter = (environment: Environment, io: Server): Interp

const interpreter = interpret(environment, nativesAndDraw)

const gameSingleton = interpreter?.object('wollok.game.game')
const gameSingleton = interpreter?.object(GAME_MODULE)
const drawer = interpreter.object('draw.drawer')
interpreter.send('onTick', gameSingleton, interpreter.reify(17), interpreter.reify('renderizar'), drawer)

Expand Down Expand Up @@ -191,7 +188,6 @@ export const eventsFor = (io: Server, interpreter: Interpreter, dynamicDiagramCl
const sizeCanvas = canvasResolution(interpreter)
io.on('connection', socket => {
logger.info(successDescription('Running game!'))
socket.on('disconnect', () => { logger.info(successDescription('Game finished')) })
socket.on('keyPressed', key => {
queueEvent(interpreter, buildKeyPressEvent(interpreter, wKeyCode(key.key, key.keyCode)), buildKeyPressEvent(interpreter, 'ANY'))
})
Expand All @@ -210,10 +206,11 @@ export const eventsFor = (io: Server, interpreter: Interpreter, dynamicDiagramCl
socket.emit('background', background)

Check warning on line 206 in src/commands/run.ts

View check run for this annotation

Codecov / codecov/patch

src/commands/run.ts#L201-L206

Added lines #L201 - L206 were not covered by tests
})

const flushInterval = 100
const id = setInterval(() => {
try {
interpreter.send('flushEvents', gameSingleton, interpreter.reify(timer))
timer += 300
timer += flushInterval
// We could pass the interpreter but a program does not change it
dynamicDiagramClient.onReload()
if (!gameSingleton.get('running')?.innerBoolean) {
Expand All @@ -225,7 +222,13 @@ export const eventsFor = (io: Server, interpreter: Interpreter, dynamicDiagramCl
socket.emit('errorDetected', error.message)
clearInterval(id)
}
}, 100)
}, flushInterval)

socket.on('disconnect', () => {
clearInterval(id)
logger.info(successDescription('Game finished'))
})

})
}

Expand Down
15 changes: 6 additions & 9 deletions src/commands/test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import { bold } from 'chalk'
import { time, timeEnd } from 'console'
import logger from 'loglevel'
import { Entity, Environment, Node, Test } from 'wollok-ts'
import { is, match, when } from 'wollok-ts/dist/extensions'
import interpret from 'wollok-ts/dist/interpreter/interpreter'
import natives from 'wollok-ts/dist/wre/wre.natives'
import { Entity, Environment, Node, Test, is, match, when, WRENatives as natives, interpret } from 'wollok-ts'
import { buildEnvironmentForProject, failureDescription, successDescription, valueDescription, validateEnvironment, handleError, ENTER, stackTrace, buildEnvironmentIcon, testIcon } from '../utils'
import { logger as fileLogger } from '../logger'
import { TimeMeasurer } from '../time-measurer'
Expand All @@ -31,7 +28,7 @@ export function getTarget(environment: Environment, filter: string | undefined,
const fqnByOptionalParameters = [file, describe, test].filter(Boolean).join('.')
const filterTest = sanitize(filter) ?? fqnByOptionalParameters ?? ''
const possibleTargets = environment.descendants.filter(is(Test))
const onlyTarget = possibleTargets.find(test => test.isOnly)
const onlyTarget = possibleTargets.find((test: Test) => test.isOnly)
const testMatches = (filter: string) => (test: Test) => !filter || sanitize(test.fullyQualifiedName)!.includes(filter)
return onlyTarget ? [onlyTarget] : possibleTargets.filter(testMatches(filterTest))
}
Expand Down Expand Up @@ -64,8 +61,8 @@ export default async function (filter: string | undefined, options: Options): Pr
const failures: [Test, Error][] = []
let successes = 0

environment.forEach(node => match(node)(
when(Test)(node => {
environment.forEach((node: Node) => match(node)(
when(Test)((node: Test) => {
if (targets.includes(node)) {
const tabulation = tabulationForNode(node)
try {
Expand All @@ -79,14 +76,14 @@ export default async function (filter: string | undefined, options: Options): Pr
}
}),

when(Entity)(node => {
when(Entity)((node: Entity) => {
const tabulation = tabulationForNode(node)
if(targets.some(target => node.descendants.includes(target))){
logger.info(tabulation, node.name)
}
}),

when(Node)( _ => { }),
when(Node)((_: Node) => { }),
))

log()
Expand Down
1 change: 0 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import logger from 'loglevel'
import { version } from '../package.json'
import { cyan } from 'chalk'


const program = new Command()
.name('wollok')
.description('Wollok Language command line interpreter tool')
Expand Down
Loading

0 comments on commit d4e215a

Please sign in to comment.