<commit_before>//
//  GameScene.swift
//  HexMatch
//
//  Created by <NAME> on 1/11/16.
//  Copyright (c) 2016 <NAME>. All rights reserved.
//

import SpriteKit
import CoreData
import SNZSpriteKitUI

class GameScene: SNZScene {
    var gameboardLayer = SKNode()
    var guiLayer = SKNode()
    
    var currentPieceLabel: SKLabelNode?
    var currentPieceHome = CGPointMake(0,0)
    var currentPieceSprite: SKSpriteNode?
    var currentPieceCaption: SKNode?
    
    var stashPieceLabel: SKLabelNode?
    var stashPieceHome = CGPointMake(0,0)
    var stashBox: SKShapeNode?
    
    var menuButton: SNZTextureButtonWidget?
    var undoButton: SNZTextureButtonWidget?
    var gameOverLabel: SKLabelNode?
    var bankButton: BankButtonWidget?
    var stashButton: SNZButtonWidget?
    var currentButton: SNZButtonWidget?
    var statsButton: SNZButtonWidget?
    var highScoreButton: SNZButtonWidget?
    
    var mergingPieces: [HexPiece] = Array()
    var mergedPieces: [HexPiece] = Array()

    var lastPlacedPiece: HexPiece?
    var lastPointsAwarded = 0
    
    var hexMap: HexMap?
    
    var undoState: NSData?
    
    var debugShape: SKShapeNode?
    
    let scoreFormatter = NSNumberFormatter()
    
    var _score = 0
    var score: Int {
        get {
            return self._score
        }
        set {
            self._score = newValue
            self.updateScore()
            
            // Update score in state
            GameState.instance!.score = self._score
            
            // Update high score
            if (self._score > GameState.instance!.highScore) {
                GameState.instance!.highScore = self._score
                self.updateHighScore()
            }
        }
    }
    
    var _bankPoints = 0
    var bankPoints: Int {
        get {
            return self._bankPoints
        }
        set {
            self._bankPoints = newValue
            self.updateBankPoints()
            
            // Update score in state
            GameState.instance!.bankPoints = self._bankPoints
        }
    }
    
    var scoreDisplay: SKLabelNode?
    var scoreLabel: SKLabelNode?
    
    var bankPointsDisplay: SKLabelNode?
    var bankPointsLabel: SKLabelNode?
    
    var highScoreDisplay: SKLabelNode?
    var highScoreLabel: SKLabelNode?
    
    override func didMoveToView(view: SKView) {
        super.didMoveToView(view)
        
        self.updateGuiPositions()
    }
    
    func initGame() {
        // Set background
        self.backgroundColor = UIColor(red: 0x69/255, green: 0x65/255, blue: 0x6f/255, alpha: 1.0)
        
        // Add guiLayer to scene
        addChild(self.guiLayer)
        
        // Get the hex map and render it
        self.renderFromState()
        
        // Generate proxy sprite for current piece
        self.updateCurrentPieceSprite()
        
        // Add gameboardLayer to scene
        addChild(self.gameboardLayer)
        
        // Init bank points
        self.bankPoints = GameState.instance!.bankPoints
        
        // Init guiLayer
        self.initGuiLayer()
        
        // Check to see if we are already out of open cells, and change to end game state if so
        // e.g. in case state was saved during end game.
        if (HexMapHelper.instance.hexMap!.getOpenCells().count==0) {
            GameStateMachine.instance!.enterState(GameSceneGameOverState.self)
        }
    }
    
    func renderFromState() {
        // Init HexMap
        self.hexMap = GameState.instance!.hexMap
        
        // Init score
        self._score = GameState.instance!.score
        
        // Init level
        HexMapHelper.instance.hexMap = self.hexMap!
        
        // Render our hex map to the gameboardLayer
        HexMapHelper.instance.renderHexMap(gameboardLayer);
    }
    
