Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Word Guessing Game using HTML CSS and JavaScript
Next article icon

Design Dragon’s World Game using HTML CSS and JavaScript

Last Updated : 12 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Project Introduction: “Dragon’s World” is a game in which one dragon tries to save itself from the other dragon by jumping over the dragon which comes in its way. The score is updated when one dragon saves himself from the other dragon. 

The project will contain HTML, CSS and JavaScript files. The HTML file adds structure to the game followed by styling using CSS. JavaScript adds functionality to the game.

File structure:

  • index.html
  • style.css
  • script.js

 

HTML Code:

  • Heading portion: It will show the name of the game.
  • Game over portion: It will be shown when you lose the game.
  • Obstacle portion: It will contain the obstacle from which the dragon has to save itself.
  • Dragon portion: It will contain the dragon which has to be saved from the obstacle i.e. the other dragon.
  • Score portion: It will show the current score of the game.

index.html 

HTML




<!DOCTYPE html>
<html>
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
  
    <link rel="stylesheet" href=
        "style.css?_cacheOverride=1606401798626">
  
    <link href=
"https://fonts.googleapis.com/css2?family=Ubuntu:ital, 
        wght@0, 300;1, 700&display=swap"
        rel="stylesheet">
</head>
  
<body>
    <h1 id="gameName">Welcome to Dragon's world</h1>
    <div class="container">
        <div class="gameover">Game Over</div>
        <div id="scorecount">Your score : 0</div>
        <div class="obstacle animateobstacle"></div>
        <div class="dragon" style="left: 426px;"></div>
    </div>
</body>
  
</html>
 
 

CSS code:

  • Positioning the game’s name: The name of the game is positioned by the absolute property of CSS.
  • Background image styling: In the container class, we have put the background image of the game with the background-size set to cover.
  • Score Card styling: We have positioned the scorecard to top right of the page and also provided it with a suitable background color to make it attractive. The text in it would be shown in white.
  • Obstacle image styling: We have positioned the obstacle to bottom left of the page and provided animation to it so that it could move towards left.
  • Dragon’s styling: We have positioned the dragon to bottom left of the page and provide animation to it so that it could jump up and save himself.
  • Game Over Styling: We have positioned the game over portion to the center of the page and it will appear when the dragon is hit by the obstacle.

style.css

/* CSS Reset */  *{      margin:0px;      padding:0px;  }  body {      /* Hides the  bottom scrollbar */      overflow: hidden;  }  /* Styling of the Game's Name */  #gameName {      position: absolute;      top:30vh;      left:38vw;  }  /* Background image styling */  .container {      background-image: url(cover.png);      background-size: cover;      width:100vw;      height:100vh;  }  /* ScoreCard Styling */  #scorecount {      position: absolute;      top:20px;      right:20px;      background-color: black;      padding: 28px;      border-radius: 20px;      color: white;  }  /* Obstacle image styling and positioning */  .obstacle {      background-image: url(obstacle.png);      background-size: cover;      width:154px;      height: 126px;      position: absolute;      bottom:0px;      right:120px;  }  /* Applying animation to the obstacle   so that it can move towards left */  .animateobstacle {      animation: aniob 5s linear infinite;  }  @keyframes aniob {      0% {          left:100vw;      }      100% {          left:-10vw;      }  }  /* Dragon's styling */  .dragon {      background-image: url(dragon.png);      background-size: cover;      width: 194px;      height: 126px;      position: absolute;      bottom:0px;      left:90px;  }  /* Applying animation to the dragon so   that it can save himself by jumping up */  .animatedragon {      animation: ani 1s linear;  }  @keyframes ani {      0% {          bottom:0px;      }      25% {          bottom:150px;      }      50% {          bottom:300px;      }      75% {          bottom:211px;      }      100% {          bottom:0px;      }  }  /* gameover styling and positioning */  .gameover {      visibility: hidden;      font-family: 'Ubuntu', sans-serif;      position: absolute;      top: 50vh;      left: 35vw;      color: red;      font-weight: bold;      font-size: 6rem;      background-color: firebrick;      border-radius: 20px;  }

JavaScript Code:

1. Movement of the dragon: This is provided by the onkeydown event.

  • Up arrow key: On pressing it, the dragon will jump upwards (animation provide by CSS).
  • Left arrow key: On pressing it, the dragon will move to the left (animation provide by CSS).
  • Right arrow key: On pressing it, the dragon will move to the left (animation provide by CSS).
document.onkeydown = function(e) {      console.log(e.keyCode);      if (e.keyCode == 38) {          dragon = document.querySelector('.dragon');          dragon.classList.add('animatedragon');          setTimeout(() => {              dragon.classList.remove('animatedragon');          }, 700);      }      if (e.keyCode == 37) {          dragon = document.querySelector('.dragon');          dragonx = parseInt(window.getComputedStyle(dragon, null)              .getPropertyValue('left'));          dragon.style.left = dragonx - 112 + "px";      }      if (e.keyCode == 39) {          dragon = document.querySelector('.dragon');          dragonx = parseInt(window.getComputedStyle(              dragon, null).getPropertyValue('left'));          dragon.style.left = dragonx + 112 + "px";      }  }

2. Updating the score: The score is satisfied only when a given condition is satisfied. We will compute the left and bottom values of both the obstacle and the dragon and then increase the score based on a proper value which shows that the dragon has saved himself from the obstacle. For this, we have taken “cross” variable and assigned “true” to it. When the dragon crosses the obstacle safely, we set the value to “false”. After approximately 1s we change the value of cross to “true”. We have also made the obstacle run faster after each cross and thus increasing the difficulty level.

setInterval(() => {      dragon = document.querySelector('.dragon');      gameover = document.querySelector('.gameover');      obstacle = document.querySelector('.obstacle');        dx = parseInt(window.getComputedStyle(          dragon, null).getPropertyValue('left'));        dy = parseInt(window.getComputedStyle(          dragon, null).getPropertyValue('bottom'));        ox = parseInt(window.getComputedStyle(          obstacle, null).getPropertyValue('left'));        oy = parseInt(window.getComputedStyle(          obstacle, null).getPropertyValue('bottom'));        offsetx = Math.abs(dx - ox);      offsety = Math.abs(dy - oy);        console.log(offsetx, offsety);        if (offsetx < 120 && offsety <= 144) {          gameover.style.visibility = 'visible';          obstacle.classList.remove('animateobstacle');      } else if (offsetx < 125 && cross) {          score += 1;          updateScore(score);          cross = false;          setTimeout(() => {              cross = true;          }, 1000);          setInterval(() => {              obsanidur = parseFloat(window                  .getComputedStyle(obstacle, null)                  .getPropertyValue('animation-duration'));                obstacle.style.animationDuration                  = obsanidur - 0.01 + 's';          }, 500);      }  }, 10);    function updateScore(score) {      scorecount.innerHTML = "Your score : " + score;  }

script.js 

javascript




<script>
    cross = true;
    score = 0;
    document.onkeydown = function(e) {
        console.log(e.keyCode);
        if (e.keyCode == 38) {
            dragon = document.querySelector('.dragon');
  
            dragon.classList.add('animatedragon');
              
            setTimeout(() => {
                dragon.classList.remove('animatedragon');
            }, 700);
        }
        if (e.keyCode == 37) {
            dragon = document.querySelector('.dragon');
  
            dragonx = parseInt(window.getComputedStyle(
                dragon, null).getPropertyValue('left'));
  
            dragon.style.left = dragonx - 112 + "px";
        }
        if (e.keyCode == 39) {
            dragon = document.querySelector('.dragon');
  
            dragonx = parseInt(window.getComputedStyle(
                dragon, null).getPropertyValue('left'));
              
            dragon.style.left = dragonx + 112 + "px";
        }
    }
    setInterval(() => {
        dragon = document.querySelector('.dragon');
        gameover = document.querySelector('.gameover');
        obstacle = document.querySelector('.obstacle');
  
        dx = parseInt(window.getComputedStyle(
            dragon, null).getPropertyValue('left'));
  
        dy = parseInt(window.getComputedStyle(
            dragon, null).getPropertyValue('bottom'));
  
        ox = parseInt(window.getComputedStyle(
            obstacle, null).getPropertyValue('left'));
  
        oy = parseInt(window.getComputedStyle(
            obstacle, null).getPropertyValue('bottom'));
  
        offsetx = Math.abs(dx - ox);
        offsety = Math.abs(dy - oy);
  
        console.log(offsetx, offsety);
  
        if (offsetx < 120 && offsety <= 144) {
            if (score != 0)
                scorecount.innerHTML = "Your score : " + score;
            gameover.style.visibility = 'visible';
            obstacle.classList.remove('animateobstacle');
        } else if (offsetx < 125 && cross) {
            score += 1;
            updateScore(score);
            cross = false;
            setTimeout(() => {
                cross = true;
            }, 1000);
            setInterval(() => {
                obsanidur = parseFloat(window
                .getComputedStyle(obstacle, null)
                .getPropertyValue('animation-duration'));
  
                obstacle.style.animationDuration
                    = obsanidur - 0.01 + 's';
            }, 500);
        }
    }, 10);
  
    function updateScore(score) {
        scorecount.innerHTML = "Your score : " + score;
    }
