diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..c660d25 Binary files /dev/null and b/.DS_Store differ diff --git a/lesson8/.DS_Store b/lesson8/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/lesson8/.DS_Store differ diff --git a/lesson8/Actions.sks b/lesson8/Actions.sks new file mode 100644 index 0000000..0530520 Binary files /dev/null and b/lesson8/Actions.sks differ diff --git a/lesson8/AppDelegate.swift b/lesson8/AppDelegate.swift new file mode 100644 index 0000000..40da84e --- /dev/null +++ b/lesson8/AppDelegate.swift @@ -0,0 +1,41 @@ +// +// AppDelegate.swift +// lesson8 +// +// Created by Vladislav Elkin on 07.08.2020. +// Copyright © 2020 Vladislav Elkin. All rights reserved. +// + +import UIKit + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + // Override point for customization after application launch. + return true + } + + func applicationWillResignActive(_ application: UIApplication) { + // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. + } + + func applicationDidEnterBackground(_ application: UIApplication) { + // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + } + + func applicationWillEnterForeground(_ application: UIApplication) { + // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. + } + + func applicationDidBecomeActive(_ application: UIApplication) { + // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + } + + +} + diff --git a/lesson8/Assets.xcassets/AppIcon.appiconset/Contents.json b/lesson8/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..9221b9b --- /dev/null +++ b/lesson8/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,98 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "20x20" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "20x20" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "29x29" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "29x29" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "40x40" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "40x40" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "60x60" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "60x60" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "20x20" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "20x20" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "29x29" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "29x29" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "40x40" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "40x40" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "76x76" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "76x76" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "83.5x83.5" + }, + { + "idiom" : "ios-marketing", + "scale" : "1x", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/lesson8/Assets.xcassets/Contents.json b/lesson8/Assets.xcassets/Contents.json new file mode 100644 index 0000000..73c0059 --- /dev/null +++ b/lesson8/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/lesson8/Base.lproj/LaunchScreen.storyboard b/lesson8/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..865e932 --- /dev/null +++ b/lesson8/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lesson8/Base.lproj/Main.storyboard b/lesson8/Base.lproj/Main.storyboard new file mode 100644 index 0000000..2cc971a --- /dev/null +++ b/lesson8/Base.lproj/Main.storyboard @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lesson8/GameScene.sks b/lesson8/GameScene.sks new file mode 100644 index 0000000..4fe4d9f Binary files /dev/null and b/lesson8/GameScene.sks differ diff --git a/lesson8/GameScene.swift b/lesson8/GameScene.swift new file mode 100644 index 0000000..1c41c2e --- /dev/null +++ b/lesson8/GameScene.swift @@ -0,0 +1,187 @@ +// +// GameScene.swift +// lesson8 +// +// Created by Vladislav Elkin on 07.08.2020. +// Copyright © 2020 Vladislav Elkin. All rights reserved. +// + +import SpriteKit +import GameplayKit + +class GameScene: SKScene { + // наша змея + var snake: Snake? + + // вызывается при первом запуске сцены + override func didMove(to view: SKView) { + // цвет фона сцены + backgroundColor = SKColor.black + // вектор и сила гравитации + self.physicsWorld.gravity = CGVector(dx: 0, dy: 0) + // добавляем поддержку физики + self.physicsBody = SKPhysicsBody(edgeLoopFrom: frame) + // выключаем внешние воздействия на игру + self.physicsBody?.allowsRotation = false + // включаем отображение отладочной информации + view.showsPhysics = true + // поворот против часовой стрелки + // создаем ноду(объект) + + setupButton() + + self.physicsWorld.contactDelegate = self + // устанавливаем категорию взаимодействия с другими объектами + self.physicsBody?.categoryBitMask = CollisionCategories.EdgeBody + // устанавливаем категории, с которыми будут пересекаться края сцены + self.physicsBody?.collisionBitMask = CollisionCategories.Snake | CollisionCategories.SnakeHead + + + createApple() + + // создаем змею по центру экрана и добавляем ее на сцену + snake = Snake(atPoint: CGPoint(x: view.scene!.frame.midX, y: view.scene!.frame.midY)) + self.addChild(snake!) + + + } + + private func setupButton() { + let counterClockwiseButton = SKShapeNode() + // задаем форму круга + counterClockwiseButton.path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 45, height: 45)).cgPath + // указываем координаты размещения + counterClockwiseButton.position = CGPoint(x: self.scene!.frame.minX+30, y: self.scene!.frame.minY+30) + // цвет заливки + counterClockwiseButton.fillColor = UIColor.gray + // цвет рамки + counterClockwiseButton.strokeColor = UIColor.gray + // толщина рамки + counterClockwiseButton.lineWidth = 10 + // имя объекта для взаимодействия + counterClockwiseButton.name = "counterClockwiseButton" + // Добавляем на сцену + self.addChild(counterClockwiseButton) + // Поворот по часовой стрелке + let clockwiseButton = SKShapeNode() + clockwiseButton.path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 45, height: 45)).cgPath + clockwiseButton.position = CGPoint(x: self.scene!.frame.maxX-80, y: self.scene!.frame.minY+30) + clockwiseButton.fillColor = UIColor.gray + clockwiseButton.strokeColor = UIColor.gray + clockwiseButton.lineWidth = 10 + clockwiseButton.name = "clockwiseButton" + self.addChild(clockwiseButton) + } + + // вызывается при нажатии на экран + override func touchesBegan(_ touches: Set, with event: UIEvent?) { + // перебираем все точки, куда прикоснулся палец + for touch in touches { + // определяем координаты касания для точки + let touchLocation = touch.location(in: self) + // проверяем, есть ли объект по этим координатам, и если есть, то не наша ли это кнопка + guard let touchedNode = self.atPoint(touchLocation) as? SKShapeNode, + touchedNode.name == "counterClockwiseButton" || touchedNode.name == "clockwiseButton" else { + return + } + // если это наша кнопка, заливаем ее зеленым + touchedNode.fillColor = .green + + + if touchedNode.name == "counterClockwiseButton" { + snake!.moveCounterClockwise() + } else if touchedNode.name == "clockwiseButton" { + snake!.moveClockwise() + } + } + + } + // вызывается при прекращении нажатия на экран + override func touchesEnded(_ touches: Set, with event: UIEvent?) { + // повторяем все то же самое для действия, когда палец отрывается от экрана + for touch in touches { + let touchLocation = touch.location(in: self) + + guard let touchedNode = self.atPoint(touchLocation) as? SKShapeNode, + touchedNode.name == "counterClockwiseButton" || touchedNode.name == "clockwiseButton" else { + return + } + // но делаем цвет снова серым + touchedNode.fillColor = UIColor.gray + } + + } + // вызывается при обрыве нажатия на экран, например, если телефон примет звонок и свернет приложение + override func touchesCancelled(_ touches: Set, with event: UIEvent?) { + } + // вызывается при обработке кадров сцены + override func update(_ currentTime: TimeInterval) { + snake?.move() + } + + private func gameOver() { + snake = nil + self.removeAllChildren() + reStart() + + } + + private func reStart(){ + setupButton() + + snake = Snake(atPoint: CGPoint(x: self.scene!.frame.midX, y: self.scene!.frame.midY)) + self.addChild(snake!) + + createApple() + } + + + func createApple(){ + // Случайная точка на экране + let randX = CGFloat(arc4random_uniform(UInt32(view!.scene!.frame.maxX-5)) + 1) + let randY = CGFloat(arc4random_uniform(UInt32(view!.scene!.frame.maxY-5)) + 1) + // Создаем яблоко + let apple = Apple(position: CGPoint(x: randX, y: randY)) + // Добавляем яблоко на сцену + self.addChild(apple) + } + +} + +extension GameScene: SKPhysicsContactDelegate { +// Добавляем метод отслеживания начала столкновения + func didBegin(_ contact: SKPhysicsContact) { + // логическая сумма масок соприкоснувшихся объектов + let bodyes = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask + // вычитаем из суммы голову змеи, и у нас остается маска второго объекта + let collisionObject = bodyes ^ CollisionCategories.SnakeHead + // проверяем, что это за второй объект + switch collisionObject { + case CollisionCategories.Apple: // проверяем, что это яблоко + // яблоко – это один из двух объектов, которые соприкоснулись. Используем тернарный оператор, чтобы вычислить, какой именно + let apple = contact.bodyA.node is Apple ? contact.bodyA.node : contact.bodyB.node + // добавляем к змее еще одну секцию + snake?.addBodyPart() + // удаляем съеденное яблоко со сцены + apple?.removeFromParent() + // создаем новое яблоко + createApple() + case CollisionCategories.EdgeBody: // проверяем, что это стенка экрана + gameOver() // соприкосновение со стеной будет домашним заданием + default: + break + } + } +} + +// Категория пересечения объектов +struct CollisionCategories { +// Тело змеи + static let Snake: UInt32 = 0x1 << 0 +// Голова змеи + static let SnakeHead: UInt32 = 0x1 << 1 +// Яблоко + static let Apple: UInt32 = 0x1 << 2 +// Край сцены (экрана) + static let EdgeBody: UInt32 = 0x1 << 3 +} diff --git a/lesson8/GameViewController.swift b/lesson8/GameViewController.swift new file mode 100644 index 0000000..e68e21b --- /dev/null +++ b/lesson8/GameViewController.swift @@ -0,0 +1,49 @@ +// +// GameViewController.swift +// lesson8 +// +// Created by Vladislav Elkin on 07.08.2020. +// Copyright © 2020 Vladislav Elkin. All rights reserved. +// + +import UIKit +import SpriteKit +import GameplayKit + +class GameViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + + let scene = GameScene(size: view.bounds.size) + // получаем главную область экрана + let skView = view as! SKView + // включаем отображение fps (количество кадров в секунду) + skView.showsFPS = true + // показывать количество объектов на экране + skView.showsNodeCount = true + // включаем произвольный порядок рендеринга объектов в узле + skView.ignoresSiblingOrder = true + // режим отображения сцены, растягивается на все доступное пространство + scene.scaleMode = .resizeFill + // добавляем сцену на экран + skView.presentScene(scene) + + } + + override var shouldAutorotate: Bool { + return true + } + + override var supportedInterfaceOrientations: UIInterfaceOrientationMask { + if UIDevice.current.userInterfaceIdiom == .phone { + return .allButUpsideDown + } else { + return .all + } + } + + override var prefersStatusBarHidden: Bool { + return true + } +} diff --git a/lesson8/Info.plist b/lesson8/Info.plist new file mode 100644 index 0000000..870f784 --- /dev/null +++ b/lesson8/Info.plist @@ -0,0 +1,47 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UIStatusBarHidden + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/lesson8/Snake.swift b/lesson8/Snake.swift new file mode 100644 index 0000000..cae1f35 --- /dev/null +++ b/lesson8/Snake.swift @@ -0,0 +1,78 @@ +import UIKit +import SpriteKit +// сама змейка +class Snake: SKShapeNode { +// массив, где хранятся сегменты тела + var body = [SnakeBodyPart]() + // скорость перемещения + var moveSpeed = 125.0 + // угол, необходимый для расчета направления + var angle: CGFloat = 0.0 +// конструктор + convenience init(atPoint point: CGPoint) { + self.init() +// змейка начинается с головы, создадим ее + let head = SnakeHead(atPoint: point) +// и добавим в массив + body.append(head) +// и сделаем ее дочерним объектом. + addChild(head) + } +// метод добавляет еще один сегмент тела + func addBodyPart(){ + moveSpeed+=5 +// инстанцируем сегмент + let newBodyPart = SnakeBodyPart(atPoint: CGPoint(x: body[0].position.x, y: body[0].position.y)) +// добавляем его в массив + body.append(newBodyPart) +// делаем дочерним объектом + addChild(newBodyPart) + } + + + + // перемещаем змейку + func move(){ + // если у змейки нет головы, ничего не перемещаем + guard !body.isEmpty else { return } + // перемещаем голову + let head = body[0] + moveHead(head) + // перемещаем все сегменты тела + for index in (0.. 0 { + let previousBodyPart = body[index-1] + let currentBodyPart = body[index] + moveBodyPart(previousBodyPart, c: currentBodyPart) + } + } + // перемещаем голову + func moveHead(_ head: SnakeBodyPart){ + // рассчитываем смещение точки + let dx = CGFloat(moveSpeed) * sin(angle); + let dy = CGFloat(moveSpeed) * cos(angle); + // смещаем точку назначения головы + let nextPosition = CGPoint(x: head.position.x + dx, y: head.position.y + dy) + // действие перемещения головы + let moveAction = SKAction.move(to: nextPosition, duration: 1.0) + // запуск действия перемещения + head.run(moveAction) + } + // перемещаем сегмент змеи + func moveBodyPart(_ p: SnakeBodyPart, c: SnakeBodyPart){ + // перемещаем текущий элемент к предыдущему + let moveAction = SKAction.move(to: CGPoint(x: p.position.x, y: p.position.y), duration: 0.1 ) + // запуск действия перемещения + c.run(moveAction) + } + + // поворот по часовой стрелке + func moveClockwise(){ + // смещаем угол на 45 градусов + angle += CGFloat(Double.pi/2) + } + // поворот против часовой стрелки + func moveCounterClockwise(){ + angle -= CGFloat(Double.pi/2) + } + +} diff --git a/lesson8/SnakeBodyPart.swift b/lesson8/SnakeBodyPart.swift new file mode 100644 index 0000000..7277066 --- /dev/null +++ b/lesson8/SnakeBodyPart.swift @@ -0,0 +1,29 @@ +import UIKit +import SpriteKit +class SnakeBodyPart: SKShapeNode { + let diameter = 10.0 + // добавляем конструктор + init (atPoint point: CGPoint){ + super.init() + // рисуем круглый элемент + path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: CGFloat(diameter), height: CGFloat(diameter))).cgPath + // цвет рамки и заливки зеленый + fillColor = UIColor.green + strokeColor = UIColor.green + // ширина рамки 5 поинтов + lineWidth = 5 + // размещаем элемент в переданной точке + self.position = point + + self.physicsBody = SKPhysicsBody(circleOfRadius: CGFloat(diameter - 4), center: CGPoint(x: 5, y:5)) + // Может перемещаться в пространстве + self.physicsBody?.isDynamic = true + // Категория - змея + self.physicsBody?.categoryBitMask = CollisionCategories.Snake + // пересекается с границами экрана и яблоком + self.physicsBody?.contactTestBitMask = CollisionCategories.EdgeBody | CollisionCategories.Apple + } + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} diff --git a/lesson8/SnakeHead.swift b/lesson8/SnakeHead.swift new file mode 100644 index 0000000..cbc386f --- /dev/null +++ b/lesson8/SnakeHead.swift @@ -0,0 +1,14 @@ +import UIKit +class SnakeHead: SnakeBodyPart { + override init(atPoint point: CGPoint){ + super.init(atPoint:point) + + self.physicsBody?.categoryBitMask = CollisionCategories.SnakeHead + // пересекается с телом, яблоком и границей экрана + self.physicsBody?.contactTestBitMask = CollisionCategories.EdgeBody | CollisionCategories.Apple | CollisionCategories.Snake + + } + required init?(coder aDecoder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} diff --git a/lesson8/apple.swift b/lesson8/apple.swift new file mode 100644 index 0000000..f6b69cc --- /dev/null +++ b/lesson8/apple.swift @@ -0,0 +1,21 @@ + +import UIKit +import SpriteKit +// Яблоко +class Apple: SKShapeNode { +//определяем, как оно будет отрисовываться + convenience init(position: CGPoint) { + self.init() + self.physicsBody = SKPhysicsBody(circleOfRadius: 10.0, center:CGPoint(x:5, y:5)) + self.physicsBody?.categoryBitMask = CollisionCategories.Apple +// рисуем круг + path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 10, height: 10)).cgPath +// заливаем красным + fillColor = UIColor.red +// рамка тоже красная + strokeColor = UIColor.red +// ширина рамки 5 поинтов + lineWidth = 5 + self.position = position + } +}