    /**
        Reset game state. This includes clearing current score, stashed piece, current piece, and regenerating hexmap with a new random starting layout.
    */
    func resetLevel() {
        // Remove current piece, stash piece sprites
        self.removeTransientGuiSprites()
    
        // Clear the board
        HexMapHelper.instance.clearHexMap(self.gameboardLayer)
        
        // Clear the hexmap
        self.hexMap?.clear()
        
        // Generate level
        LevelHelper.instance.initLevel(self.hexMap!)
        
        // Generate new current piece
        self.generateCurrentPiece()
        
        // Generate proxy sprite for current piece
        self.updateCurrentPieceSprite()
        
        // Reset buyables
        GameState.instance!.resetBuyablePieces()
        
        // Clear stash
        if (GameState.instance!.stashPiece != nil) {
            if (GameState.instance!.stashPiece!.sprite != nil) {
                GameState.instance!.stashPiece!.sprite!.removeFromParent()
            }
            GameState.instance!.stashPiece = nil
        }
        
        // Render game board
        HexMapHelper.instance.renderHexMap(gameboardLayer);
        
        // Reset score
        self.score = 0
        
        // Clear undo
        self.undoButton!.hidden = true
        self.undoState = nil
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if (self.widgetTouchesBegan(touches, withEvent: event)) {
            return
        }
        
        let location = touches.first?.locationInNode(self)
        
        if (location != nil) {
            let nodes = nodesAtPoint(location!)
         
            for node in nodes {
                if (node.name == "hexMapCell") {
                    let x = node.userData!.valueForKey("hexMapPositionX") as! Int
                    let y = node.userData!.valueForKey("hexMapPositionY") as! Int
                    
                    let cell = HexMapHelper.instance.hexMap!.cell(x,y)
    
                    if (GameState.instance!.currentPiece != nil && GameState.instance!.currentPiece is RemovePiece) {
                        currentPieceSprite!.position = node.position
                    } else
                    if (cell!.willAccept(GameState.instance!.currentPiece!)) {
                        self.updateMergingPieces(cell!)
                        
                        // Move to touched point
                        currentPieceSprite!.removeActionForKey("moveAnimation")
                        currentPieceSprite!.position = node.position
                    }
                }
            }
        }
    }
    
    /**
        Handles touch move events. Updates animations for any pieces which would be merged if the player were to end the touch event in the cell being touched, if any.
    */
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if (self.widgetTouchesMoved(touches, withEvent: event)) {
            return
        }
        
        let location = touches.first?.locationInNode(self)
        
