Jasmine Tutorial: Unit Testing Promises In Angular Services

Leave a comment Standard

So recently I’ve been doing a lot of Angular unit tests with Jasmine and Grunt. I have to say, testing promises is extremely frustrating and most of the examples I found out there either 1) didn’t work or 2) wouldn’t allow you to test content in a then block if you had multiple chained promises, or if you had a promise being called from and returned from another service. After many hours of frustrating trial and errors I found a solution I’m happy with so I want to share.

Let’s assume this is your controller:

'use strict';

angular.module('myModule').controller('myCtrl', ['$scope', 'api',
function ($scope, $api) {

  $scope.data = null;
  $scope.message = null;

  /**
  * Load some data from the API service
  * @return boolean
  **/
  $scope.loadData = function () {

    var config = {
      method: 'GET',
      url: 'http://api.domain.com/someRESTfulEndpoint',
      headers: {'Content-Type': 'application/json'},
      data: null
    };

    return $api.load(config).then(function (request) {
      if (request) {
        $scope.message = 'Your data was successfully loaded';
        $scope.data = request.response;
        return true;
      } else {
        $scope.message = 'The API service failed';
      }
      return false;
    });
  };
}]);

And here is the service making your API calls:

'use strict';

angular.module('myModule').service('api', ['$rootScope', '$http',
  function ($rootScope, $http) {

    /**
    * Makes the $http request given the proper configuration options
    * @param Object configruation for the $http request
    * @return Object $http promise that resolves to request payload or error
    **/
    this.load = function (options) {
      return $http({
        method: options.method || 'GET',
        url: options.url || 'http://api.domain.com/someDefaultEndpoint',
        headers: options.headers || null,
        data: options.data || null
      }).then(
        function (request) {
          //we got a response back, return just the API payload data
          if (request.status === 200 && request.data) {
            return request.data;
          } else {
            return {
              results: false,
              message: 'API request error',
              response: request
           };
         }
       }
     );
   };
}]);

Finally, this is your working unit tests:

'use strict';

describe('testing myModule', function () {

  beforeEach(module('myModule'));

  var $controller, $rootScope, $scope, $api, $httpBackend, $q;

  beforeEach(
    inject(function (_$controller_, _$rootScope_, api, _$httpBackend_, _$q_) {
      $controller = _$controller_;
      $rootScope = _$rootScope_;
      $httpBackend = _$httpBackend_;
      $q = _$q_;
      $api = api;
      $scope = $rootScope.$new();

      $httpBackend.when('GET').respond('test http GET call');
      $httpBackend.when('POST').respond('test http POST call');

      $controller('myCtrl', {
        $scope: $scope,
        $api: $api
      });
    })
  );

  it('has a $scope.loadData() function', function() {

    var testConfig = {
      method: 'POST',
      url: 'http://api.domain.com/endpoint',
      data: { some: 'data'}
    };

    var fakeData = { data: 'is fake' };

    //we spy on the API service and also return a fake promise call
    spyOn($api, 'load').and.callFake(
      function() {
        var deferred = $q.defer();
        deferred.resolve({result: true, response: fakeData});
        return deferred.promise;
      });
    });

    $scope.loadData(testConfig); //call the function we're testing in the controller
    $scope.$apply(); //we have to call this so Angular will try and resolve the promise
    expect($api.load.calls.count()).toEqual(1); //make sure it's called the api service
    expect($scope.message).toEqual('Your data was successfully loaded');
    expect($scope.data).toEqual(fakeData);
  });

  it('returns an error if the API fails', function() {

    var testConfig = {
      method: 'POST',
      url: 'http://api.domain.com/endpoint',
      data: { some: 'data'}
    };

    spyOn($api, 'load').and.callFake(
      function() {
        var deferred = $q.defer();
        deferred.resolve({
        result: false,
        message: 'api error'
      });
      return deferred.promise;
    });

    $scope.loadData(testConfig);
    $scope.$apply();
    expect($scope.message).toEqual('api error');
    expect($api.load.calls.count()).toEqual(1);
  });
});

Continue reading

Advertisements

Sample Angular Website

Leave a comment Standard

So I’ve seen a lot of people using AngularJS but I see very few examples of a website made using it. That’s why I decided to post an example website to give you an idea of what a full website looks like using AngularJS. It has samples of some of the things you’ll commonly find in a website made entirely with Angular:

  •  Navigation & Routing
  • Providers & Directives
  • Controllers & Config Blocks
  • Data Calculations
  • Filtering

Sorry if you’re looking for Angular 2.0, this was made with Angular 1.5.8. View, fork and/or edit the files on Plunker!

Why Making A Game Takes the Fun Out of It (and how to fix this)

Comments 4 Standard

I see it all the time, people coming into forums and online communities for games and game developers asking how to make a game or how to get their ultra cool idea that everyone will love and has never been done before off the ground and make it a tangible reality. Let’s get things straight, we love games because they’re fun and entertaining. It drives our creative vision and imagination and offers an escape from the mundane and the boring reality that is our lives. This passion, this drive to express ourselves and have fun is often what leads people to try their hand at making their own games. Many will start this journey but very few will finish it and even fewer will finish it with a successful and positive outcome (and let’s face it, money in your pockets). So why does this happen? Why do so many people start down this path of learning and creativity and adventure for fun that ends up leaving them broken, frustrated and depressed? The reality is that games are a lot of work and the very nature of making a game isn’t even a little bit fun. In many ways it’s the exact opposite of what we’re trying to achieve. So how does this happen and what can we do to fix it? Let’s break it down from the point of view of an Indie game developer whose a one man shop (or small shop) trying to make a game.

Lack of skills

You want to make a game but you’ve never programmed before, you don’t know anything about what’s required to make the type of game you want to create and even if you have those things covered you may not have all the skills you need to make it happen. Just because you can program doesn’t mean you can draw or compose artwork or market your finished product if you ever get that far. As an indie game developer you really have to be a jack of all trades. Think about trying to build a house if you’ve never built a house before. What happens if you only know how to frame the house but not how to do plumbing and electrical and tile work and all the other things that are required to finish the house? You end up with just the shell of a house that is lacking in so many ways you can hardly call it a house. This is one of the biggest problems I see with indie game devs — they lack the skills to accomplish what they’ve set out to do and they’re not prepared to outsource when they need to, which brings me to my next point.

Budget constraints

Making games is inherently expensive. Even if you create your own game framework and develop your own models/artwork, sounds and music you still have to — at a minimum — invest in a computer and dedicate hundreds of hours towards the development of your game. Those hours add up and while you’re developing your game you’re not earning a living that you need to support yourself and/or your family. Yes, that’s right, you still need to eat and buy necessities and support yourself and/or your family which is why even if you do have the funds outsource some of the work you lack the skills for you’re still fighting a losing battle towards my next point.

Time constraints and distractions

Supporting yourself and your family means that you’ll still need a full time job even as you chase the ethereal dream of creating your own game. Your time is precious and what little of it you have left after your regular day job has to be split between your other financial and personal commitments. Your kids need their parents and your house and car need to be maintained and you’ll struggle to find the proper work/life balance amidst all of the chaos that you juggle on a daily basis without adding the complexities of your game into the mix.

Technical problems, bugs, new frameworks and advances

So even if you can overcome all these odds so far you’ll still find yourself stuck hitting roadblocks as your game progresses. Technical problems you didn’t predict or forsee early on (and how could you, you’re still just learning yourself) end up being the bane of your game’s existence. Now you have to go back and re-write and re-factor and debug until you’re so frustrated you could pull all of your hair out and go bald. New frameworks and technological advances will make your second guess yourself or roll back to square one because you really do want to upgrade your SDK and add in the new dynamic system and better bump map texturing because who doesn’t want their game to be using the newest, latest and greatest technology available? No one wants to play a game that doesn’t have the same bells and whistles that their competition does because they took the the extra time/budget/testing cycle hits to go with the greater tech.

Slow progress and scope creep

Ultimately these things combined will drag your game down. What may have started off well and progressing quickly has suddenly slowed to a snail’s pace. Things suddenly feel like they’re never getting done or you have so many issues on your plate that it feels like there’s never an end in sight. Your game has hit a standstill and isn’t advancing like it was in the beginning and this is awfully discouraging and frustrating. The scope of your project has suddenly tripled and your todo list is a never-ending tally of bug fixes and re-factors and speed optimizations that need to be addressed for any chances of your game seeming like it’s something worth playing.

Early demo failures and monotonous repetition

If you’ve made it far enough to put together early demos and alpha access then pat yourself on the back — most people will never make it this far and you’ve just become a member of an elite club that deserves a badge of honor. The only problem is your demo gets horrible reviews, you realize your controls are too hard to use and this puts you into a crazy monotonous cycle of playing a particular part of your game over and over again as you attempt to fine tune it and make it more playable and more fun.

