Code edit (1 edits merged)
Please save this source code
User prompt
implement setDebugValues() by re-setting stockValuesHistory values by repeating 10 times the serie 50, 75 , 100, 125, 150 , 125, 100, 75 , 50
Code edit (1 edits merged)
Please save this source code
Code edit (19 edits merged)
Please save this source code
User prompt
periodically update vsaText
User prompt
Fix Bug: 'Uncaught TypeError: Cannot read properties of undefined (reading 'toFixed')' in or related to this line: 'var vsaText = new Text2('VSA: ' + verticalSlideAmount.toFixed(0), {' Line Number: 164
User prompt
add a text at the top left corner with the verticalSlideAmount without decimals labeled VSA
Code edit (1 edits merged)
Please save this source code
Code edit (1 edits merged)
Please save this source code
User prompt
in axis vertical movement and console log should be treated only for horizontal axis
User prompt
add a propery in Axis to differenciate horizontal and vertical
User prompt
remove the decimals in the log in axis updateSlide
User prompt
in horizontal Axis updateSlide, console log current stock value, and self.y
User prompt
Fix Bug: 'ReferenceError: upperLimit is not defined' in or related to this line: 'if (self.y <= upperLimit || self.y >= lowerLimit) {' Line Number: 28
User prompt
in the horizontalAxis'updateSlide function, add the requested condition to set moveSegmentsVertically to false
Code edit (1 edits merged)
Please save this source code
User prompt
the vertical movement speed is far too high
User prompt
the vertical sliding speed is far too high
User prompt
Fix : When moveSegmentsVertically some segments have negative values
User prompt
speed up the graph drawing as before
User prompt
restore previous speed
User prompt
$50 should map to `game.height / 2`, the Y coordinate 2049 does not align with this mapping. The expected Y coordinate for $50 should be half of the game's height, not 2049. Fix
Code edit (1 edits merged)
Please save this source code
User prompt
slow down the graph drawing for debugging
User prompt
fix bug : Y values are going negative !
/****
* Classes
****/
var GraphSegment = Container.expand(function () {
var self = Container.call(this);
self.yValue = 0; // Track the Y value of the segment
self.updateSlide = function () {
if (moveSegments) {
self.x -= slideAmount;
}
if (moveSegmentsVertically) {
self.y += verticalSlideAmount;
}
};
var segmentGraphics = self.attachAsset('segment', {
anchorY: 0.5
});
// Function to slide the segment to the left
});
// Axis class to represent the graph axes
var Axis = Container.expand(function () {
var self = Container.call(this);
self.yValue = 0; // Track the Y value of the axis for vertical movement
self.updateSlide = function () {
if (moveSegmentsVertically) {
self.y += verticalSlideAmount;
}
};
self.drawAxis = function () {
var axisGraphics = self.addChild(LK.getAsset('axis', {
height: 4 // Thin line for the axis
}));
};
});
// ValueIndicator class to represent the current value of the stock on the graph
// Player class to represent the player's portfolio
var Player = Container.expand(function () {
var self = Container.call(this);
self.balance = 100; // Start with $100
self.stocks = {}; // Object to hold stocks and quantities
self.buyStock = function (stock, quantity) {
var cost = stock.getPrice() * quantity;
if (self.balance >= cost) {
self.balance -= cost;
if (!self.stocks[stock]) {
self.stocks[stock] = 0;
}
self.stocks[stock] += quantity;
}
};
self.sellStock = function (stock, quantity) {
if (self.stocks[stock] && self.stocks[stock] >= quantity) {
self.balance += stock.getPrice() * quantity;
self.stocks[stock] -= quantity;
if (self.stocks[stock] === 0) {
delete self.stocks[stock];
}
}
};
self.getBalance = function () {
return self.balance;
};
self.getPortfolio = function () {
return self.stocks;
};
});
/****
* Initialize Game
****/
var game = new LK.Game({
// No need to set backgroundColor since we are adding a background asset
});
/****
* Game Code
****/
var slideAmount = 5.0;
var slideAmountVertical = 5.0;
var moveSegmentsVertically = false;
var verticalSlideThreshold = 500; // Define a global threshold for vertical sliding
// Create and add background asset
var running = false;
var moveSegments = false;
var drawingInProgress = false;
var background = game.addChild(LK.getAsset('background', {
anchorX: 0.5,
anchorY: 0.5
}));
background.x = 1024; // Center x position
background.y = 2732 - background.height / 2; // Center y position
// Initialize game elements
var player = new Player();
var stocks = [];
// Initialize stock values history with the first value of $10
var stockValuesHistory = [50];
// Define graphIndex and initialize to 0
var graphIndex = 0;
// Declare a global array to store graph segments
var graphSegments = [];
// Generate random deltas and add to previous value for stockValuesHistory
var previousValue = stockValuesHistory[stockValuesHistory.length - 1];
for (var i = 0; i < 100; i++) {
var delta = (Math.random() - 0.5) * 100; // Generate a delta between -50 and 50
var newValue = Math.max(0, previousValue + delta);
stockValuesHistory.push(newValue);
previousValue = newValue;
}
// Create and draw horizontal axis
var horizontalAxis = game.addChild(new Axis());
horizontalAxis.yValue = game.height * 0.75; // Initialize yValue for vertical movement
horizontalAxis.drawAxis();
horizontalAxis.y = horizontalAxis.yValue;
horizontalAxis.width = game.width;
horizontalAxis.height = 6;
horizontalAxis.x = 0; // Move axis to the left side of the screen
// Create and draw vertical axis
var verticalAxis = game.addChild(new Axis());
verticalAxis.drawAxis();
verticalAxis.rotation = Math.PI / 2; // Rotate to make it vertical
verticalAxis.x = 20; // Move axis to the left side of the screen
verticalAxis.width = game.height;
verticalAxis.y = 0;
var graphPoints = [];
var graphWidth = game.width;
var segmentWidth = graphWidth / 6; //; / stockValuesHistory.length;
var x, y;
// Compute the coordinates for the graph based on stockValuesHistory
var dollarToYPixelRatio = game.height * 0.5 / 100;
for (var i = 0; i < stockValuesHistory.length; i++) {
x = Math.min(segmentWidth * i, game.width * 0.75);
y = Math.max(game.height * 0.75, game.height * 0.5 - (stockValuesHistory[i] - 50) * (game.height * 0.5 / 100)); // Calculate Y based on new mapping
graphPoints.push({
x: x,
y: y
});
}
var segmentDrawInterval = null;
var stockDisplay = []; // Array to hold stock display elements
var balanceText = new Text2('Balance: $' + player.getBalance(), {
size: 50,
fill: "#ffffff"
});
var stockValueText = new Text2('Stock Value: $' + stockValuesHistory[stockValuesHistory.length - 1].toFixed(2), {
size: 50,
fill: "#ffffff"
});
stockValueText.anchor.set(1, 0);
LK.gui.topRight.addChild(stockValueText);
function updateStockValueText() {
stockValueText.setText('Stock Value: $' + stockValuesHistory[graphIndex].toFixed(0));
}
balanceText.anchor.set(0.5, 0);
LK.gui.top.addChild(balanceText);
// Update the player's balance display
function updateBalanceDisplay() {
balanceText.setText('Balance: $' + player.getBalance().toFixed(2));
}
// Function to handle buying stocks
function buyStock(stock) {
player.buyStock(stock, 1); // Buy 1 stock for simplicity
updateBalanceDisplay();
}
// Function to handle selling stocks
function sellStock(stock) {
player.sellStock(stock, 1); // Sell 1 stock for simplicity
updateBalanceDisplay();
}
function drawNextSegment() {
console.log("drawNextSegment " + graphIndex + ' isDrawing = ' + drawingInProgress);
var hasFinished = graphIndex >= graphPoints.length - 1;
if (hasFinished) {
running = false;
LK.showGameOver();
return;
}
if (!drawingInProgress) {
var pointA = graphPoints[graphIndex];
var lastSegment = graphSegments.length > 0 ? graphSegments[graphSegments.length - 1] : null;
var lastSegmentEndX = lastSegment ? lastSegment.x + Math.cos(lastSegment.rotation) * lastSegment.width : 0;
var lastSegmentEndY = lastSegment ? lastSegment.y + Math.sin(lastSegment.rotation) * lastSegment.width : 0;
pointA.x = lastSegment ? lastSegmentEndX : 0;
pointA.y = graphPoints[graphIndex].y;
var pointB = graphPoints[graphIndex + 1];
var upperLimit = game.height * 0.25;
var lowerLimit = game.height * 0.75;
if (pointB.y < upperLimit) {
verticalSlideAmount = upperLimit - pointB.y;
moveSegmentsVertically = true;
console.log("Sliding up to adjust graph!");
} else if (pointB.y > lowerLimit && stockValuesHistory[graphIndex + 1] !== 0) {
verticalSlideAmount = lowerLimit - pointB.y;
moveSegmentsVertically = true;
console.log("Sliding down to adjust graph!");
}
var delay = 1; // Reduce delay if segments are moving
drawingInProgress = true;
drawSegment(game, graphIndex, pointA.x, pointA.y, pointB.x, pointB.y, delay);
graphIndex++;
updateStockValueText();
}
}
function drawSegment(gameRef, index, x1, y1, x2, y2, delay) {
var segment = gameRef.addChild(new GraphSegment());
segment.yValue = y1; // Set the yValue to the starting Y of the segment
// Adjust segment's y position if vertical movement is enabled
if (moveSegmentsVertically) {
segment.y += moveSegmentsVertically && y1 < verticalSlideThreshold ? slideAmountVertical : 0;
}
// Add the new segment to the global graphSegments array
graphSegments.push(segment);
console.log('new segment index=' + index + '/' + (graphSegments.length - 1), Math.floor(x1), Math.floor(y1), Math.floor(x2), Math.floor(y2));
segment.x = x1;
segment.y = y1;
segment.width = 1;
segment.height = 20;
var deltaX = x2 - x1;
var deltaY = y2 - y1;
if (deltaX === 0 && deltaY === 0) {
console.error('Invalid deltaX and deltaY for rotation calculation.');
return;
}
var distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
segment.rotation = Math.atan2(deltaY, deltaX);
/*console.log('segment.rotation ' + (graphSegments.length - 1), {
deltaY: deltaY,
deltaX: deltaX
}, segment.rotation);*/
var startTime = Date.now();
var endTime = startTime + delay * 1000;
var updateWidth = function updateWidth() {
if (!running) {
return;
}
var currentTime = Date.now();
var timeElapsed = currentTime - startTime;
var newWidth = Math.min(timeElapsed / (delay * 1000) * distance, distance);
segment.width = newWidth;
if (currentTime < endTime) {
LK.setTimeout(updateWidth, 16);
} else {
if (!moveSegments && segment.x + segment.width / 2 >= game.width * 0.5) {
moveSegments = true;
console.log("Past center !");
}
drawingInProgress = false;
}
};
updateWidth();
}
function startGame() {
// Initialize and start the game logic here
running = true;
// Set up a tick event to call drawNextSegment every second
segmentDrawInterval = LK.setInterval(drawNextSegment, 100);
}
// Main game loop
LK.on('tick', function () {
if (!running) {
return;
}
// Update slide for each graph segment and the horizontal axis
graphSegments.forEach(function (segment) {
segment.updateSlide();
});
horizontalAxis.updateSlide(); // Slide the horizontal axis vertically
// Check for game over conditions (e.g., player runs out of money)
if (player.getBalance() <= 0) {
LK.effects.flashScreen(0xff0000, 1000);
LK.showGameOver();
}
});
LK.setTimeout(function () {
startGame();
}, 1000);
A Technical dark background. Nothing just a gradiant of colors from black to dark blue. Theme : stock market. background
A modern clean empty rectangular button without borders. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
without shadow
a basic empty ui popup with a black background. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.