您好我正在尝试制作国际象棋游戏,我现在正在尝试建立一个给定两个国际象棋方块的功能,在方块上交换棋子。每个正方形都是一个具有可选ChessPiece对象的类。我目前的问题是,当我将一个棋子移动到另一个方块棋子属性时,两个棋子最终指向同一个对象,因为它们然后引用相同的方形属性。
import os
import sys
import time
from sqlalchemy import Column, ForeignKey, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
engine = create_engine('sqlite:///gmnpm.db')
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
email = Column(String(250), nullable=False)
picture = Column(String(250))
class Task(Base):
__tablename__ = 'task'
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
description = Column(String(2000))
assigned_id = Column(Integer, ForeignKey('user.id'))
project_id = Column(Integer, ForeignKey('project.id'))
due = Column(Integer, default=int(time.time()))
class Project(Base):
__tablename__ = 'project'
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
description = Column(String(1000))
projnum = Column(Integer)
Base.metadata.create_all(engine)
我是否需要对这两个棋子进行深度复制,以便我可以轻松交换位置?否则,似乎注释行只会让两个棋子对象指向内存中的相同位置。
答案 0 :(得分:3)
您可以使用swap方法并声明两个方法参数,将关键字inout添加到它们中:
struct ChessPiece {
let piece: String
}
struct Square {
let row: Int
let col: Int
var chessPiece: ChessPiece?
}
private func swapSquaresPieces(square1: inout Square, square2: inout Square) {
swap(&square1.chessPiece, &square2.chessPiece)
}
var square1 = Square(row: 1, col: 1, chessPiece: ChessPiece(piece: "queen"))
var square2 = Square(row: 2, col: 2, chessPiece: ChessPiece(piece: "king"))
swapSquaresPieces(square1: &square1, square2: &square2)
print(square1)
print(square2)
这将打印
Square(row:1,col:1,chessPiece:Optional(ChessPiece(piece:" king")))
Square(row:2,col:2,chessPiece: 可选(ChessPiece(件:"女王")))