-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Lesson8 #9
Open
abercromb
wants to merge
1
commit into
master
Choose a base branch
from
lesson8
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Lesson8 #9
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Binary file not shown.
Binary file not shown.
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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. | ||
} | ||
|
||
|
||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
{ | ||
"info" : { | ||
"author" : "xcode", | ||
"version" : 1 | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
<?xml version="1.0" encoding="UTF-8" standalone="no"?> | ||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM"> | ||
<dependencies> | ||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/> | ||
<capability name="Safe area layout guides" minToolsVersion="9.0"/> | ||
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> | ||
</dependencies> | ||
<scenes> | ||
<!--View Controller--> | ||
<scene sceneID="EHf-IW-A2E"> | ||
<objects> | ||
<viewController id="01J-lp-oVM" sceneMemberID="viewController"> | ||
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3"> | ||
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/> | ||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> | ||
<color key="backgroundColor" xcode11CocoaTouchSystemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/> | ||
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/> | ||
</view> | ||
</viewController> | ||
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/> | ||
</objects> | ||
<point key="canvasLocation" x="53" y="375"/> | ||
</scene> | ||
</scenes> | ||
</document> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
<?xml version="1.0" encoding="UTF-8"?> | ||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BV1-FR-VrT"> | ||
<dependencies> | ||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/> | ||
<capability name="Safe area layout guides" minToolsVersion="9.0"/> | ||
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> | ||
</dependencies> | ||
<scenes> | ||
<!--Game View Controller--> | ||
<scene sceneID="tXr-a1-R10"> | ||
<objects> | ||
<viewController id="BV1-FR-VrT" customClass="GameViewController" customModuleProvider="target" sceneMemberID="viewController"> | ||
<view key="view" multipleTouchEnabled="YES" contentMode="scaleToFill" id="3se-qz-xqx" customClass="SKView"> | ||
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/> | ||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> | ||
<color key="backgroundColor" xcode11CocoaTouchSystemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/> | ||
<viewLayoutGuide key="safeArea" id="4qk-I5-YsI"/> | ||
</view> | ||
</viewController> | ||
<placeholder placeholderIdentifier="IBFirstResponder" id="SZV-WD-TEh" sceneMemberID="firstResponder"/> | ||
</objects> | ||
</scene> | ||
</scenes> | ||
</document> |
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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<UITouch>, 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<UITouch>, 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<UITouch>, 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 | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
устраевший способ получения random