Friday, February 3, 2017

second assignment

Hello world!
as part of my english assignment,  i was told to write this blogpost about my strong and weak points and also my future plans regarding the english language. as with almost any other Indonesians, english was taught to me as a secondary language at a relatively young age,  though for me, it didn’t stop at school, because throughout my child hood, me and my sister had been using english to talk to each other. Mostly because our parent does not know english particularly well and thus we can get away with making rude remarks to one another. I believe that one of my strong points in english is speaking, i’ve been able to fluently have conversations with my sister. The problem is that sometimes i’m too afraid to make mistakes that i sometimes stop myself to talk at all to save myself from the embarrassment, for example in english classes.

writing, though, is a whole different story, i’ve always loved english literature. most of the books i have in my collections are in english, ranging from casual novels to a book about the mathematics of chances, which i admittedly haven’t finished. one of my favorite book to read is called “the alchemist” by Paulo Coelho, which managed to convince one of my friends to linger more into the world of literature. i can’t say that my writing capability is at par with these authors though, i am extremely limited in my vocabulary, which brings me to my future plans in learning english. I want to someday write either a story book or a comic as a hobby, and so i want to expand my vocabulary to a more stellar height. also, maybe speak up more in english conversations, but that requires extensive social interactions.

Saturday, January 28, 2017

English Assignment 1


The story i'd like to tell is of how i met two of my friends back in high school. friends who had a big impact in my life. Back in our first days of high school, when we were all fresh men, everything was intimidating. It was such a huge leap from middle school, everything was different. I didn’t have my friends from middle school anymore, and i wasn’t particularly good at making new friends. For the first couple of days i barely knew anyone. i’d stay in the corner of the class, minding my own business, mostly avoiding any eye contact whenever possible. The first few weeks were better. We started to get to know each other, and as with typically any other high school kids, we started to form groups of people we’d rather hang out with than others, and believe it or not, my friends who are the main focus this story wasn’t in my circle of friends.
A few months into class, during an IT session, we were assigned into groups of 3 random students, i was put into a group i haven’t really been hanging out with so i was a bit uneasy. We were told to create anything tech related, the more complex the better. I have always loved tech related stuff, I’ve been spending my spare time back in middle school programming instead of doing my homework and stuff. I had this idea of making a video game for our project, i thought the idea would get utterly rejected but to my surprise, my friends seemed very interested. Obviously, being the only one in the group who knows how to program games, i did all the coding. But it was so much fun, we would meet up after school and discuss what our game was going to be like. Then the next few days i’d work out the code for the game and have them test it. their faces lit up when i showed them the prototype of the game, even if it was just gray boxes moving around. one of them worked on the graphics of the game while me and the other would tweak the code and add new features.

The end result wasn’t really much. But thanks to that experience and the enthusiasm of both of my friends, i knew what i want to choose as a career. And i can’t thank them enough. funny thing is, one of them is also studying programming so now if we want to make games together, i won’t be the only one who is doing the code.

Sunday, December 4, 2016

how to install and create a simple program with QT (C++)

my fourth assignment post... is to create an instruction on how to install Qt and create a simple program with it.

so first of all, you need to visit their website;
This is their website
after visiting their website, you should see a big green button that says "download QT", click on that.
it should take you to a page that asks you about several stuff regarding your level of distribution and stuff... i'm going to go get the open source version because i have no money, if you wanted to get the open source version you could answer it in this order...
"in-house deployment, private use, student use" --> "no" -->  "yes"
and the download button would light up with the text saying "get open source QT"
Click on in!
it should take you to the download page, and there will be another button that says "download now"
click it and the installer should start downloading

since i'm on a mac, i got the .dmg file, just run the installer like normal


it should open up the installer window

just click continue, and it will ask you if you want to create a QT account, just click skip for now...



after that click continue and it should start downloading some of the necessary stuff.
after that it will ask you to pick a destination on where you want it to install, remember; after you've installed it, don't move it anywhere...


after that select the latest version and click continue.
and after that click i agree to the terms and conditions and click continue and install...

wait for it to install.

after it's done, locate the folder where you installed it in, i'm on a mac so it looks like this;


click the Qt creator application and it should open up the program and you can start making your GUI applications;


i'm going to make a program that will have a button and a text field, when you press the button, it will take whatever is in the text field and say hello, <what's in the text field>
in the end it'll look like this

(sorry, no time to make the GUI fancier)

firstly we need to create a new project so go ahead and click that "+ new project" button...

after that name your project and add in the path
leave everything at it's default values as we will only need the defaults to create this simple program.

