Answer the question
In order to leave comments, you need to log in
How to learn to use classes correctly?
Я учу Свифт и все вроде бы ок, но я никак не могу понять как использовать классы и структуры.
Прочитав оф. документацию я понимаю что класс может хранить это и это, у него могут быть методы и бла бла бла....
Но когда доходит до: "написать простенькую игру" у меня проблемы "версткой" кода.
Должен быть 1 глобальный класс Game, который хранит все свойства и методы всего что есть в игре ?
Должен быть класс Game, внутри вложенные классы ?
Классы должны быть разделены, например: класс Game, класс Person, класс Board(поле) и т.д. ?
Другой вариант?
Коротко об игре(для примера):
Рисуется поле, добавляется игрок, коробка и портал. (все в консоли)
Нужно сдвинуть коробку в портал чтобы победить.
import Foundation
class Game {
var height: Int
var width: Int
private lazy var board: = {
var gameBoard: = []
for i in 0...height - 1 {
if i == 0 || i == height - 1 {
gameBoard.append(Array(repeating: "", count: width))
} else {
var basicLine = Array(repeating: "⬜", count: width)
basicLine[0] = ""
basicLine[basicLine.count - 1] = ""
gameBoard.append(basicLine)
}
}
return gameBoard
} ()
private var alienPosition = (1, 1) {
willSet {
board[alienPosition.0][alienPosition.1] = "⬜"
} didSet {
if boxPosition == (board.count - 2, board.count - 2) {
clearConsole()
print("YOU WIN!!! ")
} else {
clearConsole()
addBoxOnBoard()
addAlienOnBoard()
print(self.board.forEach { print($0.joined(separator: "")) })
}
}
}
private lazy var boxPosition = (board.count / 2, board.count / 2)
init(height: Int, width: Int) {
self.height = height
self.width = width
loading()
clearConsole()
addBoxOnBoard()
addAlienOnBoard()
addPortalOnBoard()
print(self.board.forEach { print($0.joined(separator: "")) })
}
private func loading() {
var loadingPercent = 0
let size = 10
var squares = Array(repeating: "□", count: size)
for (i, _) in squares.enumerated() {
clearConsole()
squares[i] = "■"
loadingPercent += 10
print("\(squares.joined(separator: " ")) \(loadingPercent) %")
usleep(5)
}
}
private func clearConsole() {
for _ in 1...30 {
print("")
}
}
private func addAlienOnBoard() {
board[alienPosition.0][alienPosition.1] = ""
}
private func addBoxOnBoard() {
board[boxPosition.0][boxPosition.1] = ""
}
private func addPortalOnBoard() {
board[board.count - 2][board.count - 2] = ""
}
enum Move {
case up
case down
case right
case left
}
func moveAlien(direction: Move) {
switch direction {
case .up:
if (alienPosition.0 - 1, alienPosition.1) != boxPosition && board[alienPosition.0 - 1][alienPosition.1] != " " {
alienPosition.0 -= 1
} else if (alienPosition.0 + 1, alienPosition.1) == boxPosition && board[boxPosition.0 - 1][boxPosition.1] != " "{
boxPosition.0 -= 1
alienPosition.0 -= 1
}
case .down:
if (alienPosition.0 + 1, alienPosition.1) != boxPosition && board[alienPosition.0 + 1][alienPosition.1] != "" {
alienPosition.0 += 1
} else if (alienPosition.0 + 1, alienPosition.1) == boxPosition && board[boxPosition.0 + 1][boxPosition.1] != ""{
boxPosition.0 += 1
alienPosition.0 += 1
}
case .right:
if (alienPosition.0, alienPosition.1 + 1) != boxPosition && board[alienPosition.0][alienPosition.1 + 1] != "" {
alienPosition.1 += 1
} else if (alienPosition.0, alienPosition.1 + 1) == boxPosition && board[boxPosition.0][boxPosition.1 + 1] != ""{
boxPosition.1 += 1
alienPosition.1 += 1
}
case .left:
if (alienPosition.0, alienPosition.1 - 1) != boxPosition && board[alienPosition.0][alienPosition.1 - 1] != "" {
alienPosition.1 -= 1
} else if (alienPosition.0, alienPosition.1 - 1) == boxPosition && board[boxPosition.0][boxPosition.1 - 1] != " "{
boxPosition.1 -= 1
alienPosition.1 -= 1
}
}
}
}
let myGame8 = Game(height: 6, width: 6)
Answer the question
In order to leave comments, you need to log in
Your question is about application architecture, not "how to use classes properly".
And, the correct answer to your question about the architecture of the application can only be given by the one who set you the task of writing this application.
- you can write everything in one class.
- can be divided into different classes.
- can be split into different libraries.
My answer is - write as you like (this implies both "how you like" and "how lighter" and "how the left heel wants"). You are just learning, and if you are not a genius, then, love, first write it wrong. So - train, and, as a result, learn.
Smoking principles SOLID, GRASP, DI, etc. Patterns, again. As you write code, check to see if your ideas are in line with these principles. The end goal is "strongly connected and weakly hooked", then your code can be simple and understandable.
But everything is in moderation.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question