Never good enough

Unfortunately the truth is that your game will never be good enough. Someone will always find something to complain about even if you see some great feedback and helpful critiques that, if implemented, could really take your game to the next level and set you apart from your competition. Your controls will never be 100% perfect, your menu system may be too hard to read or too complex to navigate and you’ll never quash all the bugs that have been reported partly because you can’t re-create them all because your game is being run and tested under hundreds of different environments and hardware and operating systems that you didn’t have access to (and probably never will) as you were developing. If you’ve made it here this might just be the time for you to throw in the towel and say goodbye to all the blood, sweat and tears you succumbed to in order to make it this far.

Overcoming It All

If this has discouraged you against making your own game — good. Making a game isn’t easy and it’s not something for everyone so don’t waste your time early on if you’re not prepared to go through everything I’ve already mentioned and be able to walk away without anything to show for it. However that doesn’t mean you shouldn’t make a game or that it’s impossible to do it either. Where there is a will there’s a way and let me show you how.

  • Map out your game design, features, characters and how the game works. Now create lots of small, easy tasks you can accomplish in order to see your core game mechanics to completion enough that you could play a simple version of your game without any extra bells and whistles. Set yourself up to do as little as you have to but as much as you need to in order to get a completed version of your game.
  • If you lack the skill to do something you have two options. The first is that you resign yourself to taking the time to learn this new skill and the next is that you can outsource the skill to someone who’s already achieved it. You don’t have to be an expert programmer to make a game, just an adequate one. If you’re going to invest time into learning a new skill don’t dwell on it for too long, learn enough that you feel confident you can accomplish the task at hand and then move on. Investing too much time in learning a skill will start you down a path that walks further and further away from working on your game.
  • Sit down and map out all of the expenses you foresee as being necessary to complete your game. Now triple it. If you can’t afford to spend this amount of money into your game then you need to go back to your concept and re-work it until you get a budget that you can work with. If you’re really determined you can look for some outside investors but don’t count on this — ever. Most investors want to see a fully working demo before they’ll even consider opening their pocketbooks and investors will demand more than 50% of whatever profits you make from your game when it’s done.
  • Your time is precious when you have so little of it to devote to your game. Start by mapping out a timeline of your game features/assets and how long you think it will take you to accomplish them. Now double that. Now compare that to how much free time you really have to devote to your game. Will this game take you more than a year to complete? Do you have the dedication to spend more than a year working on a single project? If the answer is no then you need to go back to the drawing board until you’ve come up with a reasonable timeline that you can work with. Keep your game as small as you possibly can by focusing on the core mechanics and leaving out any fluff that you could add at a later date. Now stick to your timeline. If you budget 2 weeks to work on a character and by the end of the second week the character isn’t done don’t dwell on it — either move on to the next item in your list. Don’t adjust your timeline and don’t spend more time that you budgeted on this part of it. Sure, your ultimate goal is to have a working character with great animation but if you can’t ever get a game working with a broken character then who cares if your character’s animation is jerky or unrealistic? Think about the big picture because you can always circle back later.
  • Invest in a good debugger and testing tools. Do whatever you can to automate this process as much as possible because it will give you more time to work on trivial issues when you can quickly address and fix the larger ones. If you run into a bug that makes your game do something funky but it doesn’t prevent the gameplay from continuing table it and work on something else. Try not to get caught up in the more minute issues and focus more on the big picture. You can always circle back and fix bugs later but if you spend all your time bug quashing you’ll end up with a pretty interface or character or scene that doesn’t let interact and play with it. Pick a version of a framework and stick with it, don’t upgrade it unless you absolutely have to. The more you upgrade and update to the latest and greatest the more issues you’ll run into and the more refactoring and scope creep you’ll run into. It’s okay to build a game that isn’t using the latest and greatest version of your frameworks or 3rd party integrations. This will also give you a chance to work with and around the quirks in the version of the framework/software you chose to use instead of having to re-work around these every time you upgrade and re-factor.
  • Get the core mechanics working version of your game finished as early as possible no matter what it looks like or how bad it is. A crappy, ugly, glitching yet working version of your game is better than a pretty, perfectionist, bug free version of your game that isn’t at all playable. Don’t wait until the last minute or the week before it opens to get feedback on what you’re doing. Feedback is a great way to find issues you hadn’t considered and it will give you an idea of what other people think about your game. After all, no one wants to play a game they don’t think is fun. Don’t ignore constructive criticism even if it’s not what you want to hear. That doesn’t mean you have to change or add anything anyone has ever asked you for — it means that you need to take those things into consideration going forward. See past the reviews that focus on your aesthetics — at least initially — because you can always change and fix those later, core mechanics and gameplay are much harder to tackle once you’ve invested lots of time and energy into them.
  • Your game will NEVER be perfect. You will always be tweaking, adding, adjusting and fine tuning it. Instead of wasting your time doing this early on and ending up with something that isn’t a viable product devote that time to your game after you have something you can put out there. Don’t be a perfectionist, no matter how many bugs you quash and features you add or tweak there will always be another bug or problem coming down the pipeline. Try to prioritize the most important ones and tackle those first. Ultimately you want to get something up and working no matter how good or bad it is and then build upon it from there. Rome wasn’t built in a day so don’t expect your game to be. Get a working version up first and foremost and then add on to it and enhance it over time, your customer base won’t hate you for that, rather the opposite — they’ll appreciate your continued efforts to improve upon what you’ve done so far.

Best Tools To Test Your Website’s Responsiveness

Comment 1 Standard

Since converting my game websites to be fully responsive and use HTML5 I’ve gone through a lot of different responsiveness testing tools. So far these are my favorites:

  1. Web Developer – addon for Firefox. This takes the cake for me because it’s already built into the right click menu on my browser so it’s really easy to invoke whenever and wherever. On top of that it’s designed to show you a number of different responsive views at one time and you can customize the views that it shows when it launches. Of course it comes with a whole host of other nifty tools to aid in your web development so it gets a raving 5 stars from me. It’s not as fully fleshed out in Chrome but there is a Chrome version as well. The only downside to this tool is that if you change something and you want to see an update of your changes you can’t just refresh the screen that pops up in a new tab. Instead you have to close the tab and launch the responsive view from the right click menu. Not a huge bother but it could be improved upon.
  2. http://quirktools.com/screenfly/ – simple, intuitive interface. Just enter your website and you’re well on your way for an easy experience to view your site on phones, tables and even televisions. The downside of this website is that you have to reload it every time you want to check what a different page of your website would look like.
  3. http://ipadpeek.com/ – the ipad and iphone emulator. It looks like an ipad and it does a pretty good job emulating an ipad and iphone — it will even show screen rotations. The only downside to this is that it doesn’t let you change version of the ipad because I believe the newest AIR 2 has a larger screen than the one in this emulator but I could be wrong.
  4. http://www.mobilephoneemulator.com/ – the multi-phone emulator. So this isn’t nearly as easy to use as the item in the number 2 spot which is why it’s bumped down a spot on my list even though it has a much wider array of phones you can test your site on including some of the popular android, htc and samsung phones. Just pick the make and model and enter your website and this site will render it to the proper screen size.
  5. http://ready.mobi/– last but not least. Although this doesn’t rank high in the visual department this is an excellent tool for evaluating what issues your markup may present to mobile users. Things like images exceeding certain file size and dimensions (which make for a slow mobile experience) and how your file sizes will impact your loading times are why this site makes my list. The downside is that it doesn’t visually show you what your responsive site will look like but it takes an analytical approach which is super helpful and informative regardless.

Now it looks like you’re ready to check out these 11 unconventional programming tips to improve your programming skills!

Node JS Tutorial: How To Create A Simple Server

Leave a comment Standard

This will allow you to quickly setup a working node server in just a few easy steps.

1. Install Node.js

For Windows/Linux
Go to http://nodejs.org and download the
latest version of node for the operating system you want to install it on.

Open node and test if it’s working by typing 2+2 and hitting enter.

For Mac OS X
Visit Homebrew and then open your
command line and run (If you’re prompted to install command line tools go ahead and do that). :

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

When that’s done run you can make sure your install was successful by running:

brew doctor

Then it’s a good idea run this to make sure you have the most up to date copy:

brew update

Then install node by running:

brew install node

Test your install by opening a command line and typing this to see the node version:

node -v

2. Install NPM

This package will help you install lots of node related libraries. You can find out more
about it by visiting https://npmjs.org.
Open a command line and type:

npn install express body-parser

If you get an error on Windows that says something along the lines of

Error: ENOENT, stat...

This means the NPM directory is missing from your filesystem. Navigate to where NPM should be as displayed by the error message and create an empty folder called npm.

3. Create These Simple Server Files

First let’s make our index.html. This should go in the directory you want to serve this index file from. So on a server it would be something along the lines of htdocs/public_html/directory/ or var/www/html and on your local computer it should be whatever directory you did your npm install.

Create the index.html file:

<html ng-app="app">
  <head>
    <title>My First Node Server File</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/stylesheet.css">
  </head>
  <body ng-controller="appCtrl">
    <div class="page-header">
      <h1>
        <i class="glyphicon glyphicon-certificate"></i>
        Congratulations!
      </h1>
    </div>
    <section>You have successfully created your first HTML5 node server.</section>
  </body>
  <footer>
    <a href="http://design1online.com" target="_blank">Tutorials by Design1Online.com, LLC</a>
  </footer>
</html>

Now let’s create the server.js file:

'use strict';

// Importing express and body parser libraries
var express = require('express');
var bodyParser = require('body-parser');

//this is a built in node library that handles the file system
var fs = require('fs');


/**
* Server configs
*/

/**
* The port to run your node server on
* 
* If you're running this on a web server this should be 80
* If you're running this locally try 8080 or 9080
*/
var BASE_PORT = 8080;

/** 
* The root directory of your files
*
* By default it uses the current folder this file is in
*/
var ROOT_DIR = __dirname + '/';
ROOT_DIR = fs.realpathSync(ROOT_DIR);
if (!fs.existsSync(ROOT_DIR)) {
	console.log('Error: cannot find working directory: ' + ROOT_DIR);
	exit();
}

/**
* Create an instance of express
*/
var app = express();

/**
 * Adds a simple logging, "mounted" on the root path.
 * Using Express middleware
 **/
app.use(function(req, res, next) {
	console.log('%s %s', req.method, req.url);
	next();
});

/**
 * Allows us to parse http body parameters as json
 **/
app.use(bodyParser.json());

app.use(express.static(ROOT_DIR));

app.listen(BASE_PORT, function() {
	console.log('Node server started @ http://localhost:' + BASE_PORT);
	console.log('Serving static files from ' + ROOT_DIR);
	console.log('Press Ctrl + c for server termination');
});

4. Start the Server

Go to the directory you installed npm in and that your index.html and server.js file reside. This is where you want to start the node server. In the console type:

node server.js

Now open your browser. If you installed node on a server then navigate to your index page on your website. You should see your new node js index file. If you’re running the node server on your local machine then type in http://localhost:BASE_PORT and replace BASE_PORT with the port number you configured in the server.js file. You’ll see your index file in your browser.

Congrats! You’ve successfully create your first node server.

Use Play Testing To Reduce Your Game Development Costs

Leave a comment Standard

What Is Play Testing?

This is a technique where you build a working version of your game and play it before you ever release the game to market. So you may be asking yourself, how does this reduce my game development costs if I need a working version of the game before I can play test it? The answer is simple: create your working game in an inexpensive medium. So what if your marketable game is going to have cutting edge graphics or high poly 3D models or even stunning visual effects that require months of complex mathematics and physics and matrices — with play testing you can see how well your core gameplay and mechanics work (or fail) without any of those expensive bells or whistles and in a lot less time.

How Do I Play Test?

I generally break this down into six steps.

1. Define your core game components, mechanics and boundaries

Start by sitting down and thinking about the core components of your game. How does your game work? How could someone play a physical manifestation of your game?

2. Write the game rules

Now that you know all of the components of the game you’ll need to write up a set of rules. Your play testers will use these so they know how they should play your game. If you can’t identify any rules for your game then you’ve found your first problem — you don’t actually have a game yet and it’s time to go back to the drawing board.

3. Gather your materials

Not all games need materials but you probably will even if it’s as simple as a few pencils and some blank sheets of paper. It’s time to visit a local arts and crafts store and buy whatever you think is necessary for someone to play a simplified version of your game — be creative to keep your costs low (ie use paper balls instead of nerf balls). You will need enough materials for at least one person to play your game. If your game is multiplayer you may need to invest a bit more so you can let multiple people play together.

4. Get lots of people to play your game

This is pretty much self explanatory but it’s also a really deep topic. Other than to say the more people who you can get to play the better, I’ll come back to it later.

5. Analyze your results

You can take a lot away from a play testing session. Did your player(s) struggle understanding the rules or sticking to the rules because they weren’t clearly defined or they didn’t make sense. Did your players pick up the general mechanics and components of the game quickly? Even if you have a negative response to both of these areas don’t panic! This is a good indication that your rules need improvement and that other materials or aids might be required (ie tutorials) before your players can really understand what you’re asking them to do.

6. Finding the fun

Ultimately your play testing session boils down to did your player(s) enjoy themselves? Was it so long and complex that they quickly lost interest or was it so fast paced that they finished almost as soon as they started? Where they laughing and becoming immersed in the experience or growing frustrated and angry? Did they feel sufficiently challenged? Some people find asking their play testers questions about their experience helpful and often times will ask for them to fill out a feedback sheet or a survey when they’re done. Personally I prefer just watching people play. Watching someone play your game will give you a huge amount of feedback and target areas in need of improvement all without breaking the bank. Remember that it’s okay to go back to square one and start again if your play testers don’t have a positive response to your game. The best part about negative feedback is that it just saved you from spending lots of time, energy, resources and money on a game no one thinks is fun.

Who Should Be Play Testing Your Game?

Okay so I kind of glazed over step four because I wanted to devote a whole section to it. I always start play testing with my target audience. Your target audience should be the age range and gender you believe your game will most appeal to. For instance, if I was intending to make a game for young children I would keep in mind their computer skills, the types of devices they are most likely to play on, their hand-eye coordination, their cognitive abilities in understanding themes, stereotypes and story development. Each of these would be adjusted based upon what I expect young children would find fun and amusing — loud silly noises, larger buttons, brighter colors, less text to read and rules introduced slowly and over time to build complexity.

Now your target age range and genders should all be play testers — but so should other groups. Don’t limit yourself to only your target audience or your may miss gaining valuable insight to how people play and interpret your game. Although you may be designing a game for young children you may find that your target audience has missed it’s mark when the young children have only negative responses to your play testing sessions while a different group of play testers find your game the perfect mix of fun and challenging entertainment.

There’s also a matter of size to consider. Even if your game is single player, what happens when you ask two people to play it together? This may (or may not) change your game dynamics for the better or lead you in a completely different direction that ends up becoming something much more successful that what you had to start with. In that same vein, push the limits. What happens if you triple the number of players who are playing at a time? This is especially important for multiplayer games where your play testers end up being on a small segment of the number of players who will ultimately be playing your game. You might suddenly find your calculations for resource management fall short when your player base grows exponentially or that the influx of players completely changes the pace and feel of the game — for good or for bad.

So, What Are The Advantages of Play Testing?

  • Testing early makes it easier to discover and fix problems
  • Increasing and decreasing the number of players at a time can help you find new and interesting perspectives and aspects of your game you had not yet considered improving or expounding upon — and they may be the best features of your game
  • You can work in a controlled environment and see how your games is affected by a specific number of players influences game factors such as economy, resource depletion, or competition.
  • Watching people play will help you areas of the game players find confusing or not challenging enough
  • You can find your true target audience, not what you think or feel your target audience should be
  • Players can give you valuable feedback before the game is put out to market
  • Reduced costs of game development, you won’t have to go back and fix features of the game players don’t like when the game is out to market — you’ve already identified those areas through play testing
  • This gives you the ability to go back to square one at any point in time, and then bring your changes back to your play testing groups until you get it right

Summary

Game development is expensive so do yourself a favor and make sure you’re spending your money on a game that’s going to help you reap the rewards of all your hard work. Play testing is easy and much cheaper than spending your money on a game that’s only going to flop when it hits the market.

Cywgin .bashrc file

Leave a comment Standard

I’ve been working on my .bashrc file so I thought I would share.

# To the extent possible under law, the author(s) have dedicated all 
# copyright and related and neighboring rights to this software to the 
# public domain worldwide. This software is distributed without any warranty. 
# You should have received a copy of the CC0 Public Domain Dedication along 
# with this software. 
# If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. 

# base-files version 4.2-3

# ~/.bashrc: executed by bash(1) for interactive shells.

# The latest version as installed by the Cygwin Setup program can
# always be found at /etc/defaults/etc/skel/.bashrc

# Modifying /etc/skel/.bashrc directly will prevent
# setup from updating it.

# The copy in your home directory (~/.bashrc) is yours, please
# feel free to customise it to create a shell
# environment to your liking.  If you feel a change
# would be benifitial to all, please feel free to send
# a patch to the cygwin mailing list.

# User dependent .bashrc file

# If not running interactively, don't do anything
[[ "$-" != *i* ]] && return

# Shell Options
#
# See man bash for more options...
#
# Don't wait for job termination notification
# set -o notify
#
# Don't use ^D to exit
# set -o ignoreeof
#
# Use case-insensitive filename globbing
# shopt -s nocaseglob
#
# Make bash append rather than overwrite the history on disk
# shopt -s histappend
#
# When changing directory small typos can be ignored by bash
# for example, cd /vr/lgo/apaache would find /var/log/apache
shopt -s cdspell

# Completion options
#
# These completion tuning parameters change the default behavior of bash_completion:
#
# Define to access remotely checked-out files over passwordless ssh for CVS
# COMP_CVS_REMOTE=1
#
# Define to avoid stripping description in --option=description of './configure --help'
# COMP_CONFIGURE_HINTS=1
#
# Define to avoid flattening internal contents of tar files
# COMP_TAR_INTERNAL_PATHS=1
#
# Uncomment to turn on programmable completion enhancements.
# Any completions you add in ~/.bash_completion are sourced last.
# [[ -f /etc/bash_completion ]] && . /etc/bash_completion

# History Options
#
# Don't put duplicate lines in the history.
# export HISTCONTROL=$HISTCONTROL${HISTCONTROL+,}ignoredups
#
# Ignore some controlling instructions
# HISTIGNORE is a colon-delimited list of patterns which should be excluded.
# The '&' is a special pattern which suppresses duplicate entries.
# export HISTIGNORE=$'[ \t]*:&:[fb]g:exit'
# export HISTIGNORE=$'[ \t]*:&:[fb]g:exit:ls' # Ignore the ls command as well
#
# Whenever displaying the prompt, write the previous line to disk
# export PROMPT_COMMAND="history -a"

# Aliases
#
# Some people use a different file for aliases
# if [ -f "${HOME}/.bash_aliases" ]; then
#   source "${HOME}/.bash_aliases"
# fi
#
# Some example alias instructions
# If these are enabled they will be used instead of any instructions
# they may mask.  For example, alias rm='rm -i' will mask the rm
# application.  To override the alias instruction use a \ before, ie
# \rm will call the real rm not the alias.
#
# Interactive operation...
# alias rm='rm -i'
# alias cp='cp -i'
# alias mv='mv -i'
#
# Default to human readable figures
# alias df='df -h'
# alias du='du -h'
#
# Misc :)
# alias less='less -r'                          # raw control characters
# alias whence='type -a'                        # where, of a sort
 alias grep='grep --color'                     # show differences in colour
 alias egrep='egrep --color=auto'              # show differences in colour
 alias fgrep='fgrep --color=auto'              # show differences in colour
#
# Some shortcuts for different directory listings
alias ls='ls -hF --color=tty'                 # classify files in colour
alias dir='ls --color=auto --format=vertical'
alias vdir='ls --color=auto --format=long'
alias ll='ls -l'                              # long list
alias la='ls -A'                              # all but . and ..
# alias l='ls -CF'                              #

# Umask
#
# /etc/profile sets 022, removing write perms to group + others.
# Set a more restrictive umask: i.e. no exec perms for others:
# umask 027
# Paranoid: neither group nor others have any perms:
# umask 077

# Functions
#
# Some people use a different file for functions
# if [ -f "${HOME}/.bash_functions" ]; then
#   source "${HOME}/.bash_functions"
# fi
#
# Some example functions:
#
# a) function settitle
# settitle () 
# { 
#   echo -ne "\e]2;$@\a\e]1;$@\a"; 
# }
# 
# b) function cd_func
# This function defines a 'cd' replacement function capable of keeping, 
# displaying and accessing history of visited directories, up to 10 entries.
# To use it, uncomment it, source this file and try 'cd --'.
# acd_func 1.0.5, 10-nov-2004
# Petar Marinov, http:/geocities.com/h2428, this is public domain
# cd_func ()
# {
#   local x2 the_new_dir adir index
#   local -i cnt
# 
#   if [[ $1 ==  "--" ]]; then
#     dirs -v
#     return 0
#   fi
# 
#   the_new_dir=$1
#   [[ -z $1 ]] && the_new_dir=$HOME
# 
#   if [[ ${the_new_dir:0:1} == '-' ]]; then
#     #
#     # Extract dir N from dirs
#     index=${the_new_dir:1}
#     [[ -z $index ]] && index=1
#     adir=$(dirs +$index)
#     [[ -z $adir ]] && return 1
#     the_new_dir=$adir
#   fi
# 
#   #
#   # '~' has to be substituted by ${HOME}
#   [[ ${the_new_dir:0:1} == '~' ]] && the_new_dir="${HOME}${the_new_dir:1}"
# 
#   #
#   # Now change to the new dir and add to the top of the stack
#   pushd "${the_new_dir}" > /dev/null
#   [[ $? -ne 0 ]] && return 1
#   the_new_dir=$(pwd)
# 
#   #
#   # Trim down everything beyond 11th entry
#   popd -n +11 2>/dev/null 1>/dev/null
# 
#   #
#   # Remove any other occurence of this dir, skipping the top of the stack
#   for ((cnt=1; cnt <= 10; cnt++)); do
#     x2=$(dirs +${cnt} 2>/dev/null)
#     [[ $? -ne 0 ]] && return 0
#     [[ ${x2:0:1} == '~' ]] && x2="${HOME}${x2:1}"
#     if [[ "${x2}" == "${the_new_dir}" ]]; then
#       popd -n +$cnt 2>/dev/null 1>/dev/null
#       cnt=cnt-1
#     fi
#   done
# 
#   return 0
# }
# 
# alias cd=cd_func

#make a directory and cd into it
mkcd() {
    if [ $# != 1 ]; then
        echo "Usage: mkcd <dir>"
    else
        mkdir -p $1 && cd $1
    fi
}

#create a symlink (aka shortcut)
symlink() {
    if [ $# != 1 ]; then
        echo "Usage: symlink <target_path> [link_path]"
    else
        ln -s $1 $2
    fi
}

#how many directories to cd .. through (ie up 4 moves up 4 directories)
up(){
  local d=""
  limit=$1
  for ((i=1 ; i <= limit ; i++))
    do
      d=$d/..
    done
  d=$(echo $d | sed 's/^\///')
  if [ -z "$d" ]; then
    d=..
  fi
  cd $d
}

#extract an archive
extract () {
   if [ -f $1 ] ; then
       case $1 in
           *.tar.bz2)   tar xvjf $1    ;;
           *.tar.gz)    tar xvzf $1    ;;
           *.bz2)       bunzip2 $1     ;;
           *.rar)       unrar x $1       ;;
           *.gz)        gunzip $1      ;;
           *.tar)       tar xvf $1     ;;
           *.tbz2)      tar xvjf $1    ;;
           *.tgz)       tar xvzf $1    ;;
           *.zip)       unzip $1       ;;
           *.Z)         uncompress $1  ;;
           *.7z)        7z x $1        ;;
           *)           echo "don't know how to extract '$1'..." ;;
       esac
   else
       echo "'$1' is not a valid file!"
   fi
 }

#move up directories with periods
alias ..="cd .."
alias ...="cd ../.."
alias ....="cd ../../.."
alias .....="cd ../../../.."

#set command line to colored format user@host:~working/directory $
RESET="\[17\]"
NORMAL="\[33[0m\]"
RED="\[33[31;1m\]"
GREEN="\[33[32;1m\]"
YELLOW="\[33[33;1m\]"
BLUE="\[33[34;1m\]"
MAGENTA="\[33[35;1m\]"
CYAN="\[33[36;1m\]"
WHITE="\[33[37;1m\]"
PS1="${RESET}${RED}\u@${YELLOW}\h${WHITE}:${GREEN}\w ${CYAN}\$${NORMAL} "

#figure out which git branch we're currently on
branch_name=$(git symbolic-ref -q HEAD)
branch_name=${branch_name##refs/heads/}
branch_name=${branch_name:-HEAD}
#shorten git commands
alias gs='git status'
alias gc='git commit'
alias ga='git add'
alias gd='git diff'
alias gb='git branch'
alias gl='git log'
alias gsb='git show-branch'
alias gco='git checkout'
alias gg='git grep'
alias gk='gitk --all'
alias gr='git rebase'
alias gri='git rebase --interactive'
alias gcp='git cherry-pick'
alias grm='git rm'
alias gp='git push'
alias gf='git fetch'
alias gm='git merge'

#switch to the master branch
alias gcom='gco master'

#checkout master branch, pull in changes and then checkout your current branch and merge in those changes
alias gmm='gcom && gp && gco ${branch_name} && gm origin master'
#shows "git diff" across any project in any subdirectory
alias git-differ='for g in $(find . -name ".git"); do g=${g%%.git};printf "$g\t\t\t";pu $g >/dev/null && git diff |wc -l; p >/dev/null; done'

#does git house keeping across any project in any subdirectory
alias git-housekeep='for g in $(find . -name ".git"); do g=${g%%.git};echo $g;pu $g && git repack && git gc --auto && p;done'

# clear the cygwin console
alias clear='printf "33c"'