[GameMaker Studio] Neural Network in Game Maker Studio – part 2

Now that our neural net is set up we have to process the input and use the result to control our agent. On this part of the series, we are going to feed the neural net input data and then use the output data to allow our tiny arrow head to move towards a target object.

Feed Forward Script

First, we’ll create a script and name it scr_nn_feedforward. This script will perform the computation for our neural net. Feed forward, is a term describing an element or pathway within a control system that passes a controlling signal from a source to a load (source: Wikipedia).

To get the output value, we are going to pass the weighted sum of each input node to the neurons in the hidden layer. Apply an activation function and then do the same process for the output nodes.

///scr_nn_feedforward()

//Hidden Layer
    for(var i=0; i<array_length_1d(neurons); i++){
        neurons[i] = 0;
        for(var j=0; j<array_length_1d(inputs); j++){
            neurons[i] += inputs[j]*weights[i, j];
        }
        
        //Activation function
        neurons[i] = tanh(neurons[i]);
    }

//Output Nodes   
    for(var i=0; i<array_length_1d(outputs); i++){
        outputs[i] = 0;
        for(var j=0; j<array_length_1d(neurons); j++){
            outputs[i] += neurons[j]*output_weights[i, j];
        }
        
        //Activation function
        outputs[i] = tanh(outputs[i]);
    }
Activation Function

We will also need to create a script tanh()Hyperbolic tangent is an activation function. Activation functions makes our neural net non linear enabling it to solve more complex problems. They basically converts the input signal of a neuron into an output signal which will be used by another layer, in our case, the output layer as an input signal.

Advertisements
 
REPORT THIS AD

There’s a variety of function we can use such as Sigmoid, Rectified Linear Unit, or Leaky ReLU. Which performs differently — each provides different output ranges.

tanh(x) script
///tanh(x)

var _x = argument0;
var _e = 2.718281828459;
var _ans = (power(_e, 2*_x)-1)/(power(_e, 2*_x)+1);

return(_ans);

In the code above, we are using the variable “_e” which hold the value for Euler’s Number. Game Maker has a built-in function for it called “exp()” but the problem is that it does not work properly with negative integers which results in an incorrect return value. So instead, we are going to do it this way.

Because of its range (-1 to 1) it can be also used for the output neuron and to turn the arrow head left or right by multiplying the output to the agent’s turn speed.

Arrow head object

Next, we will create our arrow head object. We’ll name it obj_arrowhead. Create and add a sprite for it. I prefer to make a simple 32px v-shaped arrow.

Make sure it’s tip is is pointing to the right (0 degree) and set the origin at the center.

On create event, we are going to use the scripts we created in part 1 to initialize the neural net:

///Initialize the neural net
   scr_nn_create();

//Initialize weights
   scr_nn_initialize();

On the step event, we are going to set the input values on neural net which is the degree the arrow should turn in order to point towards our target. Then we will execute the feed forward script we created earlier:

var target = obj_target;

//Give input
   inputs[0] = angle_difference(image_angle, point_direction(x, y, target.x, target.y));

//Feed forward
   scr_nn_feedforward();

Next, on the same step event, we’ll make the arrow head turn left or right — rotating it by adding the product of outputs[0] and turn_speed to the image_angle of the arrow head.

var turn_speed = 3; //How fast it turn
var move_speed = 5; //How fast the arrow head move

    //Turn
        var left = 0, right = 0;
        image_angle += turn_speed*(outputs[0]);
    
    //Move
        x += lengthdir_x(move_speed, image_angle);
        y += lengthdir_y(move_speed, image_angle);  
Target Object

For the target object. We’ll create an object obj_target and then add a sprite (set the origin of the sprite to center).

Step Event:

//Move self to mouse pos on click
    if(mouse_check_button_pressed(mb_left)){
        x = mouse_x;
        y = mouse_y;
    }
Main Controller Object

