Vladislav Smirnov
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Snake Game AI -- Your First Bot Snakes AI has got a very simple interface for bot creation. The minimum you need to implement in order to make a functioning bot is a class, that implements the Bot interface. ## Set up the workspace ### Requirements * [JDK 8](https://www.oracle.com/java/technologies/javase/javase-jdk8-downloads.html) * [IntelliJ Idea](https://www.jetbrains.com/idea/) (optional, recommended) ### Clone the repository Clone the repo using Git: ``` // ssh git clone git@github.com:BeLuckyDaf/snakes-game-tutorial.git // https (you don't know why the one above doesn't work) git clone https://github.com/BeLuckyDaf/snakes-game-tutorial.git ``` or simply download the [zip file](https://github.com/BeLuckyDaf/snakes-game-tutorial/archive/master.zip). ### Open the project Open *snakes.ipr* in IntelliJ Idea or any other IDE. 1. Set up JDK a. Open Project Structure ![](https://i.imgur.com/3HclqiQ.png "Project Structure" =400x) b. Choose the correct version ![](https://i.imgur.com/rLaCxCH.png "JDK" =400x) 2. Set up a configuration a. Open the configuration settings ![](https://i.imgur.com/epnjA1K.png "Edit Configurations" =400x) b. Set correct JRE version for Main ![](https://i.imgur.com/gRuwuuF.png "JRE" =400x) c. Add or change your bot name. *(return here after you've finished the tutorial)* ![](https://i.imgur.com/itzElFW.png "Bot names" =400x) ### Launch the game The sample bot is already set up in the project, simply compile and launch the game by pressing Shift+F10 or `Run > Run 'Main'` in the menu. ![](https://i.imgur.com/gYTVIqa.png "Run" =400x) ## Example bot ### Create a package First, let's create a new package for you. Name it however you want, for the sake of this tutorial, we'll call it *student*. ### Create a class Our bot class must implement the Bot interface, otherwise, we won't be able to tell the game what it does. ```java package student public class MyBot implements Bot { } ``` That also means, that we must implement the following method, specified in the interface. ```java public Direction chooseDirection(Snake snake, Snake opponent, Coordinate mazeSize, Coordinate apple) ``` In fact, this is the only method that we are required to implement in order to make our bot work, so let's make a simple bot, the only function of which would be not dying. So our code now looks like this: ```java package student public class MyBot implements Bot { @Override public Direction chooseDirection(Snake snake, Snake opponent, Coordinate mazeSize, Coordinate apple) { return null; } } ``` ### The bare minimum The code above is not going to work yet, so at least for it to make sense and for the sake of simplicity, we will now make the snake always go upwards. ```java @Override public Direction chooseDirection(Snake snake, Snake opponent, Coordinate mazeSize, Coordinate apple) { return Direction.UP; } ``` You can try it out now, see how to [run your bot](#Run-your-bot). ### Pure randomness Now to be able to make some randomness we'll also define a list of all directions that we could possible go in as an array. ```java private static final Direction[] DIRECTIONS = new Direction[] {Direction.UP, Direction.DOWN, Direction.LEFT, Direction.RIGHT}; ``` And pick one random direction. ```java package student import java.util.Random; public class MyBot implements Bot { private static final Direction[] DIRECTIONS = new Direction[] {Direction.UP, Direction.DOWN, Direction.LEFT, Direction.RIGHT}; @Override public Direction chooseDirection(Snake snake, Snake opponent, Coordinate mazeSize, Coordinate apple) { Random random = new Random(); Direction randomDir = DIRECTIONS[random.nextInt(DIRECTIONS.length)] return randomDir; } } ``` See how to [run your bot](#Run-your-bot). ### More advanced logic Now we have a randomly moving bot, but it's not enough, it'll never achieve anything by just randomly moving in different directions, moreover, the snake can't move on all four directions, since there is no way it would go backwards, let's dig into this. To achieve a more advanced AI, first take look at what information do we possess: * Our own snake * The opponent snake * The size of the maze * The coordinate of the apple It would help us if we knew where our own snake's head is located, so let's add that. ```java Coordinate head = snake.getHead(); ``` We can move in any direction, except going backwards, so we should find the coordinate of "backwards". We will just take the second coordinate from our snake list of body parts. ```java Coordinate afterHeadNotFinal = null; if (snake.body.size() >= 2) { Iterator<Coordinate> it = snake.body.iterator(); it.next(); afterHeadNotFinal = it.next(); } final Coordinate afterHead = afterHeadNotFinal; ``` Now remove the backwards direction from the list of our possible moves. ```java Direction[] validMoves = Arrays.stream(DIRECTIONS) .filter(d -> !head.moveTo(d).equals(afterHead)) .sorted() .toArray(Direction[]::new); ``` Since our bot doesn't want to die, filter out all directions which might cause that. ```java Direction[] notLosing = Arrays.stream(validMoves) .filter(d -> head.moveTo(d).inBounds(mazeSize)) // maze bounds .filter(d -> !opponent.elements.contains(head.moveTo(d))) // opponent body .filter(d -> !snake.elements.contains(head.moveTo(d))) // and yourself .sorted() .toArray(Direction[]::new); ``` Now choose which move to take. We could add some randomness here, but it is not important now. So if we can move without losing, do it, otherwise, take any valid move that is not backwards, since there is no way to not lose. ```java if (notLosing.length > 0) return notLosing[0]; else return validMoves[0]; ``` ### Final Code So here is what we came up with, this is included with the repository, you find it as *johndoe.SampleBot*. ```java package student public class MyBot implements Bot { private static final Direction[] DIRECTIONS = new Direction[] {Direction.UP, Direction.DOWN, Direction.LEFT, Direction.RIGHT}; @Override /* choose the direction (stupidly) */ public Direction chooseDirection(Snake snake, Snake opponent, Coordinate mazeSize, Coordinate apple) { Coordinate head = snake.getHead(); /* Get the coordinate of the second element of the snake's body * to prevent going backwards */ Coordinate afterHeadNotFinal = null; if (snake.body.size() >= 2) { Iterator<Coordinate> it = snake.body.iterator(); it.next(); afterHeadNotFinal = it.next(); } final Coordinate afterHead = afterHeadNotFinal; /* The only illegal move is going backwards. Here we are checking for not doing it */ Direction[] validMoves = Arrays.stream(DIRECTIONS) .filter(d -> !head.moveTo(d).equals(afterHead)) // Filter out the backwards move .sorted() .toArray(Direction[]::new); /* Just naïve greedy algorithm that tries not to die at each moment in time */ Direction[] notLosing = Arrays.stream(validMoves) .filter(d -> head.moveTo(d).inBounds(mazeSize)) // Don't leave maze .filter(d -> !opponent.elements.contains(head.moveTo(d))) // Don't collide with opponent... .filter(d -> !snake.elements.contains(head.moveTo(d))) // and yourself .sorted() .toArray(Direction[]::new); if (notLosing.length > 0) return notLosing[0]; else return validMoves[0]; /* ^^^ Cannot avoid losing here */ } } ``` ### Run your bot In order to use your own bot, you must pass your package name and the name of the class as program arguments to the game. You must pass two bots, in order for the game to work, those could be the same. #### Example Let's use your newly written bot with the one, provided by us. Even though, they actually are the same. `java snakes.SnakesUIMain johndoe.SampleBot student.MyBot` *Note: this command is executed in the folder with already compiled .class files, not in the src directory. **You do not need** to worry about this if you are using an IDE, such as IntelliJ Idea.* If you are using any IDE, you could add those program arguments to be added automatically whenever you want to run or debug the program. ## What's next? Try to make the bot go towards the apple, it's basically the point of the game, but remember that you are not the only snake on the field. ## Be creative! We're going to let you out on a journey of bot creation now, good luck and have fun!

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully