logo
down
shadow

Building a board game using canvas + css animations


Building a board game using canvas + css animations

Content Index :

Building a board game using canvas + css animations
Tag : javascript , By : user187301
Date : December 05 2020, 12:18 PM

it helps some times It's extremely hard to answer this question with 100% accuracy because you don't provide working example but here's how I would probably do it (if I understood your game correctly):
store tiles in array [{left: 0, top: 0}, {/* ... */}, /* ... */] store current position as variable (correlates to index of tile in tiles array) if user rolls, add roll amount to current and you have new tile position
// meta code
const tiles = [
  {left: 0, top: 0},
  {left: 10, top: 10},
  {left: 20, top: 20},
  {left: 30, top: 30},
  {left: 40, top: 40},
  {left: 50, top: 50},
  {left: 60, top: 60},
  {left: 70, top: 70},
  {left: 80, top: 80},
  {left: 90, top: 90},
  {left: 100, top: 100},
  {left: 110, top: 110},
  {left: 120, top: 120},
];

let rollHistory = [];
let currentPosition = 0; // starting positon

function rollDice() {
  return Math.floor(Math.random() * 6) + 1;
}

// show roll history
const el = document.getElementById('roll-history');

function updateHistory(roll) {
  rollHistory.push(roll);
  el.innerHTML = '';
  rollHistory.forEach((record, i) => {
    const recordDiv = document.createElement('div');
    recordDiv.innerHTML = `${(i + 1)}: ${record}`;
    el.appendChild(recordDiv);
  });
}

// draw tiles
const tilesWrapper = document.getElementById('tiles-wrapper');

tiles.forEach(tile => {
  const tileDiv = document.createElement('div');
  tileDiv.className = 'tile';
  tileDiv.style.left = tile.left + 'px';
  tileDiv.style.top = tile.top + 'px';
  tilesWrapper.appendChild(tileDiv);
});


// button and position logic
const button = document.getElementById('roll-button');
const piece = document.getElementById('piece');

button.addEventListener('click', (e) => {
  const roll = rollDice();
  updateHistory(roll);

  if (currentPosition + roll >= tiles.length) {
    // not enought tiles left, go to last
    currentPosition = tiles.length - 1;
  } else {
    currentPosition += roll;
  }
  
  piece.style.left = tiles[currentPosition].left + 'px';
  piece.style.top = tiles[currentPosition].top + 'px';
  
  // if on last, WIN!
  if (currentPosition === tiles.length - 1) {
    setTimeout(() => alert('You win!'), 1);
  }
});
#roll-button {
  position: absolute;
  right: 50%;
  top: 10px;
}

#piece {
  position: absolute;
  top: 0;
  left: 0;
  height: 10px;
  width: 10px;
  border-radius: 50%;
  background: #000;
}

.tile {
  position: absolute;
  height: 10px;
  width: 10px;
  border: 1px solid red;
}

.history {
  position: absolute;
  right: 10px;
  top: 10px;
  width: 150px;
  background: #eee;
}
<button id="roll-button">Roll</button>

<div class="history">
  History (move: roll) <br /> <br />
  <div id="roll-history"></div>
</div>

<div id="piece"></div>
<div id="tiles-wrapper"></div>

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

<canvas> Go/Baduk/Weiqi Game Board


Tag : javascript , By : Carter
Date : March 29 2020, 07:55 AM
seems to work fine Try using gridContext.globalCompositeOperation = 'destination-over'; when drawing the background.

Suitable model for a Checkers board game implemented in Canvas, with animations in mind


Tag : javascript , By : ugufugu
Date : March 29 2020, 07:55 AM
this will help I would suggest that for each from you first draw all the pieces that aren't moving, then draw the moving piece along some interpolated line from it's start to end position (given by time).
To be honest, for something with this level of graphical complexity, I would stick with HTML/CSS/jQuery, using position: absolute images to represent the pieces. Then you could use jQuery's animate function to show the last piece moving from it's start to end position really easily (and with parameters like swing or linear to get the behaviour you want). e.g.:
// Assumes pieces are objects with id and position properties
// and for each piece there is an image with id: piece.id

$('#'+piece.id).animate({
    left:  piece.position.x * board_scale,
    top:   piece.position.y * board_scale
});

UIView animations in board game


Tag : iphone , By : Ansari
Date : March 29 2020, 07:55 AM
This might help you Use a CAKeyframeAnimation on the view's layer, instead of using +[UIView animateWithDuration:...].
First, you may need to add the QuartzCore framework to your target. If you don't know how to do that, read How to "add existing frameworks" in Xcode 4? Also add #import to your app's .pch header file.
CGPoint position = self.playerOneImage.layer.position;
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:position];
position.x += 50; [path addLineToPoint:position];
position.y += 100; [path addLineToPoint:position];
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animation.duration = 1.0f;
animation.path = path.CGPath;
animation.calculationMode = kCAAnimationPaced;
// Important: you must actually set the layer's position!
// Otherwise the animation will put it back at the start
// when the animation ends.  You should set the layer's
// final position, then add the animation.
self.playerOneImage.layer.position = position;
[self.playerOneImage.layer addAnimation:animation forKey:@"position"];
CGPoint position = self.playerOneImage.layer.position;
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:position];
position.x += 50; [path addLineToPoint:position];
position.y += 100; [path addLineToPoint:position];
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animation.duration = 1.0f;
animation.path = path.CGPath;
animation.calculationMode = kCAAnimationPaced;
// Important: you must actually set the layer's position!
// Otherwise the animation will put it back at the start
// when the animation ends.  You should set the layer's
// final position, then add the animation.
self.playerOneImage.layer.position = position;
[self.playerOneImage.layer addAnimation:animation forKey:@"position"];

Multiple Canvas Board Game vs. Single Canvas


Tag : javascript , By : mobi phil
Date : March 29 2020, 07:55 AM
This might help you The most important thing is to find a balance and understand why you would use one canvas versus layered canvases.
For a tic-tac-toe game only one is needed as there is nothing there that needs constantly updates. If would be easier to maintain as well. Event-driven (ie. nothing happens until you click/do something) games/apps such as this would typically not benefit from several layers.

New to Reactjs, Building a Game of Life, but the old board is updating with the new board


Tag : javascript , By : Schmidt
Date : March 29 2020, 07:55 AM
hop of those help? In gameStep, you are changing this.state.board itself. I'd recommend using immutable structures, e.g. immutable.js. However, since you are only beginning, you can try cloning the state into newState using Object.assign -
var newBoard = Object.assign({}, this.state.board);
Related Posts Related QUESTIONS :
  • XPath select on child nodes
  • Idle event on mouse move - how to stop script permanently on mouse move
  • Why do I get logic is not defined in this code
  • When I enter a number in the input, the first function starts
  • ES6 imports and node_modules hell
  • How to get css selector of clicked-on element?
  • How to auto input MySQL data (input column 1 data to auto input column 2 data with same column) in php?
  • Appending to Datalist Via Javascript
  • Customizing Material-UI Components with Styled-Components
  • Populate elements with class name using Javascript
  • How to execute promises in batches (first resolving 10, then next 10 and so on)
  • Maximo JS automation script: "importPackage" is not defined
  • How to surround selected text inside textarea with <em> on key combination CTRL+i?
  • Your configured registry does not support audit requests ~ On npm audit
  • What's the Angular equivalent of Vue <slot/>?
  • Iconify icon not updating when "data-icon" set with setAttribute()
  • Javascript newbie stuck with XMLHttpRequest return data
  • How to add obj to to state in my example Redux React
  • Loading "grunt-karma.js" tasks...ERROR >> SyntaxError: Unexpected identifier
  • Why do I get log is not defined
  • get the multiple index of the same string
  • How can I iterate over an Array object by using For IN or FOR OF
  • Launch local executable from web browser
  • How to prepare array of json objects to d3 hierarchical tree structure
  • VueJS - event emitted - show HTML before other calculations
  • Export SASS/SCSS variables to Javascript without exporting them to CSS
  • How to attach an event handler only once continuously
  • How to make button open a link in new tab in JavaScript?
  • Find range from the javascript object
  • How can I use my jQuery code as JavaScript?
  • How to show 5 images in a 2 row slider with bxslider
  • How to convert stream into variables in typescript
  • Three.js custom shader error on Chrome GL_INVALID_OPERATION: Active draw buffers with missing fragment shader outputs
  • My JavaScript doesn't work. How can I solve this problem?
  • Why is this async function is running synchronously?
  • Get updated variable from within react hook before return
  • I want to show all image preview but whenever I upload a new one the old one is gone
  • Would I be able to give access to specific electron APIs safely?
  • Why several clicks fire for each instance of a Class?
  • cant grab value from div using attr()
  • Make web service not accessible by browser?
  • Select DOM elements within template
  • How to customize angular ui-grid row background color?
  • Binding data in two respective $scope in AngularJS, how?
  • react put some props after import class
  • Variable is distributed among same components
  • switch class in jQuery/JavaScript for active/inactive state
  • How To Track Outbound Clicks Using Javascript
  • How to get total seconds elapsed since the beginning of the month?
  • Protractor: Stale element reference at "browser.wait(EC.visibilityOf(confDial), FIFTY_SECONDS);"
  • Access to an array inside an object
  • Reseting an JavaScript Interval with different value?
  • Learning Angular for the first time - version 2 or 4?
  • Rendering RSS feed (XML) in React with jquery, why do object values parsed from the feed seem empty?
  • Node.js xml2js http.request tag matching
  • applying texture to custom plane geometry in Threejs
  • How do I pass an Event as a function parameter in HTML written inside JavaScript variable?
  • Interface of object parameter with default value and default property
  • Does using try / catch rather than `.catch` observable operator with XHR requests reduce performance?
  • In IE11 background colors not working on printing
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com