after that, the program will create the project folder for you, which will contain several different files, but in this example we will only need to be focusing on two files, the mainwindow.cpp inside the sources folder and the mainwindow.ui inside the forms folder.

go ahead and double click the mainwindow.ui folder, this will take you to the design tab, which is an easy to use drag and drop system.

drag the button, and the textedit elements into your GUI, also drag and drop a label element where you want the text to be displayed...

you can also access the properties of these elements in the bottom right side of the design tab, which is the one colored yellow in my screen...
there you can edit the variable names that will be used to reference these ui elements in the code, you can also change several other properties regarding the elements such as the displayed text on the button (which in my case i changed to "press Me")

after you're done "designing" your GUI go ahead and right click your button element, and press the "go to slot..."

it will pop out a new window to choose the action to be listened to, choose clicked() and hit ok.


this will take you to the mainewindow.cpp with an added block of code, now everything within the block of this code will execute whenever the button is clicked...

now within this block, add these lines of code...



it's pretty self explanatory, really... what we're doing here is we create a new variable with the type of QString (which is the QT version of strings with additional functionality regarding UIs), we assign to it the value of whatever is in the textEdit (the instance name is textEdit, ofcourse you can change it in the properties field)  field when the button is pressed converted it into a string (hence the toPlainText() method).

now we grab an element of the UI with the instance name of "label" and set it's text (setText()) to "hello, " and the variable we created...

run the code and it'll look just like the one i did!







Tuesday, November 29, 2016

Simple Pong Game Using HTML Canvas

This is the third assignment that i have to post here in my blog.
i need to demonstrate the use of the HTML canvas tag, so i thought, what better way to do that than to create one of the simplest games ever?

you heard me! we're making;

PONG


first thing's first; all you need to create this game is a text editor of your choice (i use sublime), and a browser that supports canvas...
if your browser does NOT support canvas... then are you living under a rock? get yourself the latest version of google chrome or something.

so to start, i'm going to show you the end result;
Looks awesome right? RIGHT!?

here's the scource code;

<!DOCTYPE HTML>
<head>
<title> THE GAME(?) </title>
</head>
<body>
<canvas id="canvas" width = "1000" height = "700"></canvas>
</body>
<script>
var canvasMan = document.getElementById("canvas");

var player1PosX = 100;
var player2PosX = canvasMan.width - 100;

var player1PosY = canvasMan.height/2;
var player2PosY = canvasMan.height/2;

var playerSize = 100;

var speedOverall = 5;

var vx = -speedOverall;
var vy = speedOverall;
var bx = canvasMan.width/2;
var by = canvasMan.height/2;

var aiSpeed = 2;

var scorePlayer1 = 0;
var scorePlayer2 = 0;

var c=canvasMan.getContext("2d");
canvasMan.addEventListener ('mousemove', function(e){
player1PosY = e.clientY - playerSize/2;
});
setInterval (update, 10)

function runAI(){
if (player2PosY + playerSize/2 > by){
player2PosY -= aiSpeed;
}
if (player2PosY + playerSize/2 < by){
player2PosY += aiSpeed;
}
}
function reset(){
bx = canvasMan.width/2;
by = canvasMan.height/2;
vx = -speedOverall;
vy = Math.floor(Math.random () * 10 - 5 + 1);
}
function update(){
by += vy;
bx += vx;
if (by < 0){
vy *= -1;
}
if (by > canvasMan.height){
vy *= -1;
}

if (bx < player1PosX + 10 && vx < 0){
if (by > player1PosY && by < player1PosY + playerSize && bx > player1PosX){
vx *= -1;
vy = Math.floor(Math.random () * 10 - 5 + 1);
}
if (bx < 0){
scorePlayer2++;
reset();
}
}
if (bx > player2PosX - 10 && vx > 0){
if (by > player2PosY && by < player2PosY + playerSize && bx < player2PosX){
vx *= -1;
vy = Math.floor(Math.random () * 10 - 5 + 1);
}
if (bx > canvasMan.width){
scorePlayer1++;
reset();
}
}

runAI();

//draw the background
c.fillStyle = "#000000";
// test if double qoute can be used in this particular statement
c.fillRect (0, 0, canvasMan.width, canvasMan.height);

//draw the players;
c.fillStyle = "#ffffff";
c.fillRect (player1PosX, player1PosY, 10, playerSize);
c.fillRect (player2PosX, player2PosY, 10, playerSize);
c.fillRect (bx, by, 10, 10);
c.font = "50px helvetica";
c.fillText(scorePlayer1, 200, 100);
c.fillText(scorePlayer2, canvasMan.width - 200, 100);
}

</script>

now, it's pretty straight forward.
we have a 'canvas' tag (<canvas></canvas>) that has several attributes; the id, the width, and the height.
i think the later two is pretty self explanatory, the width and the height just sets the size of the canvas.
the ID is going to be used to later reference the element int the javascript code.

the rest of the HTML is not really interesting, so let's move on to the script tag (<script></script>) which indicates the start and the end of a javascript block...

inside the script tag we have several variable declerations, these are done outside a specific function because we need them to be global functions.
the first variable is the canvas variable which stores tha canvas element in the HTML, we reference to it by using the id we specified earlier and using the getElementById statement.

the next two variables (player1PosX and player2PosX) is used to later state where to draw the paddles in the canvas along the x axis, we use 100 for the player1PosX so the first paddle so that the first paddle will be positioned 100 pixels after the start of the canvas (0).

both player1PosY and player2PosY is set to half the height of the canvas to position them in the middle of the canvas.

playerSize is used to later calculate the hit boxes of the paddles and use that to figure out wether the ball hit the paddle or not.

speedOverall is the speed of the ball. which will later be modified with Math.random() to create a dynamic gameplay.

vx and vy is going to be the speed of the ball, as you can see, we set the value to speedOverall.

bx and by is the position of the ball, it will later be constantly changed during the entirety of the gameplay.

aiSpeed is just the speed the second player can move in.

and the scorePlayer1 and scorePlayer2 just keeps track of the scores...

c references to the 2d context of the canvas
The getContext() method returns an object that provides methods and properties for drawing on the canvas.
This reference will cover the properties and methods of the getContext("2d") object, which can be used to draw text, lines, boxes, circles, and more - on the canvas.

this is all the variable declerations, now let's move on to the heart of the code.

canvasMan.addEventListener ('mousemove', function(e){
player1PosY = e.clientY - playerSize/2;
});

what this does is that it creates an event listener that will listen to wether or not the mouse is moving or not, hence the 'mousemove' parameter, it could also be used for other stuff such as 'mouseover' or 'mousedown' and many more, but for this particular example, we'll stick with 'mousemove'.
the second parameter is a function that is called whenever the event is heard, in this example we'll just create an inline function because the function is only oneline. this function will take a parameter called e.
inside the function we only have one statement. but this statement will be repeated for as long as the mouse is moving. this statement updates the variable called player1PosY and assigns to it the value of the mouse in the y axis (that is what e.clientY is, note e can be changed as long as the parameter is changed) minus the size of the paddle divided by two, this is due to the fact taht canvas draws objects (in our case rectangles) from the top-left corner.

the second statement; setInterval (update, 10); creates a continuous loop that executes every 10 miliseconds, hence the second parameter, which could be changed accordingly but in this case we'll just stick with 10...
the first parameter (update) is a function that will be run every interval (the 10 miliseconds).

now let's look at the update function...
function update(){
by += vy;
bx += vx;
if (by < 0){
vy *= -1;
}
if (by > canvasMan.height){
vy *= -1;
}

if (bx < player1PosX + 10 && vx < 0){
if (by > player1PosY && by < player1PosY + playerSize && bx > player1PosX){
vx *= -1;
vy = Math.floor(Math.random () * 10 - 5 + 1);
}
if (bx < 0){
scorePlayer2++;
reset();
}
}
if (bx > player2PosX - 10 && vx > 0){
if (by > player2PosY && by < player2PosY + playerSize && bx < player2PosX){
vx *= -1;
vy = Math.floor(Math.random () * 10 - 5 + 1);
}
if (bx > canvasMan.width){
scorePlayer1++;
reset();
}
}

runAI();

//draw the background
c.fillStyle = "#000000";
// test if double qoute can be used in this particular statement
c.fillRect (0, 0, canvasMan.width, canvasMan.height);

//draw the players;
c.fillStyle = "#ffffff";
c.fillRect (player1PosX, player1PosY, 10, playerSize);
c.fillRect (player2PosX, player2PosY, 10, playerSize);
c.fillRect (bx, by, 10, 10);
c.font = "50px helvetica";
c.fillText(scorePlayer1, 200, 100);
c.fillText(scorePlayer2, canvasMan.width - 200, 100);
}

the first few lines handles game mechanics and logic,
canvas animation works by drawing new things every set interval and forgetting anything before it. so we can use this to our advantage by drawing the objects with coordinates of variables we change with functions and logic,
the bx and by is used for this, it is added by the value of vx and vy, and later it will be used as the coordinates for the "ball", after that we have several logical statements, which is mostly mathematical stuff that i will not explain much but basically the first 2 if's are used to bounce the ball if it hits the top and bottom of the canvas