For the main controller object, obj_nn_main, we just want it to create a number of arrow head objects in the room and save the instance id of each one in an array for later use.

Create event:

randomize();

//Create multiple arrow heads
    for(var i=0; i<10; i++){
        nn_obj[i] = instance_create(x, y, obj_arrowhead);
    }
Setting up the Room

• Place obj_nn_main at the middle of a room.
• Place obj_target anywhere.

Run the game. If your arrow heads behave like this, it’s time to celebrate. It’s a success:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

As you can see, some of the agents are able to follow the target already. The simplicity of the task makes it easy for the neural network to get the correct set of w

 

 

 

 

 

 

 

eights on first try. But hey, we will start simple and then use the neural net for more complicated task later on.

By now, the neural net is complete and it is able to perform an action. But we are not completely done yet. We still haven’t done anything to train it yet.

 

On the next part of this series, we are going to train our neural net using genetic algorithm. See you on the next post!

 

[출처] https://highleapstudios.wordpress.com/2019/10/05/neural-network-in-game-maker-studio-2/

 

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
45 [게임 일반] 선택 기반 게임의 표준 패턴 : Standard Patterns in Choice-Based Games 졸리운_곰 2025.01.13 236
44 [게임 일반] SharpMoku a Gomoku/Five in a Row Written in C# : SharpMoku a Gomoku/Five in a Row C#로 작성됨 : 오목게임 개발 file 졸리운_곰 2024.10.31 311
43 [게임 마켓플레이스] 스팀에 ‘게임’을 출시하고 싶다면? file 졸리운_곰 2024.09.07 316
42 [게임 일반] 카드 덱 이미지 (트럼프 카드) 졸리운_곰 2024.05.27 224
41 [게임 개발 일반] 콘솔은 어려울수록, 모바일은 쉬울수록 '돈' 쓴다 file 졸리운_곰 2023.10.30 264
40 [게임 개발 일반] 게임 초기 기획서 작성 방법 졸리운_곰 2023.07.16 250
39 [게임 일반] 하이퍼 캐주얼 모바일 게임 퍼블리셔가 말하는 개발자의 필수 역량은? file 졸리운_곰 2023.02.08 245
38 [게임 일반] 외신, 2D 게임 개발에 적합한 엔진 10종 선정 file 졸리운_곰 2023.01.15 206
37 [게임 일반] 성공적인 하이퍼 캐주얼 게임 제작을 위해 알아야 할 모든 것 졸리운_곰 2023.01.11 192
36 [게임 일반] 게임의 정의와 요소 file 졸리운_곰 2023.01.02 185
35 [게임 일반] 게임(Game), 일상에서 만드는 놀이의 즐거움 file 졸리운_곰 2023.01.02 205
34 [게임 일반] 우리는 왜 게임에 빠지는가 - 게임의 요소와 게임 변천의 역사 졸리운_곰 2023.01.02 250
33 [게임 일반] 재미있는 게임이란? 10부. 게임의 6단계 file 졸리운_곰 2023.01.02 194
32 [게임 일반] 재미있는 게임이란? 9부 -스타2의 패턴전략- file 졸리운_곰 2023.01.02 214
31 [게임 일반] 재미있는 게임이란? 8부 -블리자드의 패턴전략- file 졸리운_곰 2023.01.02 265
30 [게임 일반] 재미있는 게임이란? 7부 -Wow의 패턴전략- file 졸리운_곰 2023.01.02 162
29 [게임 일반] 재미있는 게임이란? 6부 -패턴과 리소스- file 졸리운_곰 2023.01.02 228
28 [게임 일반] 재미있는 게임이란? 5부 -카오스 시스템- file 졸리운_곰 2023.01.02 266
27 [게임 일반] 재미있는 게임이란? 4부 -패턴과 상호작용-' file 졸리운_곰 2023.01.02 186
26 [게임 일반] 재미있는 게임이란? 3부 '게임이 나아가야 할 방향' file 졸리운_곰 2023.01.02 162
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED