Javascript from Zero to Proficiency by Patrick Felicia 笔记

JavaScript also makes it possible to communicate with a server through technologies often referred as AJAX, whereby information is sent asynchronously to the server, and then processed accordingly. 

<HEAD>  tag includes information that will not be displayed on the page; for example, the title of the page, JavaScript code, or styling preferences. 

CTRL + R refreshes a webpage.

It is good practice to add spaces around the operators such as +, -, /, or % for clarity. A block of instructions start with an opening curly bracket and that ends with a closing curly bracket. 
---------------------------

/*Adding the following javascript code in the webpage will cause the url change to http://127.0.0.1:11760/Ireland and the page doesn't load.*/

<SCRIPT>
var name="Pat", location = "Ireland", year = 2018;
console.log(year);
</SCRIPT>

-------------------

        var str1 = "string01";
        var str2 = "string02";
        var num1 = 1;
        var strs_combined = str1 +str2;
        var str_combine_num = str1 + num1;
        alert(strs_combined);
        alert(str_combine_num);


------------------
& can not be used in variable name.
---------------

var nameOfUser = prompt("Please enter your name","");
if (nameOfUser == "Patrick") 
    alert ("Hello Patrick");
else 
    alert ("Hello Stranger");

-------------------

var result = prompt("What is 1 + 1","");
        
resultAsNumber = parseInt(result);    
        
if (resultAsNumber === 2) 
    alert ("Well done");
else 
    alert ("Sorry, wrong answer");

----------------------
A function can be called using the () operator
---------------
Global variables need to be declared at the start of the script (using the usual declaration syntax) and outside of any function. They can then be used anywhere in the script.
---------------

//If a variable is initialized in a method without being declared, it is considered as a global variable        
function function3()
{
    testGlobal = 3;
} 
function3();
alert("value of testGlobal is: " + testGlobal);//this should display "value of test is: 3";


---------------
In JavaScript, a script will be executed until an error occurs in this script. When an error is detected, the browser will just stop to execute any further code.
--------------

<script type="text/javascript" src="myScript.js"></script>
<!--    linking to an external javascript file.-->

-----------------
We all learn by trial and error, and making mistakes is part of the learning process.
--------------
So, as you create your first script, set any fear aside, try to experiment, be curious, and get to learn the language. It is like learning a new foreign language: when someone from a foreign country understands your first sentences, you feel so empowered!
-----------------
Strings are considered as objects with associated attributes (often called properties) and functions (often referred as methods).
------------------

var myName = "Patrick";
var numberOfLetters = myName.length;
console.log("There are " + numberOfLetters + " letters in " +myName);

--------------------

var mySentence = "This is a short sentence.";
if (mySentence.indexOf("short") >=0 )             console.log ("Index of the word 'short' is: " + mySentence.indexOf("short"));
else 
    console.log ("'short' is not included in the sentence");

----------------

//slicing a string.
var mySentence = "This sentence is long and needs to be shorter";
var shorterSentence = mySentence.slice (0,14);
console.log(shorterSentence);

-----------------

var mySentence = "This sentence is long and needs to be shorter";
console.log(mySentence);

var modifiedSentence = mySentence.replace ("is long","is way too long");
console.log(modifiedSentence);

var upperCaseSentence = mySentence.toUpperCase();
console.log(upperCaseSentence);

var lowerCaseSentence = mySentence.toLowerCase();
console.log(lowerCaseSentence);

-------------------

var randomNmber = Math.random();
if (randomNmber <.7) 
    console.log ("there was a 70% chance for this message to be displayed");
else 
    console.log ("there was a 30% chance for this message to be displayed");

--------------------

var answer = prompt("Please enter your choice 1- 3","");
var choice = Number(answer);

switch (choice){
    case 1:
    console.log ("you chose 1");
    break;
    case 2:
    console.log ("you chose 2");
    break;
    case 3:
    console.log ("you chose 3");
    break;
    default:
    console.log ("Default option");
    break;
} 

console.log ("We have exited the switch structure");

---------------

do
{
    var answer = prompt("Please enter your choice 1- 3","");
    var choice = Number(answer);
} while (choice <= 1 || choice >=3);

--------------------

var questions = ["What is 2+2", "What is 4+2", "What is 4+5"];
var correctAnswers = [4, 6, 9];
var score = 0;

for (i = 0; i < 3; i ++)
{
    var answer = Number(prompt("Question "+ (i+1)+": "+questions[i],""));
    if (answer == correctAnswers[i]) {
        alert("Well done!"); 
        score++;
    }            
    else 
        alert ("Sorry wrong answer");
}

alert ("You answered " + score + " questions correctly");


---------------------

//creating an array
var words = new Array();
words[0] = "beauty";
words[1] = "peace";
words[2] = "calm";
console.log(words);


--------------------

var test = ["Noemy", "Alan", "John"];
console.log("Elements before sorting: " + test);
test.sort();
console.log("Elements after sorting: " + test);


-------------

<!DOCTYPE html>
<HTML>
    <HEAD>
    <TITLE>My First HTML Page</TITLE>
    <SCRIPT>  
    function updateTimer()
    {
        var todaysDate = new Date();
        var enDate = new Date (2019, 2, 6, 23,59,59,0);
        var diff = Math.abs(enDate-todaysDate);
        
        var nbDays = Math.floor(diff/(1000*60*60*24));
        var nbHours = Math.floor((diff%(1000*60*60*24))/(1000*60*60));
        var nbMinutes = Math.floor((diff%(1000*60*60))/(1000*60));
        var nbSeconds = Math.floor((diff%(1000*60))/(1000));
        
        document.getElementById("timer").innerHTML = nbDays+" Days";
        document.getElementById("timer").innerHTML += nbHours+" Hours";
        document.getElementById("timer").innerHTML += nbMinutes+" Minutes";
        document.getElementById("timer").innerHTML += nbSeconds+" Seconds";
    }
    
        
    </SCRIPT>
        
    </HEAD>
    <BODY  onload="setInterval(updateTimer,1000);">

        <DIV id = "timer"> </DIV>
                
    </BODY>
</HTML>


-----------------------------

var student1 = {

                fName: "Paul", 
                lName: "Murphy", 
                studentID:"ID101", 
                classes: ['CS700', 'CS800'],

                displayName : function (){return "My name is " + this.fName + " "+this.lName;}
               }

console.log(student1.displayName());

------------------

var student1 = {
                fName: "Paul", 
                lName: "Murphy", 
                studentID:"ID101", 
                classes: ['CS700', 'CS800'],
                displayName : function (){console.log("My name is " + this.fName + " "+this.lName);}
                }
student1.displayName();


---------------

//adding new property to an exiting object
function Student (firstName, lastName, studendIdentification, classesAttended)
{
    this.fName = firstName;
    this.lName = lastName;
    this.studentId = studendIdentification;
    this.classes = classesAttended;
}
        
var student3 = new Student("David", "Callagher", "120",['CS700', 'CS800']);
console.log("Student3 " + student3.lName);
console.log("Student3 " + student3.classes[0]);
var student4 = new Student("Mary", "Black", "121",['CS701', 'CS800']);
console.log("Student4 " + student4.lName);
console.log("Student4 " + student4.classes[0]);
student3.fullName = student3.fName + " " + student3.lName;
console.log("Student 3's full name: "+student3.fullName);    


---------------

function Student (firstName, lastName, studendIdentification, classesAttended)
{
    this.fName = firstName;
    this.lName = lastName;
    this.studentId = studendIdentification;
    this.classes = classesAttended;
    this.fullName = this.fName + " " + this.lName;
    this.nbModulesAttended = function() {return this.classes.length;}
}
        
var student3 = new Student("David", "Callagher", "120",['CS700', 'CS800']);
console.log("Student3 " + student3.lName);
console.log("Student3 " + student3.classes[0]);
var student4 = new Student("Mary", "Black", "121",['CS701', 'CS800']);
console.log("Student4 " + student4.lName);
console.log("Student4 " + student4.classes[0]);
console.log("Student 3's full name: "+student3.fullName);
console.log(student4.fullName);
console.log("Number of classes attended by Student 3: "+ student3.nbModulesAttended());
console.log(student4["fName"]);


--------------

console.log(Math.ceil(2.1));//3


----------------

var questions = ["electricity", "DNA"];
var answers = ["scientist1", "scientist2"];
var score = 0;
for (var i = 0; i < answers.length; i++)
        {
            var userAnswer = prompt ("Who discovered "+questions[i],"");
            userAnswer = userAnswer.toLowerCase();
            if (userAnswer == answers [i]) score++;
        }
alert ("You have answered "+ score + " Questions correctly!");


--------------

<!DOCTYPE html>
<HTML>
<HEAD>
    <SCRIPT>
function readField ()
{ 
    var text = document.getElementById("myText").innerHTML;
    console.log("Text found: "+ text);
    document.getElementById("myText").innerHTML = "Hello Stranger";
} 
        
function checkField()
{
    var fieldContent = document.getElementById("fName").value;
    if (fieldContent == "") alert ("Sorry, this field should not be empty");
    document.getElementById("fName").style.backgroundColor = "red";
}
        
    </SCRIPT>
</HEAD>
<BODY >
    
<DIV onclick = "readField()" id = "myText"> Hello World</DIV>
First Name: <INPUT type = text id = "fName" onblur = "checkField()">
</BODY>
</HTML>


-----------------

<!DOCTYPE html>
<HTML>
<HEAD>
    <SCRIPT>

function copyAddress()
{ 
    document.getElementById("b_fname").value = document.getElementById("s_fname").value;
    document.getElementById("b_lname").value = document.getElementById("s_lname").value;
    document.getElementById("b_address").value = document.getElementById("s_address").value;
}
        
    </SCRIPT>
</HEAD>
<BODY >
    
<FORM>
Shipping Address<BR>

<TABLE border = 0>
<TR> <TD>First Name</TD><TD><INPUT id = "s_fname"> </TD> </TR>
<TR> <TD>Last Name</TD><TD><INPUT id = "s_lname"> </TD> </TR>
<TR> <TD>Shipping Address</TD><TD><INPUT id = "s_address"> </TD> </TR>
</TABLE>

<BR>
<BUTTON type = "button" onclick = "copyAddress();"> Same Shipping Details </BUTTON>
<BR>
<BR>
Billing Address<BR>

<TABLE border = 0>
<TR> <TD>First Name</TD><TD><INPUT id = "b_fname"> </TD> </TR>
<TR> <TD>Last Name</TD><TD><INPUT id = "b_lname"> </TD> </TR>
<TR> <TD>Shipping Address</TD><TD><INPUT id = "b_address"> </TD> </TR>
</TABLE>

</FORM>
</BODY>
</HTML>


--------------------

<!DOCTYPE html>
<HTML>
<HEAD>
    <SCRIPT>
function checkField()
{
    var fieldToValidate = document.getElementById("phoneNumber");
    var feedback = document.getElementById("feedback");
    if (!fieldToValidate.checkValidity()) feedback.innerHTML = fieldToValidate.validationMessage;
}

        
    </SCRIPT>
</HEAD>
<BODY >
    
<FORM>
Phone Number: <INPUT type = "number" id = "phoneNumber" onblur = "checkField()"> 
<DIV id="feedback"></DIV>
</FORM>
    
</BODY>
</HTML>


--------------------------

<!DOCTYPE html>
<HTML>
<HEAD>
    <SCRIPT>
function checkField()
{
    var fieldToValidate = document.getElementById("phoneNumber");
    var feedback = document.getElementById("feedback");
    if (fieldToValidate.validity.valueMissing) feedback.innerHTML = "This field can't be left empty. Please enter a value";
}

        
    </SCRIPT>
</HEAD>
<BODY >
    
<FORM>
Phone Number: <INPUT type = "number" id = "phoneNumber" onblur = "checkField()" required>
<DIV id="feedback"></DIV>
</FORM>
    
</BODY>
</HTML>


----------------------

<!DOCTYPE html>
<!--add event listner-->
<HTML>
<HEAD>
    <SCRIPT>
function initEvents(){
    document.getElementById("button").addEventListener ("click", displayMessage)
    document.getElementById("button").addEventListener ("mouseover", displayMessageWhenOver);
} 
function displayMessage()
{
    console.log("You just clicked the button");
    document.getElementById("button").removeEventListener ("mouseover", displayMessageWhenOver);
}

function displayMessageWhenOver()
{
    console.log("You just moved the mouse over the button");
}
        
    </SCRIPT>
</HEAD>
<BODY onload = "initEvents()">
    
<BUTTON id = "button" type = "button" > Click me </BUTTON>
    
</BODY>
</HTML>


---------------
In JavaScript terms, when we deal with the innermost element (i.e., the child), we say that we are bubbling events, and if we decide to deal with the outermost element (i.e., the parent), we say that we are capturing events.
By default, if you add an event to an element, events are bubbled; however, it is possible to modify this options when adding an event, by specifying a third attribute and setting it to true (for a capturing behavior).
---------------

<!DOCTYPE html>
<!--bubbling events-->
<HTML>
<HEAD>

<SCRIPT>
function initEvents() {
document.getElementById("table").addEventListener("click",displayMessageWhenTableClicked,flase);
        
document.getElementById("innerCell").addEventListener ("click", displayMessageWhenInnerCellClicked, flase);
        }
        
function displayMessageWhenTableClicked()
{
    console.log("You clicked within the table");
} 

function displayMessageWhenInnerCellClicked()
{
    console.log("You clicked within the cell");
}
            
    </SCRIPT>    
</HEAD>
<BODY onload="initEvents()">
    
<TABLE id = "table" style = "background-color: black">
<TR><TD>Inside TR</TD><TD>Inside TR</TD><TD>Inside TR</TD></TR>
<TR><TD>Inside TR</TD><TD id = "innerCell" style = "background-color: red">Click Me, I Am inside</TD><TD>Inside TR</TD></TR>
<TR><TD>Inside TR</TD><TD>Inside TR</TD><TD>Inside TR</TD></TR>
</TABLE>

</BODY>
</HTML>


-----------------------

<!DOCTYPE html>
<!--navigating through nodes-->
<HTML>
<HEAD>

    <SCRIPT>
    function countElements()
    { 
        var body = document.getElementsByTagName("BODY")[0];
        var parentOfBody = body.parentNode.nodeName;
        console.log("Parent of BODY is "+parentOfBody);
        var firstChild = body.firstChild.nodeName;
        console.log("First Child of BODY is"+firstChild);
        var lastChild = body.lastChild.nodeName;
        console.log("Last Child of BODY is "+lastChild);
        var nextSiblingOfId1 = document.getElementById("div1").nextSibling.nodeName;
        console.log("The next sibling of DIV1 is "+nextSiblingOfId1);
    }
            
    </SCRIPT>    
</HEAD>
    
<BODY onload = countElements()><DIV id = "div1"> Hello World 1</DIV><DIV id = "div2"> Hello World 2</DIV>
    
</BODY>
    
</HTML>


---------------------

<!DOCTYPE html>
<!--adding and removing nodes and elements-->
<HTML>
<HEAD>

    <SCRIPT>
    function modifyDocument(){
        var newParagraph = document.createElement("p");
        var nodeWithinParagraphElement = document.createTextNode("This is a new paragraph");
        newParagraph.appendChild(nodeWithinParagraphElement);
        document.getElementById("div1").appendChild(newParagraph);
        var newParagraph2 = document.createElement("P");
        var nodeWithinParagraphElement2 = document.createTextNode("This is a new paragraph that will appear before the previous one");newParagraph2.appendChild(nodeWithinParagraphElement2);
        document.getElementById("div1").insertBefore(nodeWithinParagraphElement2, newParagraph);
    }    
    
    function removeNodes()
    {
        var firstDiv = document.getElementById("div1");
        if (firstDiv.firstChild) firstDiv.removeChild(firstDiv.firstChild);
    }
    </SCRIPT>    
</HEAD>
    
<!--<BODY onload = countElements()><DIV id = "div1"> Hello World 1</DIV><DIV id = "div2"> Hello World 2</DIV>-->
<BODY onload = modifyDocument()><DIV id = "div1"> Hello World 1</DIV><DIV id = "div2"> Hello World 2</DIV>

<BUTTON onclick = "removeNodes()" type = button> Click here to remove paragraphs.</BUTTON>
    
</BODY>
    
</HTML>


-----------

<!DOCTYPE html>
<!--opening, closing and moving windows using javascript-->
<HTML>
<HEAD>

    <SCRIPT>
        function openWindow()
        {
            myWindow = window.open("","hello","menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes, width=300, height = 300");
        } 
        function closeWindow()
        {
            myWindow.close();
        }
        
        function moveWindowRight()
        {
            myWindow.moveBy(100,0);
            myWindow.focus();
        } 
        function moveWindowLeft()
        {
            myWindow.moveBy(-100,0);
            myWindow.focus();
        }
        
        function resizeWindow()
        {
//            myWindow.resizeTo(500, 500);
            myWindow.resizeBy(-100,-100);
            myWindow.focus();
        }    
    </SCRIPT>
    
</HEAD>
<BODY>

<BUTTON onclick = "openWindow()" type = "button">Click to open a new window</BUTTON>
<BUTTON onclick = "closeWindow()" type = "button">Click to close the new window</BUTTON>
<BUTTON onclick = "moveWindowRight()" type = "button">Click to move new window to the right</BUTTON>
<BUTTON onclick = "moveWindowLeft()" type = "button">Click to move new window to the left</BUTTON>
<BUTTON onclick = "resizeWindow()" type = "button">Click to Resize the new window</BUTTON>    
</BODY>
    
</HTML>


----------------

<!DOCTYPE html>
<!--working with browser's location-->
<HTML>
<HEAD>

    <SCRIPT>
//        specify that the function changeLocation should be called after 1 second (i.e., 1000 milliseconds).
//        setInterval(changeLocation, 1000);

        function changeLocation()
        { 
            window.location.assign("http://www.baidu.com");
        }
                
    </SCRIPT>
    
</HEAD>
<BODY >

<BUTTON onclick = "changeLocation()" type = "button">Click to open go to Apple.com</BUTTON>

</BODY>
    
</HTML>

--------------------
 

<HTML>
    <HEAD>
            <SCRIPT>
                
                var nbFields = 0;

                function deleteTextFields()
                {
                    var myNode = document.getElementById("div1");
                    var nbChild = myNode.childNodes.length;
                    console.log ("NB Children" + nbChild);
                    document.getElementById("div1").removeChild(myNode.childNodes[nbChild -1]);
                    document.getElementById("div1").removeChild(myNode.childNodes[nbChild -2]);
                    document.getElementById("div1").removeChild(myNode.childNodes[nbChild -3]);
                    nbFields--;
                    

                }
                function addTextFields()
                {
                    nbFields++;
                    var newParagraph = document.createElement("INPUT");
                    var label = document.createTextNode("Field" + nbFields);
                    var br = document.createElement("BR");
                    newParagraph.type = "text";
                    document.getElementById("div1").appendChild(label);
                    document.getElementById("div1").appendChild(newParagraph);
                    document.getElementById("div1").appendChild(br);
                }
            </SCRIPT>

    </HEAD>
    
        <BODY ><DIV id = "div1"></DIV>

        <BUTTON onclick = "addTextFields()" type = button> Click here to add text fields</BUTTON>

        <BUTTON onclick = "deleteTextFields()" type = button> Click here to delete text fields</BUTTON>
        </BODY>
<HTML>

 

Unity 5 From Zero to Proficiency (Intermediate): A step-by-step guide to coding your first game in C# with Unity. Why this book can help you to get started with Game Development Creating your own game can be very intimidating at the start, and quite often, regardless of your experience with games, it is sometimes difficult to find the time and motivation to get over the first barriers and to get started. Often, these barriers seem higher than they actually are. Maybe you are a teacher trying to introduce games in your classroom or a parent trying to help your child with coding, but with no previous coding or game development experience; maybe you are a hobbyist who would love to create interactive environments based on your favorite games; maybe you are a student getting started with game development but you just don't know where to start or what resources to use; or maybe you have tried online video tutorials but found them disjointed. You may be wondering: "How can I start to create my games if I have no experience of coding", or "this game engine is so complex that I just don't know where to get started". This is quite common, and you can easily overcome these issues with a step-by-step approach that gets you to progressively develop and use your skills. This is the approach that I have used successfully over the past years to take students from no knowledge of coding or game development to good levels of proficiency in Unity and coding. Of course, it takes some time and dedication; however, by following the techniques and suggestions described in this book, I can promise you that you will progress, regardless of your background, and become more comfortable with Unity and coding. Content and structure of this book In this book, the third book in the series, you will become comfortable with programming in C# by creating a simple survival game in Unity. The book includes: A list of the learning objectives at the start of each chapter. Step-by-step activities. Opportunities to engage in deeper learning and problem-solving skills through challenges at the end of each chapter. Quizzes to test your knowledge. Code solutions (in C#) for each chapter. Cheat-sheets (i.e., shortcuts, best practice, etc.) that you can download. When you buy this book you get: Support via email. 18 video tutorials. 80% off the pdf version (save $5). 50% off the paperback version (save $22). The content of each chapter is as follows: Chapter 1 provides an introduction to C# and explains key programming concepts such as variables, variable types, polymorphism, constructors, or methods as well as best practices for C# programming within Unity. Chapter 2 helps you to code your first script in C#. It explains common coding mistakes and errors in Unity, and how to avoid them easily. Chapter 3 gets you to use C# to instantiate, use and control Rigidbody objects from your script as well as explosions. Chapter 4 explains how to create a simple weapon management system. You will create weapons (e.g., a gun and a grenade launcher), manage the collection of ammunition, and also implement a user interface to keep track of ammunition. Chapter 5 explains how to use Mecanim and NavMesh navigation to control an animated NPC that detects, follows, or shoot at the player. Chapter 6 makes it possible to combine the skills that you have acquired in the previous chapters to create a fully functional level. You will also learn how to generate a maze (or game level) dynamically from your code. Chapter 7 provides answers to Frequently Asked Questions (FAQs) related to FSM, NavMesh, Rigiddbody components, or Artificial Intelligence. It also provides links to additional exclusive video tutorials that can help you with some of your questions. Chapter 8 summarizes the topics covered in the book and provides you with more information on the next steps If you want to start programming in C# using a tried-and-tested method: download this book now. Table of Contents Chapter 1: Introduction to Programming in C# Chapter 2: Creating your First Script Chapter 3: Adding Simple AI Chapter 4: Creating and Managing Weapons Chapter 5: Using Finite State Machines Chapter 6: Putting It All Together Chapter 7: Frequently Asked Questions Chapter 8: Thank You!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值