        if (location != nil) {
            let nodes = nodesAtPoint(location!)
         
            for node in nodes {
                if (node.name == "hexMapCell") {
                    let x = node.userData!.valueForKey("hexMapPositionX") as! Int
                    let y = node.userData!.valueForKey("hexMapPositionY") as! Int
                    
                    let cell = HexMapHelper.instance.hexMap!.cell(x,y)
                    
                    if (GameState.instance!.currentPiece != nil && GameState.instance!.currentPiece is RemovePiece) {
                        currentPieceSprite!.position = node.position
                    } else
                    if (cell!.willAccept(GameState.instance!.currentPiece!)) {
                        self.updateMergingPieces(cell!)
                        
                        // Move to touched point
                        currentPieceSprite!.removeActionForKey("moveAnimation")
                        currentPieceSprite!.position = node.position
                    }
                }
            }
        }
        
    }
    
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if (self.widgetTouchesEnded(touches, withEvent: event) || touches.first == nil) {
            return
        }
        
        let location = touches.first?.locationInNode(self)
        
        if ((location != nil) && (GameStateMachine.instance!.currentState is GameScenePlayingState)) {
            for node in self.nodesAtPoint(location!) {
                if (self.nodeWasTouched(node)) {
                    break;
                }
            }
        }
    }
    
    func nodeWasTouched(node: SKNode) -> Bool {
        var handled = false
        
        if (node.name == "hexMapCell") {
            let x = node.userData!.valueForKey("hexMapPositionX") as! Int
            let y = node.userData!.valueForKey("hexMapPositionY") as! Int
            
            let cell = HexMapHelper.instance.hexMap!.cell(x,y)
            
            // Refresh merging pieces
            self.updateMergingPieces(cell!)
            
            // Do we have a Remove piece?
            if (GameState.instance!.currentPiece != nil && GameState.instance!.currentPiece is RemovePiece) {
                // Capture state for undo
                self.captureState()
                
                // Process the removal
                self.playRemovePiece(cell!)
            } else
            // Does the cell contain a collectible hex piece?
            if (cell!.hexPiece != nil && cell!.hexPiece!.isCollectible) {
                // Capture state for undo
                self.captureState()
                
                // Let the piece know it was collected
                cell!.hexPiece!.wasCollected()
                
                // Clear out the hex cell
                cell!.hexPiece = nil
            } else
            // Will the target cell accept our current piece, and will the piece either allow placement
            // without a merge, or if not, do we have a merge?
            if (cell!.willAccept(GameState.instance!.currentPiece!) && (GameState.instance!.currentPiece!.canPlaceWithoutMerge() || self.mergingPieces.count>0)) {
                // Capture state for undo
                self.captureState()
            
                // Store last placed piece, prior to any merging
                GameState.instance!.lastPlacedPiece = GameState.instance!.currentPiece

                // Place the current piece
                self.placeCurrentPiece(cell!)
            }
            
            handled = true
        }
        
        return handled
    }
    
    func handleMerge(cell: HexCell) {
        // Are we merging pieces?
        if (self.mergingPieces.count>0) {
            var maxValue = 0
            
            // Remove animations from merging pieces, and find the maximum value
            for hexPiece in self.mergingPieces {
                hexPiece.sprite!.removeActionForKey("mergeAnimation")
                hexPiece.sprite!.setScale(1.0)
                if (hexPiece.value > maxValue) {
                    maxValue = hexPiece.value
                }
            }
            
            // Let piece know it was placed w/ merge
            GameState.instance!.currentPiece = GameState.instance!.currentPiece!.wasPlacedWithMerge(maxValue)
            
            // Store merged pieces, if any
            self.mergedPieces = self.mergingPieces
            
            // Create merge animation
            let moveAction = SKAction.moveTo(HexMapHelper.instance.hexMapToScreen(cell.position), duration: 0.15)
            let moveSequence = SKAction.sequence([moveAction, SKAction.removeFromParent()])
            
            // Remove merged pieces from board
            for hexPiece in self.mergingPieces {
                hexPiece.sprite!.runAction(moveSequence)
                hexPiece.hexCell?.hexPiece = nil
            }
        } else {
            // clear merged array, since we are not merging any on this placement
            self.mergedPieces.removeAll()
            
            // let piece know we are placing it
            GameState.instance!.currentPiece!.wasPlacedWithoutMerge()
        }
    }
    
    func placeCurrentPiece(cell: HexCell) {
        // Handle merging, if any
        self.handleMerge(cell)
    
        // Place the piece
        cell.hexPiece = GameState.instance!.currentPiece
        
        // Record statistic
        GameStats.instance!.incIntForKey(cell.hexPiece!.getStatsKey())
        
        // Move sprite from GUI to gameboard layer
        GameState.instance!.currentPiece!.sprite!.moveToParent(self.gameboardLayer)
        
        // Position on gameboard
        GameState.instance!.currentPiece!.sprite!.position = HexMapHelper.instance.hexMapToScreen(cell.position)
        
        // Award points
        self.awardPointsForPiece(GameState.instance!.currentPiece!)
        self.scrollPoints(self.lastPointsAwarded, position: GameState.instance!.currentPiece!.sprite!.position)
        
        // Generate new piece
        self.generateCurrentPiece()
        
        // Update current piece sprite
        self.updateCurrentPieceSprite()<commit_msg>touchesMoved was functionally identical to touchesBegan, so removed and replaced w/ a call. Also removed unneeded call to self.mergedPieces.removeAll(), and added comments.<commit_after>//
//  GameScene.swift
//  HexMatch
//
//  Created by <NAME> on 1/11/16.
//  Copyright (c) 2016 <NAME>. All rights reserved.
//

import SpriteKit
import CoreData
import SNZSpriteKitUI

class GameScene: SNZScene {
    var gameboardLayer = SKNode()
    var guiLayer = SKNode()
    
    var currentPieceLabel: SKLabelNode?
    var currentPieceHome = CGPointMake(0,0)
    var currentPieceSprite: SKSpriteNode?
    var currentPieceCaption: SKNode?
    
    var stashPieceLabel: SKLabelNode?
    var stashPieceHome = CGPointMake(0,0)
    var stashBox: SKShapeNode?
    
    var menuButton: SNZTextureButtonWidget?
    var undoButton: SNZTextureButtonWidget?
    var gameOverLabel: SKLabelNode?
    var bankButton: BankButtonWidget?
    var stashButton: SNZButtonWidget?
    var currentButton: SNZButtonWidget?
    var statsButton: SNZButtonWidget?
    var highScoreButton: SNZButtonWidget?
    
    var mergingPieces: [HexPiece] = Array()
    var mergedPieces: [HexPiece] = Array()

    var lastPlacedPiece: HexPiece?
    var lastPointsAwarded = 0
    
    var hexMap: HexMap?
    
    var undoState: NSData?
    
    var debugShape: SKShapeNode?
    
    let scoreFormatter = NSNumberFormatter()
    
    var _score = 0
    var score: Int {
        get {
            return self._score
        }
        set {
            self._score = newValue
            self.updateScore()
            
            // Update score in state
            GameState.instance!.score = self._score
            
            // Update high score
            if (self._score > GameState.instance!.highScore) {
                GameState.instance!.highScore = self._score
                self.updateHighScore()
            }
        }
    }
    
    var _bankPoints = 0
    var bankPoints: Int {
        get {
            return self._bankPoints
        }
        set {
            self._bankPoints = newValue
            self.updateBankPoints()
            
            // Update score in state
            GameState.instance!.bankPoints = self._bankPoints
        }
    }
    
    var scoreDisplay: SKLabelNode?
    var scoreLabel: SKLabelNode?
    
    var bankPointsDisplay: SKLabelNode?
    var bankPointsLabel: SKLabelNode?
    
    var highScoreDisplay: SKLabelNode?
    var highScoreLabel: SKLabelNode?
    
    override func didMoveToView(view: SKView) {
        super.didMoveToView(view)
        
        self.updateGuiPositions()
    }
    
    func initGame() {
        // Set background
        self.backgroundColor = UIColor(red: 0x69/255, green: 0x65/255, blue: 0x6f/255, alpha: 1.0)
        
        // Add guiLayer to scene
        addChild(self.guiLayer)
        
        // Get the hex map and render it
        self.renderFromState()
        
        // Generate proxy sprite for current piece
        self.updateCurrentPieceSprite()
        
        // Add gameboardLayer to scene
        addChild(self.gameboardLayer)
        
        // Init bank points
        self.bankPoints = GameState.instance!.bankPoints
        
        // Init guiLayer
        self.initGuiLayer()
        
        // Check to see if we are already out of open cells, and change to end game state if so
        // e.g. in case state was saved during end game.
        if (HexMapHelper.instance.hexMap!.getOpenCells().count==0) {
            GameStateMachine.instance!.enterState(GameSceneGameOverState.self)
        }
    }
    
    func renderFromState() {
        // Init HexMap
        self.hexMap = GameState.instance!.hexMap
        
        // Init score
        self._score = GameState.instance!.score
        
        // Init level
        HexMapHelper.instance.hexMap = self.hexMap!
        
        // Render our hex map to the gameboardLayer
        HexMapHelper.instance.renderHexMap(gameboardLayer);
    }
    
    /**
        Reset game state. This includes clearing current score, stashed piece, current piece, and regenerating hexmap with a new random starting layout.
    */
    func resetLevel() {
        // Remove current piece, stash piece sprites
        self.removeTransientGuiSprites()
    
        // Clear the board
        HexMapHelper.instance.clearHexMap(self.gameboardLayer)
        
        // Clear the hexmap
        self.hexMap?.clear()
        
        // Generate level
        LevelHelper.instance.initLevel(self.hexMap!)
        
        // Generate new current piece
        self.generateCurrentPiece()
        
        // Generate proxy sprite for current piece
        self.updateCurrentPieceSprite()
        
        // Reset buyables
        GameState.instance!.resetBuyablePieces()
        
        // Clear stash
        if (GameState.instance!.stashPiece != nil) {
            if (GameState.instance!.stashPiece!.sprite != nil) {
                GameState.instance!.stashPiece!.sprite!.removeFromParent()
            }
            GameState.instance!.stashPiece = nil
        }
        
        // Render game board
        HexMapHelper.instance.renderHexMap(gameboardLayer);
        
        // Reset score
        self.score = 0
        
        // Clear undo
        self.undoButton!.hidden = true
        self.undoState = nil
    }
    
    /**
        Handles touch begin and move events. Updates animations for any pieces which would be merged if the player were to end the touch event in the cell being touched, if any.
    */
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if (self.widgetTouchesBegan(touches, withEvent: event)) {
            return
        }
        
        let location = touches.first?.locationInNode(self)
        
        if (location != nil) {
            let nodes = nodesAtPoint(location!)
         
            for node in nodes {
                if (node.name == "hexMapCell") {
                    // Get cell using stord position from node's user data
                    let x = node.userData!.valueForKey("hexMapPositionX") as! Int
                    let y = node.userData!.valueForKey("hexMapPositionY") as! Int
                    
                    let cell = HexMapHelper.instance.hexMap!.cell(x,y)
    
                    // If we have a Remove piece, move it to the target cell regardless of contents
                    if (GameState.instance!.currentPiece != nil && GameState.instance!.currentPiece is RemovePiece) {
                        currentPieceSprite!.position = node.position
                    } else
                    // Otherwise, check to see if the cell will accept the piece
                    if (cell!.willAccept(GameState.instance!.currentPiece!)) {
                        self.updateMergingPieces(cell!)
                        
                        // Move to touched point
                        currentPieceSprite!.removeActionForKey("moveAnimation")
                        currentPieceSprite!.position = node.position
                    }
                }
            }
        }
    }
    
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.touchesBegan(touches, withEvent: event)
    }
    
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if (self.widgetTouchesEnded(touches, withEvent: event) || touches.first == nil) {
            return
        }
        
        let location = touches.first?.locationInNode(self)
        
        if ((location != nil) && (GameStateMachine.instance!.currentState is GameScenePlayingState)) {
            for node in self.nodesAtPoint(location!) {
                if (self.nodeWasTouched(node)) {
                    break;
                }
            }
        }
    }
    
    /**
     
        Handle a node being touched. Place piece, merge, collect, etc.
     
    */
    func nodeWasTouched(node: SKNode) -> Bool {
        var handled = false
        
        if (node.name == "hexMapCell") {
            let x = node.userData!.valueForKey("hexMapPositionX") as! Int
            let y = node.userData!.valueForKey("hexMapPositionY") as! Int
            
            let cell = HexMapHelper.instance.hexMap!.cell(x,y)
            
            // Refresh merging pieces
            self.updateMergingPieces(cell!)
            
            // Do we have a Remove piece?
            if (GameState.instance!.currentPiece != nil && GameState.instance!.currentPiece is RemovePiece) {
                // Capture state for undo
                self.captureState()
                
                // Process the removal
                self.playRemovePiece(cell!)
            } else
            // Does the cell contain a collectible hex piece?
            if (cell!.hexPiece != nil && cell!.hexPiece!.isCollectible) {
                // Capture state for undo
                self.captureState()
                
                // Let the piece know it was collected
                cell!.hexPiece!.wasCollected()
                
                // Clear out the hex cell
                cell!.hexPiece = nil
            } else
            // Will the target cell accept our current piece, and will the piece either allow placement
            // without a merge, or if not, do we have a merge?
            if (cell!.willAccept(GameState.instance!.currentPiece!) && (GameState.instance!.currentPiece!.canPlaceWithoutMerge() || self.mergingPieces.count>0)) {
                // Capture state for undo
                self.captureState()
            
                // Store last placed piece, prior to any merging
                GameState.instance!.lastPlacedPiece = GameState.instance!.currentPiece

                // Place the current piece
                self.placeCurrentPiece(cell!)
            }
            
            handled = true
        }
        
        return handled
    }
    
    /**
        
        Handle the merging of pieces
     
    */
    func handleMerge(cell: HexCell) {
        // Are we merging pieces?
        if (self.mergingPieces.count>0) {
            var maxValue = 0
            
            // Remove animations from merging pieces, and find the maximum value
            for hexPiece in self.mergingPieces {
                hexPiece.sprite!.removeActionForKey("mergeAnimation")
                hexPiece.sprite!.setScale(1.0)
                if (hexPiece.value > maxValue) {
                    maxValue = hexPiece.value
                }
            }
            
            // Let piece know it was placed w/ merge
            GameState.instance!.currentPiece = GameState.instance!.currentPiece!.wasPlacedWithMerge(maxValue)
            
            // Store merged pieces, if any
            self.mergedPieces = self.mergingPieces
            
            // Create merge animation
            let moveAction = SKAction.moveTo(HexMapHelper.instance.hexMapToScreen(cell.position), duration: 0.15)
            let moveSequence = SKAction.sequence([moveAction, SKAction.removeFromParent()])
            
            // Remove merged pieces from board
            for hexPiece in self.mergingPieces {
                hexPiece.sprite!.runAction(moveSequence)
                hexPiece.hexCell?.hexPiece = nil
            }
        } else {
            // let piece know we are placing it
            GameState.instance!.currentPiece!.wasPlacedWithoutMerge()
        }
    }
    
    func placeCurrentPiece(cell: HexCell) {
        // Handle merging, if any
        self.handleMerge(cell)
    
        // Place the piece
        cell.hexPiece = GameState.instance!.currentPiece
        
        // Record statistic
        GameStats.instance!.incIntForKey(cell.hexPiece!.getStatsKey())
        
        // Move sprite from GUI to gameboard layer
        GameState.instance!.currentPiece!.sprite!.moveToParent(self.gameboardLayer)
        
        // Position on gameboard
        GameState.instance!.currentPiece!.sprite!.position = HexMapHelper.instance.hexMapToScreen(cell.position)
        
        // Award points
        self.awardPointsForPiece(GameState.instance!.currentPiece!)
        self.scrollPoints(self.lastPointsAwarded, position: GameState.instance!.currentPiece!.sprite!.position)
        
        // Generate new piece
        self.generateCurrentPiece()
        
        // Update current piece sprite
        self.updateCurrentPieceSprite()
{'fraction_non_alphanumeric': 0.08142523364485982, 'fraction_numerical': 0.0035046728971962616, 'mean_word_length': 1.620777630370446, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1661410', 'n_tokens_mistral': 7033, 'n_tokens_neox': 6648, 'n_words': 1623}