the later 2 if's and it's nested if's are logics used by the game to determine wether the ball went past the paddles (on either sides) and if so add the score to the appropriate players and run the reset function, and if not bounce the ball back.
we determine if the ball hits the paddle by using the paddleSize variable earlier, since we know that the coordinates of the paddle starts from the top point (0 from the paddle) to the bottom (paddle size) added by the coordinates of the paddle, then we can just check if the ball is within the paddle Y coord and the paddle Y  coord plus the size of the paddle.

next we dwell on the code that creates the visuals of the game;

c.fillStyle = "#ffffff";

determines the colours of the elements drawn after it's statement until another fillStyle is stated.

fill rect will accept parameters of this order fillRect (xCoordinate, yCoordinate, width, height);

c.fillRect (player1PosX, player1PosY, 10, playerSize);
c.fillRect (player2PosX, player2PosY, 10, playerSize);

draws the paddles for both players. note that player1PosY will constantly change according to the user mouse Y coordinates, the player2PosY will also be modified by the runAi function, which we'll get into later.

c.fillRect (bx, by, 10, 10);

draws the ball, which is actually a rectangle, because we wanted to capture the old-ish feel of the pong game.
notice the first and second parameter is bx and by, which will be changed constantly.

c.font = "50px helvetica";
c.fillText(scorePlayer1, 200, 100);
c.fillText(scorePlayer2, canvasMan.width - 200, 100);

just shows the scores of both players...


now let's move on the the reset() function;
function reset(){
bx = canvasMan.width/2;
by = canvasMan.height/2;
vx = -speedOverall;
vy = Math.floor(Math.random () * 10 - 5 + 1);
}
this function basically runs everytime the ball hits either edge of the screen horizontally speaking, it will put the ball back in the middle of the canvas and randomize the speed it is going in the y direction.

next is the AI function that will move the second player, this will not be as interesting as it sounds;
function runAI(){
if (player2PosY + playerSize/2 > by){
player2PosY -= aiSpeed;
}
if (player2PosY + playerSize/2 < by){
player2PosY += aiSpeed;
}
}
that's right; 4 lines of code for an AI, a really dumb AI;
in a nutshell this code checks wether the ball is above the paddle, which in that case it will move up, or is it below the paddle, which it will move down.

and there you have it, a working PONG game! enjoy!!!

also, enjoy the latest installment of

"PORTAL PONG!"






Sunday, September 18, 2016

Assignment 2!

This is my second assignment; which is making a simple code.
with that out of the way, here's my code!!!

because i've been learning classes and how to use them in C++, i figured why not kill 2 birds with one stone by practicing both my assignment and classes in one code:



#include <iostream>
#include <string>

#include <stdio.h>

using namespace std;

class presunivClass {
public:
    
    presunivClass();
    ~presunivClass();
    
    void setSeats (int newSeats){
        if (newSeats > 0){
            numSeats = newSeats;
        }else{
            cout << "do you expect them to just stand up during the whole lecture session?" << endl;
        }
    }
    void setName (string nameDude){
        if (nameDude != ""){
            className =nameDude;
        }else{
            cout << "enter a name, how else could the students recognize the classroom?" << endl;
        }
    }
    void setLecturer (string lectureGuy){
        if (lectureGuy != ""){
            lecturerName = lectureGuy;
        }else{
            cout << "you have to address who will be teaching the class";
        }
    }
    void setTime (int newTime){
        timePack = newTime;
    }
    int getSeats (){return numSeats;}
    string getTime (){
        if (timePack == 1){
            return "7:30";
        }else{
            return "10:30";
        }
    }
    
    string getName (){return className;}
    string getLecturer(){return lecturerName;}
    
private:
    
    
    int numWindows, numSeats, numDoors, timePack;
    
    string className, lecturerName;
    
};

presunivClass::presunivClass(){
    
}

presunivClass::~presunivClass(){
    cout << "class dismissed! Hurrahh!!!" << endl;
}

