[Introduction to Swift Combat] teach you to write 2048 (a)

Source: Internet
Author: User

Apple equipment is becoming more and more popular, holding a cell phone want to beat the drums, and then have this series, will step by step teach you to learn swift programming, learn to do their own App,github address: Https://github.com/scarlettbai/2048.git.

This article requires you to understand some of the basic swift syntax. It's a practice-oriented place where you don't talk too much about basic grammar. Do not understand that everyone can Google, the swift development environment is also very easy, directly on the Mac to install a Xcode can be, first of all we look at the results we want to achieve:

Of course, you can also change the numbers in the text to your female votes on the phone, but also to give a small surprise, the effect such as the following:

From being able to see it. Finally the effect is actually mainly divided into scoreboard and game panel. The game panel is a background and a lot of small pieces, the middle of the small pieces of space. Today, we will teach you to write the game panel first.

First create a new swiftproject. There's not much to say here. Then create a new file Numbertailgamecontroller.swift. This file mainly deals with logic such as the initialization of the game.

Create a new Numbertailgamecontroller class to inherit the Uiviewcontroller, including for example the following properties:

class  Numbertailgamecontroller: Uiviewcontroller {var  demension:int // 2048 the number of blocks per row in a game  var  threshold:int //highest score, If you win or lose, you will not use it today. Reserved  let  boardwidth:cgfloat = 260.0  //the length and height of the game area  let  thinpadding:cgfloat = 3.0  //the spacing between small blocks inside the game area  let  Viewpadding:cgfloat = 10.0  //scoreboard and game chunk spacing  let  verticalviewoffset:cgfloat = 0.0  //an initialization property, and there will be a place for } 

Next, add the Init method to Numbertailgamecontroller.

init(demension d : Int , threshold t : Int) {    22 : d    88 : t    super.initnilnil)    view.backgroundColorUIColor0xE6/2550xE2/2550xD4/2551)}

Here is mainly limited to a minimum of two blocks and a minimum score of 8 points, in addition to set the entire panel background color, about the color, we can take their favorite color and directly replace the above hexadecimal value can be.

Next we add a Start Game button to the Main.storyboard and then add the following response in the default Viewcontroller.swift, for example:

@IBAction func setupGame(sender:UIButton) {    NumbertailGameController(demension:4threshold:2048)    selfanimated:truecompletion:nil)}

Then we click on the execution in Xcode. You can see the effect, click Start Game, effects such as the following:

You can see here the background color for us to set the background color of the view, the following we come to join the game block:

New Gamebordview.swift file, this file is the view file of our game block. Add the following code to the file, for example:

Import Uikitclass Gamebordview:UIView{var demension:intnumber of blocks per row (column)var tilewidth:CGFloat  //width of each small piecevar tilepadding:CGFloat  //spacing between each small block    //Initialize, in which backgroundcolor is the background color of the game block. Foregroundcolor is a small piece of colorInit (demension d:int, titlewidth width:CGFloat, titlepadding padding:CGFloat, BackgroundColor:Uicolor, Foregroundcolor:Uicolor) {demension = d tilewidth = width tilepadding = padding let totalWidth = tilepadding +CGFloat(demension) * (tilepadding + tilewidth)Super. Init(Frame:cgrectmake (0,0, TotalWidth, TotalWidth)) Self. BackgroundColor= BackgroundColor}}

Here we create a template for a game block, and next we add the following code to initialize a game block object in the game's host controller Numbertailgamecontroller, and add it to our panel:

Override Func Viewdidload () {Super. Viewdidload() Setupgame ()}func setupgame () {Let viewwidth = view. Bounds. Size. WidthLet Viewheight = view. Bounds. Size. HeightGet the top left corner of the game area.xcoordinate func xposition2center (view v:uiview), cgfloat{let vwidth = V. Bounds. Size. WidthReturn0.5* (Viewwidth-vwidth)}//Get the upper left corner of the game areaycoordinates func yposition2center (order:int, Views: [UIView])-cgfloat {assert (views. Count>0) Let Totalviewheigth = cgfloat (views. Count-1) *viewpadding + views. Map({$0.Bounds. Size. Height}). Reduce(Verticalviewoffset, combine: {$0+ $1}) Let Firsty =0.5* (viewheight-totalviewheigth) var acc:cgfloat =0For Iinch 0.. <order{ACC + = viewpadding + views[i]. Bounds. Size. Height} return ACC + firsty}//Gets the edge length of each chunk, i.e.: (game chunk length-gap sum)/block number let width = (boardwidth-thinpadding*cgfloat (DE Mension +1))/cgfloat (demension)//Initialize a game block object let Gamebord = Gamebordview (demension:demension, Titlewidth:wi DTH, titlepadding:thinpadding, Backgroundcolor:uicolor (red:0x90/255, Green:0x8d/255, Blue:0x80/255, Alpha:1), Foregroundcolor:uicolor (red:0xf9/255, Green:0xf9/255, Blue:0xe3/255, Alpha:0.5) and//All view objects in the panel today. There are only game blocks at the moment, maybe adding a scoreboard let's views = [Gamebord]//Set the absolute position of the game block in the entire panel. That is, the first point in the upper-left corner var f = Gamebord. FrameF. Origin. x= Xposition2center (View:gamebord) F. Origin. Y= Yposition2center (0, views:views) Gamebord. Frame= f//Add the game object to the current panel view. Addsubview(Gamebord)}

The gaze in the above code is already very specific. Everyone may be questioned is the x and Y coordinates of the calculation, the x-coordinate is very easy, in fact, is: The total width of the current panel minus the width of the game block, the rest is the width of the spare, divided by 2 is the X-point coordinates . The y-coordinate is slightly more complicated, so the scoring panel will be added later, so his value should be: The total height of the current panel minus the total height of all views divided by 2 and then the total height of the view before the game block is added, is the y-coordinate value of the game area .

Other places are very easy, among the Foregroundcolor is the gaze, is the following to the game block to add the default small box when the color.
Let's do a look at the effect:

Can see the Panel has already, next we want to add to the panel to initialize the translucent small square, we add in the Gamebordview such as the following method:

Func setcolor (backgroundcolor bgcolor:Uicolor, Foregroundcolor ForeColor:Uicolor){ Self. BackgroundColor= bgcolor var xcursor = tilepadding var ycursor:CGFloat     for_ In0.. <demension{Ycursor = tilepadding for_ In0.. <demension {Let tileframe =UIView(Frame:CGRect(X:xcursor, Y:ycursor, Width:tilewidth, Height:tilewidth)) Tileframe. BackgroundColor= ForeColor Tileframe. Layer. Cornerradius=8Addsubview (tileframe) Ycursor + = tilepadding + tilewidth} xcursor + = tilepadding + tilewidth }}

In fact, this method adds a small chunk of demension*demension to the game block. The color of every little piece is our incoming Foregroundcolor
To perform the following look:

Can see the basic game panel has already had, today first said here. You can try to join the scoreboard yourself, and of course I will.

My blog: blog.scarlettbai.com
My public number: Reading fitness program
Welcome to sweep code Follow my public number view many other articles

[Introduction to Swift Combat] teach you to write 2048 (a)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.