</script>
 
 

Reference: Dragon game

Output:

https://media.geeksforgeeks.org/wp-content/uploads/20201206163914/WhatsApp-Video-2020-12-06-at-4.36.51-PM.mp4


Next Article
Word Guessing Game using HTML CSS and JavaScript
author
shahbazalam75508
Improve
Article Tags :
  • JavaScript
  • Technical Scripter
  • Web Technologies
  • JavaScript-Projects
  • Technical Scripter 2020

Similar Reads

  • Create a snake game using HTML, CSS and JavaScript
    Snake Game is a single-player game where the snake gets bigger by eating the food and tries to save itself from the boundary of the rectangle and if the snake eats their own body the game will be over. Game Rules:If the snake goes out of the boundary or eats its own body the game will be over.Prereq
    4 min read
  • Design Dragon's World Game using HTML CSS and JavaScript
    Project Introduction: "Dragon's World" is a game in which one dragon tries to save itself from the other dragon by jumping over the dragon which comes in its way. The score is updated when one dragon saves himself from the other dragon. The project will contain HTML, CSS and JavaScript files. The HT
    6 min read
  • Word Guessing Game using HTML CSS and JavaScript
    In this article, we will see how can we implement a word-guessing game with the help of HTML, CSS, and JavaScript.  Here, we have provided a hint key & corresponding total number of gaps/spaces depending upon the length of the word and accept only a single letter as an input for each time. If it
    4 min read
  • Build a Memory Card Game Using HTML CSS and JavaScript
    A memory game is a type of game that can be used to test or check the memory of a human being. It is a very famous game. In this game, the player has some cards in front of him and all of them facing down initially. The player has to choose a pair of cards at one time and check whether the faces of
    6 min read
  • Create a Simon Game using HTML CSS & JavaScript
    In this article, we will see how to create a Simon Game using HTML, CSS, and JavaScript. In a Simon game, if the player succeeds, the series becomes progressively longer and more complex. Once the user is unable to repeat the designated order of the series at any point, the game is over. Prerequisit
    5 min read
  • Create a Minesweeper Game using HTML CSS & JavaScript
    Minesweeper is a classic puzzle game that challenges your logical thinking and deduction skills. It's a great project for developers looking to improve their front-end web development skills. In this article, we'll walk through the steps to create a Minesweeper game using HTML, CSS, and JavaScript.
    4 min read
  • Whack-a-Mole Game using HTML CSS and JavaScript
    Whack-A-Mole is a classic arcade-style game that combines speed and precision. The game is set in a grid of holes, and the objective is to "whack" or hit the moles that randomly pop up from these holes. In this article, we are going to create Whack-a-Mole using HTML, CSS and JavaScript. Preview Imag
    3 min read
  • Simple HTML CSS and JavaScript Game
    Tap-the-Geek is a simple game, in which the player has to tap the moving GeeksForGeeks logo as many times as possible to increase their score. It has three levels easy, medium, and hard. The speed of the circle will be increased from level easy to hard. I bet, it is very difficult for the players to
    4 min read
  • Design Hit the Mouse Game using HTML, CSS and Vanilla Javascript
    In this article, we are going to create a game in which a mouse comes out from the holes, and we hit the mouse with a hammer to gain points. It is designed using HTML, CSS & Vanilla JavaScript. HTML Code: First, we create an HTML file (index.html).Now, after creating the HTML file, we are going
    5 min read
  • Create a 2D Brick Breaker Game using HTML CSS and JavaScript
    In this article, we will see how to create a 2D Brick Breaker Game using HTML CSS & JavaScript. Most of you already played this game on your Mobile Phones where you control a paddle to bounce a ball, aiming to demolish a wall of bricks arranged at the top of the screen. 2D Brick Breaker Game is
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences