I'm very new to JavaScript programming and would appreciate any sort of help on this.
I'm trying to program a task that is separated into 4 games. Each of the games has the same structure- a stimulus (different image in each game) appears on the screen, then you have 2 choices- either 1) press “enter” to keep playing to see the “result” image (different image in each game) or 2) press “space bar” stop playing and accumulate the points earned up to that point. If you decide to keep playing, the “result” image will show up which will show you whether you win or lose one point. You start the game with 50 points and over 100 trials, the percentage of “win”s per 10 trials drops from 90% to 0%.
What is the best way to set up these trials and collect this type of data? Currently, I have made an array of 100 responses corresponding to the 100 trials:
correctresponse = [“spacebar_code”, “enter_code”, “enter_code”, “enter_code” ….]
Similarly, I’ve made an array of 100 outcome responses:
outcome = [“image1.jpg”, “image2.jpg”…]
I’m also unsure as to setting up some key functions. My function to capture keypresses right now is:
function getKeyTest(keyStroke) {
isNetscape=(document.layers);
keyID = (window.event) ? event.keyCode : keyStroke.keyCode;
eventChooser = (isNetscape) ? keyStroke.which : keyID;
which = String.fromCharCode(eventChooser);
for (i=0;i<response_keys.length;i++) {
if (which == response_keys[i]) {
rtEndTime = new Date();
var currentRT = rtEndTime - rtStartTime;
trialRTs.push(currentRT);
if (currentRT < 500)
rtUnder500++;
} else if (currentRT > 10000) {
rtOver10000++;
}
if (response_keys[i] == correctResponses[trialNumber]) {
accuracy[trialNumber] = 1;
correctTotal = correctTotal + 1;
} else {
accuracy[trialNumber] = 0;
}
trial_outcome();
}
if (which == spacebar_code && trialTypes[trialNumber] == "test") { //this does not seem to end the trial
save_data(); }
}
}
Another question I have is:
There are 4 different conditions that have to be randomized across the 4 games.
cue, delay;
cue, no delay;
no cue, delay;
no cue, no delay.
Where
Cue = there’s a tally of points shown above the stimuli
Delay = there is a 5-second delay between the outcome of each trial and the next chance for the person to respond
I’m not quite sure what the best way to randomize the 4 conditions across the 4 games would be. I think I need to create an array and do a shuffle function, but how would I define the elements in that array to contain the two different aspects (cue and delay)?
Related
https://www.hackerrank.com/challenges/game-of-stones-1/problem
**Game of Stones
**
Two players (numbered 1 and 2) are playing a game with stones. Player 1 always plays first, and the two
players move in alternating turns. The game's rules are as follows:
In a single move, a player can remove either **2,3 ,5 **or stones from the game board.
If a player is unable to make a move, that player loses the game.
Given the number of stones, find and print the name of the winner (i.e., First or Second ) on a new line.
Each player plays optimally, meaning they will not make a move that causes them to lose the game if some
better, winning move exists.
**Input Format
**
The first line contains an integer, , denoting the number of test cases.
Each of the subsequent lines contains a single integer, , denoting the number of stones in a test case.
Constraints
1 <= T <= 100
1 <= n <= 100
**Output Format
**
On a new line for each test case, print First if the first player is the winner; otherwise, print Second .
this code is working on IDE
`function gameOfStones(n) {
// Write your code here
let inputValues = n.toString().split('');
let player1 = new Set();
let player2 = new Set();
let output = []
player1.add(0);
player1.add(1);
for(let i = 2; i <=parseInt(inputValues[0]) ; i++){
if(player1.has(i-2) || player1.has(i-3) || player1.has(i-5)){
player2.add(i)
} else player1.add(i)
}
for(let i = 1; i < inputValues.length; i++){
if(player1.has(parseInt(inputValues[i]))){
output.push('Second')
} else output.push('First')
}
return output.join('\n')
}`
hackerrank ide gives a blank space instead of first or second
so I have 2 numbers that gets randomly generated from 1 to 13 but if a number is above 10 it gets treated as 10 similar to the blackjack game
function getRandomNumber2() {
let random = Math.floor(Math.random() * 12 + 1);
if (random > 10) {
return 10;
} else {
return random;
}
}
then i attached these numbers to variables then I put them in a list and I summed them
secondCard = getRandomNumber2()
cardsList = [firstCard, secondCard];
sumGAME = firstCard + secondCard;
now I want these numbers to show in the website as images but I can still sum them and all, let's say I got number 2 then the image attached to number 2 gets displayed and if i ask for new set of numbers then the images gets deleted and gets replaced with the new pic
what I tried to do
I tried to identify each one of the 13 images as an individual variable and put if statement that looks like this
if(cardsList[0]===1)
{cards.appendChild(card1)}
and kept going for all the cards
the issue
if I ask for new set of cards it doesn't delete the old images but adds 2 more to it
I want an item to appear every now and then. Usually one item appear that give +10 score but i want a rare item to appear at a random chance that give more points.
Ive already tried something that looks like this except repurposed for what i need
if (Math.random() * 100 < 80) {
sendMessage("hi");
}
else if (Math.random() * 100 < 5) {
sendMessage("bye");
}
I expected for a gold thing to appear but it never did
You should probably first determine what you want the probabilities of these events to be and how frequently you want them to occur.
Presumably you'd have some short time interval between these events, say for example 60 seconds. And then the chance of a rare one could be 5%. So your example at the moment seems to be a bit off because of your else statement.
const rand => Math.rand() * 100;
if(rand() <= 80){
// 80% of any reward appearing
if(rand() <= 5){
// Give the super reward, 5% chance
} else {
// Give the regular reward
}
}
Hope that makes sense.
basically you need to calculate once the random probability and then assign the reward based on your logic.
const normalProbability = 80;
const epicProbability = 5;
const obtainReward = () => {
const calculated = Math.random() * 100;
if (calculated <= normalProbability && calculated > epicProbability) {
console.log(`normal probability to appear a common object... you got ${calculated}%`)
return calculated;
} else if (calculated <= epicProbability) {
console.log(`epic probability to appear a common object, you got ${calculated}%`);
return calculated;
}
console.log(`no reward because you got... ${calculated}%`);
return calculated;
}
console.log("starting the automatic process")
setInterval(() => obtainReward(), 3000);
I found a nice simple bit of code to show a count up and I can easily vary the steps each count up makes. So this one counts up in 10's so 10, 20, 30, 40, 50, etc. appears on the page.
Code text is as follows
<script type="text/javascript">
var counter = 0
var timer; { counter = counter + 10;//increment the counter by 10
//display the new value in the div
document.getElementById("timer_container").innerHTML = counter;
}
</script>
</head>
<body onload='timer=setInterval("countUP()", 1000 );'>
<div id="timer_container"<0>/div>
</body>
</html>
What beats me however is how to include the counter multiple times on a single page with each counter using a different counting amount. I'd like to be able to include a lot of counters in a table on a page with each one going up in different amounts 1, 2, 3, 4 etc.
What this is for is to help my teacher wife with times tables on a big whiteboard so there would be 12 different colored areas on display featuring each times table from 1 to 12
Each colored box displayed will include:
image - mysite.com/3timestableicon.png
text - "3x Table"
counter code - going up in increments of 3 and stopping after 20 steps
text- "See - Each step is in 3's!"
I can probably figure out the table and all the different cells to make all this display correctly but I'm stuck getting more than one counter to appear on a single page at the moment so would appreciate any help on this bit.
The problem you have is that var counter = 0 is a global variable. So if you copy n paste the script multiple times, you're sharing the same variable.
I'm not sure how much programming experience you have, but the best way to do this would be to have a counting function. Your code snippet looks like you incorrectly pasted it, but you need to have a function, say count that increments a counter and wraps it when it gets to 12 (or however high you want to go) before looping around. Remove the if statement if you don't want it to loop.
var k = 0;
function count() {
if (k == 12) k = 0;
else k = k + 1;
// update your divs now with the new value of k
}
Then you can execute that with the interval function to count every x number of millis.
<body onload='timer=setInterval("count()", 1000 );'>
Then have an update function which updates the div's with the new values. And this function would apply a multiplier to the current counter (k) value.
function updateDisplay(id, multiplier) {
document.getElementById(id).innerHTML = k * multiplier;
}
Then you can wrap all that together for the times table of 1 to 12 by using this code in the count function to update all the div containers.
for (var n = 1; n <= 12; n++) {
updateDisplay("timer_container_" + n, n);
}
In your HTML you'd just add in 12 divs, each one with the id, "timer_container_1" etc.
I'll leave it as an exercise to the reader to put these functions together and the required divs into a HTML file.
I have a canvas game which calls a function incScore every time an action is performed in the game to increase the score.
Inside incScore I have a few if statements to draw a particular image to represent a level number on the canvas.
I also want to have a sound play once per level up. The way I've gone about things the lvlup sound will play every time the score matches the if statement.
Can anyone please help me get this so that the sound will only play once when the level changes and not again until the next level change? I'm also mention I'm using jQuery incase it has anything that could help me.
incScore(); //everytime an action in the game causes the score to increase
function incScore(){
if (scoreTotal < 500){
lvlimg = "L01";
drawLevel(lvlimg);
lvlupSound();
}
else if (scoreTotal > 500 && scoreTotal < 1000){
lvlimg = "L02";
drawLevel(lvlimg);
lvlupSound();
}
else{
lvlimg = "L03";
drawLevel(lvlimg);
lvlupSound();
}
}
You could shorten your function and use a semi static property to save the state. Using that, you can compare the current level to the previous and play a sound if they differ.
function incScore(){
incScore.level = incScore.level || 'L0'; //< initialize property
lvlimg = "L0" + scoreTotal < 500 ? 1 : scoreTotal < 1000 ? 2 : 3;
drawLevel(lvlimg);
if (incScore.level!=='L0' &&
incScore.level !== lvlimg) { lvlupSound(); };
// ^compare local level to current
incScore.level = lvlimg;
// ^ update local level
}
[edit, based on comment] The third line is a so called ternary, or conditional operator. See MDN. You can use more conditions.
To avoid playing a sound before the score has reached a first level, you could use
if (incScore.level!=='L0' && incScore.level !== lvlimg).
I've created a mockup jsFiddle
A simple solution could be comparing the current level to the old one, to detect when the level changed:
function scoreToLevel(score)
if(score < 500){
return 1
}else if (score < 1000){
return 2
}else{
return 3
}
}
function incScore()
var next_level = scoreToLevel(scoreTotal)
if(next_level !== current_level){
lvlimg = "L0" + next_level;
drawLevel(lvlimg)
lvlupSound()
}
}
The easiest solution is to factor the sound out of those if statements. If the levels are nice and regular like that(every 500 points) and the points always increase in a way that you will always land exactly on an even multiple of 500 when you level up, something like this should do:
if(scoreTotal % 500 === 0 && scoreTotal < 1001)
{
lvlupSound();
}
If you won't always land directly on the gate to the next level(maybe the player can earn anywhere between 1 and 15 points at a time) then you should be able to get by using something along the lines of this before you increment the player's score:
if( (scoreTotal % 500) > ((scoreTotal + increment) % 500)
{
lvlupSound();
}
if your level boundries are not regular like that obviously it gets a little bit more complex, but that should get you started.
That is because you have the in every statement for every score (which means from 0 to infinite).
You will need to write inner if statements such as;
if (scoreTotal < 500){
lvlimg = "L01";
drawLevel(lvlimg);
if(scoreTotal x times of each the level) // That means for each level completed
{
lvlupSound();
}
}
If your score increment is only 1, then only play the tone when the score equals the threshold for a new level.
If they can increase their score by more than 1, then you could pass the number of points in and check the score before and after to see if the numbers fall on each side of the threshold.
If that still doesn't work, some more info on the "level" and points would be appreciated.
Try something like this (demo):
var scoreTotal,
lastLevel = 0,
levels = [500, 1000, 2500, 5000, 10000, 25000, 50000, 75000],
currentLevel = 0,
lvlImg;
function incScore() {
while (scoreTotal > levels[currentLevel]) {
currentLevel++;
}
if (lastLevel !== currentLevel) {
lastLevel = currentLevel;
// gives a two digit number with a leading zero
lvlImg = ('0' + currentLevel).slice(-2);
drawLevel("L" + lvlimg);
lvlupSound();
}
}
Then you can easily add additional levels by adding the score cutoff to the levels variable.