int main (){
    //kode tugas mulai dari sini:
    bool informationFilled = false;
    
    string nameHolder, lecturerHolder;
    int seatsHolder;
    
    presunivClass programmingConcepts;
    
    while (!informationFilled){
        cout << "you've created a class, please fill out these required information!" << endl;
        cout << "what class will this be?" << endl;
        cin >> nameHolder;
        cout << endl;
        cout << "Great, now who will be the lecturer?" << endl;
        cin >> lecturerHolder;
        cout << endl;
        cout << "okay, now how many students will be attending this class" << endl;
        cin >> seatsHolder;
        cout << endl;
        cout << "thank you for filling this out, now checking if it's complete, please wait..." << endl;
        
        programmingConcepts.setSeats(seatsHolder);
        programmingConcepts.setName(nameHolder);
        programmingConcepts.setLecturer(lecturerHolder);
        
        if (nameHolder != "" && lecturerHolder != "" && seatsHolder > 0){
            cout << "Great job, the form has been succesfully completed!"<<endl;
            
            bool timeChoose = true;
            
            while (timeChoose){
                cout << "please choose which time would you like the class to begin" <<endl;
                cout << "1. 7:30    2. 10:30" <<endl;
                int time = 0;
                scanf ("%d", &time);
                switch (time){
                    case 1:
                        cout << "you have chosen 7:30, don't be late!" <<endl;
                        programmingConcepts.setTime(time);
                        timeChoose = false;
                        break;
                    case 2:
                        cout << "you have chosen 10:30, don't be late!" <<endl;
                        programmingConcepts.setTime(time);
                        timeChoose = false;
                        break;
                    default:
                        cout << "that is not an option, try again:" << endl;
                        timeChoose = true;
                        break;
                }
            }
            informationFilled = true;

            }else{
            cout << "the information is false, please try again;" << endl;
        }
        
    }
    cout << endl << "great, begin class with this information; class name: "<< programmingConcepts.getName() <<endl << "class lecturer: " << programmingConcepts.getLecturer()<<endl << "number of students: "<< programmingConcepts.getSeats()<< endl << "and it begins: "<< programmingConcepts.getTime() <<endl;
    return 0;
}


incase i'm not allowed to use C++
This one is the one without the OOP aspects:



        

#include <stdio.h>


int dude(int x, int y){
    if (x < y){
        return 1;
    }else{
        return 0;
    }
}

int main (){
    int a = 0, b = 0;
    bool filled = false;
    
    while (!filled){
        printf("fill in two variables, no zero or negative numbers\n");
        printf("enter a value for a: \n");
        scanf("%d", &a);
        printf("enter a value for b: \n");
        scanf("%d", &b);
        if (a > 0 && b > 0){
            printf("thank you for filling this out\n");
            filled = true;
        }else{
            printf("you cannot enter that number\n");
        }
    }
    switch (dude (a, b)){
        case 1:
            printf ("a is less than b\n");
        break;
        case 0:
            printf ("a is more than b\n");
        break;
    }
    return 0;
}




        
Explanation:
starting from "int main (){"

first i declare variables using this format:

datatype variableName;

in the code i declared informationFilled as a boolean by typing:
bool informationFilled = false;
and i immediately assigned a value by adding an equation mark and the value of "false" for booleans.

next, i started a while loop which is structured like this:

while (condition){
//blah blah blah
}

the condition i used is (!informationFilled), which basically means that anything within this while block will loop as long as informationFilled is false (! stands for "not").

within that while loop are a bunch of cin's and cout's, which has the same function as scanf and printf so i don't think i need to explain that.

ignore the stuff that starts with "programmingConcept", those are class functions that i like to call "setters".

next, still in the while loop is an If statement, which is structured like this :

if (condition){
//do stuff
}

you can also add an else or else if at the bottom to add more complexity:

if (condition){

}else if (other condition){

}else{

}

i forgot to mention, "conditions" are basically boolean values (true or false), that can be replaced with comparative operators comparing two or more variables (in the case of more comparision you could use logical operators such as and (&&) and or (||))

within the if statement, i added another while loop, just to show you can do that.
and within THAT while loop i added a switch statement which is formatted like this:

switch (variable){
case condition1:
//do something
break;
case condition2:
//do something else.
break;
default:
//do something if no other case conditions are met
breaK:
}

you can have as many cases as you want. basically it's just another version of the if statements (and it's friends)

in case you didn't notice, i added an assignment statement to the conditions in both whiles in some if statements and some switch cases, these are what i like to call "loop breakers"i coined the term myself, don't judge me!. the purpose of these are to prevent any unlimited loops and to make it possible to exit a loop.

now let's get down to functions; the functions i used in my code are functions inside classes, including special ones like constructor and destructor functions; but simpler functions in non OOP language are like this

functions are stated like so:

returnType functionName (dataType parameterVariable){
//do stuff
return someVariableMatchingTheReturnType
}

of course you can ignore the return if the return type is void.

this is how you call a function;

functionName (argumentVariable);

functions with returnTypes can also be used in places where you can use a normal variable for example; variable assignment;

int x = someFunctionWithAReturnTypeOfInteger(argumentVariable);

Result of first code (i don't know why but i can't put any spaces between the string inputs):


Result of second code:




That is it for this assignments.