Ejemplo n.º 1
0
        private float Alphabeta(Board board, Disc playerToMove, int distanceToLeafNodes, float alpha, float beta)
        {
            if (distanceToLeafNodes == 0)
            {
                NodesEvaluated++;
                return _nodeEvaluator.Evaluate(playerToMove, board);
            }

            float best = float.MinValue;
            foreach (Square move in board.Moves(playerToMove))
            {
                if (best >= beta)
                {
                    BetaCutoffs++;
                    break;
                }
                var childBoard = new Board(board);
                childBoard.MakeMove(playerToMove, move);

                if (best > alpha) alpha = best;
                float score = -Alphabeta(childBoard, playerToMove.Opponent(), distanceToLeafNodes - 1, -beta, -alpha);
                if (score > best)
                {
                    best = score;
                    if (distanceToLeafNodes == _currentSearchDepth)
                    {
                        BestScore = score;
                        BestMove = move;
                    }

                }
            }
            return best;
        }
        public Point NextMove(Disc[,] board, Disc playerColor)
        {
            Point bestMove = new Point(0, 0);
            int bestScore = int.MinValue;

            foreach (Point p1 in ReversiGame.ValidMoves(board, playerColor))
            {
                Disc[,] newBoard = ReversiGame.PlayTurn(board, p1, playerColor);
                foreach (Point p2 in ReversiGame.ValidMoves(newBoard, playerColor.Reversed()))
                {
                    int score = ReversiGame.Score(newBoard, playerColor);
                    if (score > bestScore)
                    {
                        bestMove = p1;
                        bestScore = score;
                        break;
                    }
                }
            }

            if (ReversiGame.IsValidMove(board, bestMove, playerColor))
            {
                return bestMove;
            }

            return ReversiGame.ValidMoves(board, playerColor).First();
        }
        public Point NextMove(Disc[,] board, Disc playerColor)
        {
            //Point bestMove = new Point(0, 0);
            //int bestScore = int.MinValue;
            //foreach (Point p in ReversiGame.ValidMoves(board, playerColor))
            //{

            //    Disc[,] d = ReversiGame.PlayTurn(board, p, playerColor);
            //    Disc[,] after = bestTurnEnemy(playerColor, d);
            //    foreach (Point p2 in ReversiGame.ValidMoves(after, playerColor))
            //    {
            //        int score = ReversiGame.Score(ReversiGame.PlayTurn(after, p2, playerColor), playerColor);
            //        if (score > bestScore)
            //        {
            //            bestMove = p;
            //            bestScore = score;
            //        }
            //    }

            //}
            //if (ReversiGame.IsValidMove(board,bestMove,playerColor))
               // {
                return ReversiGame.ValidMoves(board, playerColor).First();
            //}
            //return bestMove;
        }
        public bool CloseToEdge(Disc[,] board)
        {
            int size = board.GetLength(0);

            return X == 1 || Y == 1
                   || X == size - 2 || Y == size - 2;
        }
        /// <summary>
        /// The minimax algorithm
        /// </summary>
        /// <param name="board">Target board</param>
        /// <param name="playerColor">Current player</param>
        /// <param name="maxDepth">Maximim recursion depth</param>
        /// <returns>The score and point of the best minimax play</returns>
        private Tuple<int, Point> Minimax(Disc[,] board, Disc playerColor, int maxDepth)
        {
            if (maxDepth == 0)
            {
                return new Tuple<int, Point>(ReversiGame.Score(board, playerColor), null);
            }

            Point bestMove = null;
            int bestScore = int.MinValue;

            foreach (Point p in ReversiGame.ValidMoves(board, playerColor))
            {
                int score = -Minimax(
                    ReversiGame.PlayTurn(board, p, playerColor),
                    playerColor.Reversed(),
                    maxDepth - 1).Item1;

                score = HeuristicScore(board, p, score);

                if (score > bestScore)
                {
                    bestMove = p;
                    bestScore = score;
                }
            }

            if (bestMove == null)
            {
                bestScore = ReversiGame.Score(board, playerColor);
            }

            return new Tuple<int, Point>(bestScore, bestMove);
        }
Ejemplo n.º 6
0
        public BurnProgress(Disc disc, int speed)
        {
            InitializeComponent();
            _disc = disc;
            _abort = false;

            double size = new FileInfo(disc.FullName).Length;
            GetTime(size, speed);

            l_duration.Text = Math.Round((_timeSec / 60), 2) + " Minuten";
            l_speed.Text = speed + "x (" + speed * 150 + " kb/s )";

            uint flags = 0;
            flags |= (uint)NERO_BURN_FLAGS.NERO_BURN_FLAG_CD_TEXT;
            flags |= (uint)NERO_BURN_FLAGS.NERO_BURN_FLAG_CLOSE_SESSION;
            flags |= (uint)NERO_BURN_FLAGS.NERO_BURN_FLAG_DISABLE_EJECT;
            flags |= (uint)NERO_BURN_FLAGS.NERO_BURN_FLAG_WRITE;
            flags |= (uint)NERO_BURN_FLAGS.NERO_BURN_FLAG_BUF_UNDERRUN_PROT;

            Burn.Drive.OnDoneBurn += new _INeroDriveEvents_OnDoneBurnEventHandler(_drive_OnDoneBurn);
            Burn.Drive.OnProgress += new _INeroDriveEvents_OnProgressEventHandler(_drive_OnProgress);

            Cursor = Cursors.WaitCursor;

            switch (disc.MediaType)
            {
                case MediaType.CompactDisc:
                    Burn.Drive.BurnImage(disc.FullName , (NERO_BURN_FLAGS)flags, speed);
                    break;
                case MediaType.DigitalVersatileDisc:
                    Burn.Drive.BurnImage2(disc.FullName, (NERO_BURN_FLAGS)flags, speed, NERO_MEDIA_TYPE.NERO_MEDIA_DVD_ANY);
                    break;
            }
        }
        public Point NextMove(Disc[,] board, Disc playerColor)
        {
            Point bestMove = new Point(0, 0);
            int MaxD = 1;

            foreach (Point p in ReversiGame.ValidMoves(board, playerColor))
            {
                if ((p.X == 7 && p.Y == 7) || (p.X == 7 && p.Y == 0) || (p.X == 0 && p.Y == 7) || (p.X == 0 && p.Y == 0))
                {
                    return p;
                }
                int score = ReversiGame.Score(ReversiGame.PlayTurn(board, p, playerColor), playerColor);
                if (board.At(p) == playerColor)
                {

                }

                if (score > MaxD)
                {
                    bestMove = p;
                    MaxD = score;
                }
            }
            return bestMove;
        }
 /// <summary>
 /// Checks if a given move is valid
 /// </summary>
 /// <param name="board">The game board</param>
 /// <param name="point">The point to play in</param>
 /// <param name="currentPlayer">The current player's color</param>
 /// <returns>True if the move is valid, false otherwise</returns>
 public static bool IsValidMove(Disc[,] board, Point point, Disc currentPlayer)
 {
     if (point == null)
         return false;
     return board.At(point).IsEmpty() &&
         PointsToReverse(board, point, currentPlayer).Count > 0;
 }
Ejemplo n.º 9
0
    /// <summary>
    /// initializes the flight of the disc based on power and direction
    /// TODO body rotation at the time of release for turn?
    /// </summary>
    public void BeginFlight(Disc disc, float throwPower, Vector3 throwDirection)
    {
        if (disc == this)
        {
            // set him free!
            // you're a free disc with endless possibilities!!
            transform.SetParent(null);

            // clamp throw power above 0.1f
            if (throwPower < 0.1f) { throwPower = 0.1f; }

            // set initial velocity
            velocity = (throwDirection * throwPower) + (throwDirection / 2);

            // it's flying
            _state = DiscState.InFlight;
            anim.SetTrigger("inFlight");

            // de-subscribe for another throw
            UnsubscribeFromThrow();

            // TEMP death countdown incase the disc goes through the terrain
            StartCoroutine(DeathCountdown(8f));
        }
    }
 /// <summary>
 /// Counts the number of discs of a given color on the board.
 /// (works for Disc.Empty)
 /// </summary>
 /// <param name="board">The game board</param>
 /// <param name="color">The player color</param>
 /// <returns>The disc count</returns>
 public static int CountDiscs(Disc[,] board, Disc color)
 {
     int count = 0;
     foreach (Point p in board.PointsIterator())
         if (board.At(p) == color)
             count++;
     return count;
 }
Ejemplo n.º 11
0
        // ctor
        public Burn(Disc disc)
        {
            _disc = disc;
            // init needed data
            _speed = 0;
            _size = 0;

            InitializeComponent();
        }
Ejemplo n.º 12
0
    // fire disc enter event, run self OnDiscEnter method
    protected virtual void RaiseDiscEnter(Disc colDisc)
    {
        if (DiscEnter != null)
        {
            DiscEnter(colDisc);
        }

        OnDiscEnter(colDisc);
    }
        /// <summary>
        /// Creates a new instance of the ReversiGame Class
        /// </summary>
        /// <param name="size">The sive of the board</param>
        public ReversiGame(int size = 8)
        {
            Contract.Requires(size > 0);
            Contract.Requires(size % 2 == 0);

            board = new Disc[size, size];
            board[size / 2 - 1, size / 2 - 1] = Disc.Black;
            board[size / 2, size / 2 - 1] = Disc.White;
            board[size / 2 - 1, size / 2] = Disc.White;
            board[size / 2, size / 2] = Disc.Black;
            currentPlayer = Disc.White;
        }
Ejemplo n.º 14
0
 public override float Evaluate(Disc playerToMove, Board board)
 {
     int divisor = 0;
     float total = 0;
     foreach (var evaluator in Evaluators)
     {
         total += evaluator.Evaluate(playerToMove, board);
         divisor += evaluator.Weight;
     }
     if (divisor == 0) return 0;
     return total / divisor;
 }
        private int HeuristicScore(Disc[,] board, Point move, int score)
        {
            //Give the edges of the board a priority.
            if (move.IsEdge(board))
            {
                score += 2;
            } else if (move.CloseToEdge(board))
            {
                score -= 2;
            }

            return score;
        }
Ejemplo n.º 16
0
    /// <summary>
    /// initializes following the disc
    /// frees the camera and flags following/lookat behaviors
    /// </summary>
    public void StartFollowDisc(Disc newDisc, float throwPower, Vector3 throwDirection)
    {
        target = newDisc.transform;
        followSpeed = resetFollowSpeed;

        foreach (Transform child in transform)
        {
            child.SetParent(null);
        }

        followTarget = true;
        lookAtTarget = true;

        newDisc.DiscHit += OnDiscHit;
    }
Ejemplo n.º 17
0
        public bool PlayDisc(Disc disc, int column)
        {
            if (column > MaxColumn || column < 1) throw new ArgumentException(String.Format("Column must be between 1 and {0}", MaxColumn));
              int row = MaxRow;
              while (row > 0 && board[new Location(row, column)] != Disc.Empty) {
            row--;
              }

              if (row > 0) {
            board[new Location(row, column)] = disc;
            lastLocationPlayed = new Location(row, column);
            return true;
              }
              return false;
        }
 public Point NextMove(Disc[,] board, Disc playerColor)
 {
     Point bestMove= new Point(0,0);
     int bestScore = int.MinValue;
     foreach (Point p in ReversiGame.ValidMoves(board, playerColor))
     {
         int score = ReversiGame.Score(ReversiGame.PlayTurn(board, p, playerColor), playerColor);
         if(score > bestScore)
         {
             bestMove = p;
             bestScore = score;
         }
     }
     return bestMove;
 }
Ejemplo n.º 19
0
        public override float Evaluate(Disc playerToMove, Board board)
        {
            NodesEvaluated = 0;
            BetaCutoffs = 0;

            if (IterativeDeepening) _currentSearchDepth = 1;
            else _currentSearchDepth = MaxSearchDepth;

            while (_currentSearchDepth <= MaxSearchDepth)
            {
                _currentSearchDepth++;
                Alphabeta(board, playerToMove, _currentSearchDepth, float.MinValue, float.MaxValue);
            }

            return BestScore;
        }
 public Disc[,] bestTurnEnemy(Disc playerColor,Disc [,] currentBoard)
 {
     Point bestMove = new Point(0, 0);
     int bestScore = int.MinValue;
     Disc enemyColor = playerColor.Reversed();
     foreach (Point p in ReversiGame.ValidMoves(currentBoard, enemyColor))
     {
         int score = ReversiGame.Score(ReversiGame.PlayTurn(currentBoard, p, enemyColor), enemyColor);
         if (score > bestScore)
         {
             bestMove = p;
             bestScore = score;
         }
     }
     return ReversiGame.PlayTurn(currentBoard, bestMove, enemyColor);
 }
        public Point NextMove(Disc[,] board, Disc playerColor)
        {
            Point bestMove = new Point(0, 0);
            int bestScore = int.MinValue;
            bool flag = false, flag2=false;
            foreach (Point p in ReversiGame.ValidMoves(board, playerColor))
            {
                if ((p.X == 0 && p.Y == 0) || (p.X == 0 && p.Y == 7) || (p.Y == 0 && p.X == 7) || (p.X == 7 && p.Y == 7)) return p;
                else
                {
                    if ((p.Y == 0) || (p.Y == 7) || (p.X == 0) || (p.X == 7))
                    {
                        return p;
                    }

                }
                int score = ReversiGame.Score(ReversiGame.PlayTurn(board, p, playerColor), playerColor);
                if ((score > bestScore)&&((p.X!=1)&&(p.Y!=1)&&(p.Y!=6)&&(p.X!=6)))

                {
                    flag=true;
                    bestMove = p;
                    bestScore = score;
                }
                else
                {
                }
            }
            if(flag==false)
            {
                foreach (Point p in ReversiGame.ValidMoves(board, playerColor))
                {
                    if ((p.X != 1 && p.Y != 1)&&(p.X != 1 && p.Y != 6)&&(p.X != 6 && p.Y != 1)&&(p.X != 6 && p.Y != 6))
                    {
                        flag2 = true;
                        return p;
                    }

                }
                if (flag2 == false)
                {
                    bestMove = ReversiGame.ValidMoves(board, playerColor).First();
                }
            }
            return bestMove;
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Calculate score from Blacks perspective
        /// </summary>
        private static int EvaluateCornerPattern(Disc corner, Disc edge1, Disc edge2, Disc diagonal)
        {
            //Todo: reimplement using lookup tables
            int value = 0;

            //if the corner is empty - big penalty for X-square, small penalty for C-square
            if (corner == Disc.None)
            {
                if (diagonal == Disc.Black) value -= 20;
                else if (diagonal == Disc.White) value += 20;
                return value;
            }
            //if the corner is occupied - bonus for each adjacent
            value = 20;
            if (corner == edge1) value += 10;
            if (corner == edge2) value += 10;
            if (corner == diagonal) value += 10;
            if (corner == Disc.White) value = -value;
            return value;
        }
 /// <summary>
 /// Generates a board from a string representation
 /// </summary>
 /// <param name="s">a string representation of the board</param>
 /// <returns>A new board</returns>
 public static Disc[,] BoardFromString(this String s)
 {
     string[] lines = s.Split('\n');
     Disc[,] board = new Disc[lines.Length, lines.Length];
     for (int i = 0; i < board.GetLength(0); i++)
         for (int j = 0; j < board.GetLength(1); j++)
             switch (lines[i][j])
             {
                 case 'O':
                     board[i, j] = Disc.Black;
                     break;
                 case '-':
                     board[i, j] = Disc.Empty;
                     break;
                 case 'X':
                     board[i, j] = Disc.White;
                     break;
             }
     return board;
 }
Ejemplo n.º 24
0
        public override float Evaluate(Disc playerToMove, Board board)
        {
            int score = EvaluateCornerPattern(board["a1"], board["b1"], board["a2"], board["b2"])
                        + EvaluateCornerPattern(board["h8"], board["h7"], board["g8"], board["g7"])
                        + EvaluateCornerPattern(board["a8"], board["a7"], board["b8"], board["b7"])
                        + EvaluateCornerPattern(board["h1"], board["g1"], board["h2"], board["g2"]);

            if (playerToMove == Disc.White) score = -score;
            return score;

            //int squaresLeft = game.SquaresRemaining();

            ////TODO: make som predefined weight-arrays with better resolution
            //if (squaresLeft < 4) { return (material * 97 + mobility * 2 + position * 1) / 100; }
            //else if (squaresLeft < 10) { return (material * 10 + mobility * 10 + position * 80) / 100; }
            //else if (squaresLeft < 18) { return (material * 5 + mobility * 15 + position * 80) / 100; }
            //else if (squaresLeft < 26) { return (material * 2 + mobility * 20 + position * 78) / 100; }
            //else if (squaresLeft < 34) { return (material * 2 + mobility * 19 + position * 79) / 100; }
            //else if (squaresLeft < 42) { return (material * 0 + mobility * 15 + position * 85) / 100; }
            //else if (squaresLeft < 50) { return (material * 0 + mobility * 10 + position * 90) / 100; }
            //else { return (material * 0 + mobility * 10 + position * 90) / 100; }
        }
 void DeclareWinner(Disc disc)
 {
     RedPlayerWins = disc == Disc.Red ? "Visible" : "Hidden";
       BlackPlayerWins = disc == Disc.Black ? "Visible" : "Hidden";
       RedPlayersTurn = "Hidden";
       BlackPlayersTurn = "Hidden";
       IsBoardEnabled = "False";
 }
 /// <summary>
 /// Counts the number of discs of a given color on the board.
 /// (works for Disc.Empty)
 /// </summary>
 /// <param name="board">The game board</param>
 /// <param name="color">The player color</param>
 /// <returns>The disc count</returns>
 public static int CountDiscs(Disc[,] board, Disc color)
 {
     return board.PointsIterator().Count(p => board.At(p) == color);
 }
 public void InitializeGame()
 {
     gameBoard = new GameBoard();
       gameBoard.Initialize();
       BoardLocationColors = new ObservableCollection<string>
     (Enumerable.Repeat<string>("AliceBlue", GameBoard.MaxRow * GameBoard.MaxColumn));
       RedPlayersTurn = "Visible";
       BlackPlayersTurn = "Hidden";
       RedPlayerWins = "Hidden";
       BlackPlayerWins = "Hidden";
       CurrentPlayerDisc = Disc.Red;
       IsBoardEnabled = "True";
 }
Ejemplo n.º 28
0
        // get next available content # for adding a new content to the disc object
        public int GetNextContentNumber(Disc di)
        {
            int nxtcntn = DALServices.GetNextContentNumber(di);

            return(nxtcntn);
        }
 /// <summary>
 /// Playes a single game turn
 /// </summary>
 /// <param name="player">The player object</param>
 public void PlaySingleTurn(IReversiPlayer player)
 {
     Point point = player.NextMove((Disc[,])board.Clone(), currentPlayer);
     board = PlayTurn(board, point, currentPlayer);
     currentPlayer = currentPlayer.Reversed();
 }
Ejemplo n.º 30
0
    public override void OnCollideDisc(Disc source, GameObject other, Collision col)
    {
        AttackData data = other.GetComponent <Disc>().Attack(source, col);

        source.GetAttacked(data);
    }
Ejemplo n.º 31
0
        // ADD the next Disc to a specific case/box
        public Disc AddNextDisc(int boxnum, int casenum)
        {
            Disc di = DALServices.AddNextDisc(context, boxnum, casenum);

            return(di);
        }
Ejemplo n.º 32
0
 public PicoDrive(CoreComm comm, GameInfo game, Disc cd, bool deterministic)
     : this(comm, game, null, cd, deterministic)
 {
 }
Ejemplo n.º 33
0
        private PicoDrive(CoreComm comm, GameInfo game, byte[] rom, Disc cd, bool deterministic)
            : base(comm, new Configuration
        {
            MaxSamples    = 2048,
            DefaultWidth  = 320,
            DefaultHeight = 224,
            MaxWidth      = 320,
            MaxHeight     = 480,
            SystemId      = "GEN"
        })
        {
            var biosg      = comm.CoreFileProvider.GetFirmware("32X", "G", false);
            var biosm      = comm.CoreFileProvider.GetFirmware("32X", "M", false);
            var bioss      = comm.CoreFileProvider.GetFirmware("32X", "S", false);
            var has32xBios = biosg != null && biosm != null && bioss != null;

            if (deterministic && !has32xBios)
            {
                throw new InvalidOperationException("32X BIOS files are required for deterministic mode");
            }
            deterministic |= has32xBios;

            _core = PreInit <LibPicoDrive>(new PeRunnerOptions
            {
                Filename            = "picodrive.wbx",
                SbrkHeapSizeKB      = 64,
                SealedHeapSizeKB    = 18 * 1024,
                InvisibleHeapSizeKB = 1024,
                MmapHeapSizeKB      = 4096,
                PlainHeapSizeKB     = 64,
            });

            if (has32xBios)
            {
                _exe.AddReadonlyFile(biosg, "32x.g");
                _exe.AddReadonlyFile(biosm, "32x.m");
                _exe.AddReadonlyFile(bioss, "32x.s");
                Console.WriteLine("Using supplied 32x BIOS files");
            }
            if (cd != null)
            {
                _exe.AddReadonlyFile(comm.CoreFileProvider.GetFirmware("GEN", "CD_BIOS_EU", true), "cd.eu");
                _exe.AddReadonlyFile(comm.CoreFileProvider.GetFirmware("GEN", "CD_BIOS_US", true), "cd.us");
                _exe.AddReadonlyFile(comm.CoreFileProvider.GetFirmware("GEN", "CD_BIOS_JP", true), "cd.jp");
                _exe.AddReadonlyFile(gpgx.GPGX.GetCDData(cd), "toc");
                _cd         = cd;
                _cdReader   = new DiscSectorReader(_cd);
                _cdcallback = CDRead;
                _core.SetCDReadCallback(_cdcallback);
                DriveLightEnabled = true;
            }
            else
            {
                _exe.AddReadonlyFile(rom, "romfile.md");
            }

            if (!_core.Init(cd != null, game["32X"]))
            {
                throw new InvalidOperationException("Core rejected the file!");
            }

            if (cd != null)
            {
                _exe.RemoveReadonlyFile("cd.eu");
                _exe.RemoveReadonlyFile("cd.us");
                _exe.RemoveReadonlyFile("cd.jp");
                _exe.RemoveReadonlyFile("toc");
                _core.SetCDReadCallback(null);
            }
            else
            {
                _exe.RemoveReadonlyFile("romfile.md");
            }
            if (has32xBios)
            {
                _exe.RemoveReadonlyFile("32x.g");
                _exe.RemoveReadonlyFile("32x.m");
                _exe.RemoveReadonlyFile("32x.s");
            }

            PostInit();
            ControllerDefinition   = PicoDriveController;
            DeterministicEmulation = deterministic;
            _core.SetCDReadCallback(_cdcallback);

            _isPal           = _core.IsPal();
            VsyncNumerator   = _isPal ? 53203424 : 53693175;
            VsyncDenominator = _isPal ? 3420 * 313 : 3420 * 262;
        }
Ejemplo n.º 34
0
        static void Main(string[] args)
        {
            string dir = string.Empty;

            if (args.Length == 2)
            {
                dir = args[1];
            }
            else if (args.Length == 1)
            {
                dir = args[0] + ".ext";
            }
            else
            {
                Console.WriteLine("Usage: wiidiscextractor /path/to/disc.iso /extract/path");
                return;
            }

            Directory.CreateDirectory(dir);

            try {
                if (!Directory.Exists(args[0]))
                {
                    throw new FormatException();
                }
                DelayedStreamCache cache = new DelayedStreamCache();
                DirectoryNode      dirn  = DirectoryNode.FromPath(args[0], cache, FileAccess.Read, FileShare.Read);
                DirectoryNode      gen   = dirn.Navigate("gen", false, true) as DirectoryNode;
                if (gen == null)                 // Just in case we're given the "wrong" directory that directly contains the ark
                {
                    gen = dirn;
                }

                List <Pair <int, Stream> > arkfiles = new List <Pair <int, Stream> >();
                Stream hdrfile = null;
                foreach (FileNode file in gen.Files)
                {
                    if (file.Name.ToLower().EndsWith(".hdr"))
                    {
                        hdrfile = file.Data;
                    }
                    else if (file.Name.ToLower().EndsWith(".ark"))
                    {
                        Match match = Regex.Match(file.Name.ToLower(), @"_(\d+).ark");
                        if (match.Success)
                        {
                            arkfiles.Add(new Pair <int, Stream>(int.Parse(match.Groups[1].Value), file.Data));
                        }
                        else
                        {
                            arkfiles.Add(new Pair <int, Stream>(0, file.Data));
                        }
                    }
                }

                // FreQuency/Amplitude where the header is the ark
                if (hdrfile == null)
                {
                    if (arkfiles.Count == 1)
                    {
                        hdrfile = arkfiles[0].Value;
                        arkfiles.Clear();
                    }
                    else
                    {
                        throw new FormatException();
                    }
                }

                Ark ark = new Ark(new EndianReader(hdrfile, Endianness.LittleEndian), arkfiles.OrderBy(f => f.Key).Select(f => f.Value).ToArray());
                ark.Root.Extract(dir);
                cache.Dispose();
            } catch (FormatException) {
                Stream stream = new FileStream(args[0], FileMode.Open, FileAccess.Read);
                try {
                    Iso9660 iso = new Iso9660(stream);
                    iso.Root.Extract(dir);
                } catch (Exception) {
                    try {
                        stream.Position = 0;
                        Disc disc = new Disc(stream);

                        File.WriteAllText(Path.Combine(dir, "title"), disc.Title);

                        foreach (var partition in disc.Partitions)
                        {
                            string path = Path.Combine(dir, "partition" + disc.Partitions.IndexOf(partition).ToString());
                            Directory.CreateDirectory(path);

                            partition.Root.Root.Extract(Path.Combine(path, "data"));

                            FileStream file = new FileStream(Path.Combine(path, "partition.tik"), FileMode.Create, FileAccess.Write);
                            partition.Ticket.Save(file);
                            file.Close();

                            file = new FileStream(Path.Combine(path, "partition.tmd"), FileMode.Create, FileAccess.Write);
                            partition.TMD.Save(file);
                            file.Close();

                            file = new FileStream(Path.Combine(path, "partition.certs"), FileMode.Create, FileAccess.Write);
                            file.Write(partition.CertificateChain);
                            file.Close();
                        }
                    } catch {
                        try {
                            stream.Position = 0;
                            DlcBin bin = new DlcBin(stream);
                            U8     u8  = new U8(bin.Data);
                            u8.Root.Extract(dir);
                        } catch {
                            try {
                                stream.Position = 0;
                                U8 u8 = new U8(stream);
                                u8.Root.Extract(dir);
                            } catch {
                                stream.Position = 0;
                                Rarc rarc = new Rarc(stream);
                                rarc.Root.Extract(dir);
                            }
                        }
                    }
                }
                stream.Close();
            }
        }
Ejemplo n.º 35
0
 // Use this for initialization
 void Start()
 {
     disc = GetComponent <Disc>();
 }
Ejemplo n.º 36
0
        public PCEngine(CoreComm comm, GameInfo game, Disc disc, object Settings, object syncSettings)
        {
            CoreComm          = comm;
            MemoryCallbacks   = new MemoryCallbackSystem(new[] { "System Bus" });
            DriveLightEnabled = true;
            SystemId          = "PCECD";
            Type          = NecSystemType.TurboCD;
            this.disc     = disc;
            this.Settings = (PCESettings)Settings ?? new PCESettings();
            _syncSettings = (PCESyncSettings)syncSettings ?? new PCESyncSettings();

            GameInfo biosInfo;

            byte[] rom = CoreComm.CoreFileProvider.GetFirmwareWithGameInfo("PCECD", "Bios", true, out biosInfo,
                                                                           "PCE-CD System Card not found. Please check the BIOS settings in Config->Firmwares.");

            if (biosInfo.Status == RomStatus.BadDump)
            {
                CoreComm.ShowMessage(
                    "The PCE-CD System Card you have selected is known to be a bad dump. This may cause problems playing PCE-CD games.\n\n"
                    + "It is recommended that you find a good dump of the system card. Sorry to be the bearer of bad news!");
            }
            else if (biosInfo.NotInDatabase)
            {
                CoreComm.ShowMessage(
                    "The PCE-CD System Card you have selected is not recognized in our database. That might mean it's a bad dump, or isn't the correct rom.");
            }
            else if (biosInfo["BIOS"] == false)
            {
                // zeromus says: someone please write a note about how this could possibly happen.
                // it seems like this is a relic of using gameDB for storing whether something is a bios? firmwareDB should be handling it now.
                CoreComm.ShowMessage(
                    "The PCE-CD System Card you have selected is not a BIOS image. You may have selected the wrong rom. FYI-Please report this to developers, I don't think this error message should happen.");
            }

            if (biosInfo["SuperSysCard"])
            {
                game.AddOption("SuperSysCard");
            }

            if (game["NeedSuperSysCard"] && game["SuperSysCard"] == false)
            {
                CoreComm.ShowMessage(
                    "This game requires a version 3.0 System card and won't run with the system card you've selected. Try selecting a 3.0 System Card in the firmware configuration.");
                throw new Exception();
            }

            game.FirmwareHash = rom.HashSHA1();

            Init(game, rom);

            // the default RomStatusDetails don't do anything with Disc
            CoreComm.RomStatusDetails = $"{game.Name}\r\nDisk partial hash:{new DiscSystem.DiscHasher(disc).OldHash()}";

            _controllerDeck = new PceControllerDeck(
                _syncSettings.Port1,
                _syncSettings.Port2,
                _syncSettings.Port3,
                _syncSettings.Port4,
                _syncSettings.Port5);
        }
Ejemplo n.º 37
0
 public abstract void OnSwipe(Disc target, SwipeData swipe);
Ejemplo n.º 38
0
        private GameInfo MakeGameFromDisc(Disc disc, string ext, string name)
        {
            // TODO - use more sophisticated IDer
            var discType   = new DiscIdentifier(disc).DetectDiscType();
            var discHasher = new DiscHasher(disc);
            var discHash   = discType == DiscType.SonyPSX
                                ? discHasher.Calculate_PSX_BizIDHash().ToString("X8")
                                : discHasher.OldHash();

            var game = Database.CheckDatabase(discHash);

            if (game == null)
            {
                // try to use our wizard methods
                game = new GameInfo {
                    Name = name, Hash = discHash
                };

                switch (discType)
                {
                case DiscType.SegaSaturn:
                    game.System = "SAT";
                    break;

                case DiscType.SonyPSP:
                    game.System = "PSP";
                    break;

                case DiscType.SonyPS2:
                    game.System = "PS2";
                    break;

                case DiscType.MegaCD:
                    game.System = "GEN";
                    break;

                case DiscType.PCFX:
                    game.System = "PCFX";
                    break;

                case DiscType.TurboGECD:
                case DiscType.TurboCD:
                    game.System = "PCE";
                    break;

                case DiscType.Amiga:
                case DiscType.CDi:
                case DiscType.Dreamcast:
                case DiscType.GameCube:
                case DiscType.NeoGeoCD:
                case DiscType.Panasonic3DO:
                case DiscType.Playdia:
                case DiscType.Wii:
                    // no supported emulator core for these (yet)
                    game.System = discType.ToString();
                    throw new NoAvailableCoreException(discType.ToString());

                case DiscType.AudioDisc:
                case DiscType.UnknownCDFS:
                case DiscType.UnknownFormat:
                    game.System = _config.TryGetChosenSystemForFileExt(ext, out var sysID) ? sysID : "NULL";
                    break;

                default:                         //"for an unknown disc, default to psx instead of pce-cd, since that is far more likely to be what they are attempting to open" [5e07ab3ec3b8b8de9eae71b489b55d23a3909f55, year 2015]
                case DiscType.SonyPSX:
                    game.System = "PSX";
                    break;
                }
            }
            return(game);
        }
Ejemplo n.º 39
0
        private static void PlayGame()
        {
            Game game = new Game();

            game.Pass += (s, e) =>
            {
                Disc player = game.State.PlayerToMove().Opponent();
                Console.WriteLine("pass, " + player + " has no moves");
            };
            Disc computer = Disc.Black;
            CompositeEvaluator nodeEvaluator = new CompositeEvaluator();

            nodeEvaluator.Evaluators.Add(new WeightedEvaluator(1, new MaterialEvaluator()));
            nodeEvaluator.Evaluators.Add(new WeightedEvaluator(10, new CornerPatternEvaluator()));
            nodeEvaluator.Evaluators.Add(new WeightedEvaluator(10, new MobilityEvaluator()));

            AlphabetaEvaluator computerPlayer = new AlphabetaEvaluator(7, nodeEvaluator);

            while (!game.Over)
            {
                Drawboard(game.Board);

                Disc playerToMove = game.State.PlayerToMove();
                if (playerToMove == computer)
                {
                    float score = computerPlayer.Evaluate(playerToMove, game.Board);
                    Console.WriteLine("Score: " + score);
                    Console.WriteLine("Nodes evaluated: " + computerPlayer.NodesEvaluated);
                    Console.WriteLine("Beta cutoffs: " + computerPlayer.BetaCutoffs);
                    Console.WriteLine("Move: " + computerPlayer.BestMove);
                    game.MakeMove(computerPlayer.BestMove);
                }
                else
                {
                    while (true)
                    {
                        Console.Write("Moves: ");
                        PrintMoves(game.Board.Moves(playerToMove));
                        Console.Write("Your move: ");
                        string input = Console.ReadLine().ToLower();
                        if (input == "quit")
                        {
                            game.Resign();
                            break;
                        }
                        try
                        {
                            Square    move     = Square.Parse(input);
                            GameState newState = game.MakeMove(move);
                            break;
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Invalid move, try again");
                        }
                    }
                }
            }
            Drawboard(game.Board);
            Console.WriteLine("Game over: " + game.State);
            Console.WriteLine("Black: " + game.Board.Count(Disc.Black) + " White: " + game.Board.Count(Disc.White));
            Console.ReadLine();
        }
Ejemplo n.º 40
0
        public void TryFindUnbalancedDiscNoChildren()
        {
            var disc = new Disc("ugml(68)");

            Assert.AreEqual(false, disc.TryFindUnbalancedDisc(out Disc disc2));
        }
Ejemplo n.º 41
0
        protected override string Part1(string[] input)
        {
            var root = Disc.ReadFrom(input);

            return(root.Name);
        }
Ejemplo n.º 42
0
 public CDAudio(Disc disc, int maxVolume = short.MaxValue)
 {
     Disc             = disc;
     DiscSectorReader = new DiscSectorReader(disc);
     MaxVolume        = maxVolume;
 }
Ejemplo n.º 43
0
 public override void OnCollideTerrain(Disc source, GameObject other, Collision col)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 44
0
        public DiscInspector Start(DetectedDiscType detectedDiscType)
        {
            // cue existance check
            if (discI.CuePath == null || !File.Exists(discI.CuePath))
            {
                return(discI);
            }

            //////////////////
            /* OtherFormats */
            //////////////////

            // discjuggler - currently only implemented for dreamcast CDI files
            if (IntenseScan)
            {
                if (Path.GetExtension(discI.CuePath).ToLower() == ".cdi")
                {
                    discI.DetectedDiscType = ScanDiscJuggler();

                    return(discI);
                }
            }


            // attempt to mount the disc
            try
            {
                disc = Disc.LoadAutomagic(discI.CuePath);
                if (disc == null)
                {
                    return(discI);
                }
            }
            catch { return(discI); }

            // detect disc mode
            discView = EDiscStreamView.DiscStreamView_Mode1_2048;
            if (disc.TOC.Session1Format == SessionFormat.Type20_CDXA)
            {
                discView = EDiscStreamView.DiscStreamView_Mode2_Form1_2048;
            }

            // biztools discident init
            di = new DiscIdentifier(disc);

            // try and mount it as an ISO
            isIso = iso.Parse(new DiscStream(disc, discView, 0));

            // if iso is mounted, populate data from volume descriptor(s) (at the moment just from the first one)
            if (isIso)
            {
                var vs = iso.VolumeDescriptors.Where(a => a != null).ToArray().First();

                // translate the vd
                discI.Data._ISOData          = PopulateISOData(vs);
                discI.Data._ISOData.ISOFiles = iso.Root.Children;
                ifn = null;
            }

            // populate basic disc data
            int dataTracks  = 0;
            int audioTracks = 0;

            foreach (var t in disc.Structure.Sessions.Where(a => a != null))
            {
                for (int i = 0; i < t.Tracks.Count(); i++)
                {
                    if (t.Tracks[i].IsData == true)
                    {
                        dataTracks++;
                        continue;
                    }

                    if (t.Tracks[i].IsAudio == true)
                    {
                        audioTracks++;
                        continue;
                    }
                }
            }

            discI.Data.TotalAudioTracks = audioTracks;
            discI.Data.TotalDataTracks  = dataTracks;
            discI.Data.TotalTracks      = audioTracks + dataTracks;

            discI.DiscStructure = disc.Structure;

            // do actual interrogation
            switch (detectedDiscType)
            {
            case DetectedDiscType.UnknownFormat:
            case DetectedDiscType.UnknownCDFS:
                discI.DetectedDiscType = InterrogateALL();
                break;

            default:
                discI.DetectedDiscType = InterrogateSpecific(detectedDiscType);
                break;
            }


            discI.DiscTypeString = discI.DetectedDiscType.ToString();
            discI.DiscViewString = discView.ToString();

            return(discI);
        }
Ejemplo n.º 45
0
 private void AddDiscData(Disc disc)
 {
     AddRow();
     AddControl(CreateLabel($"Disc {disc.DiscNo}", null, true), 1, _populatingRow++, 4);
 }
Ejemplo n.º 46
0
        // get a disc by number
        public Disc GetDisc(int boxnumber, int casenumber, int discnumber)
        {
            Disc di = DALServices.GetDisc(context, boxnumber, casenumber, discnumber);

            return(di);
        }
Ejemplo n.º 47
0
        private void buttonOk_Click(object sender, EventArgs e)
        {
            using (DBContext dB = new DBContext())
            {
                Disc d = new Disc
                {
                    name       = NameTxt_box.Text,
                    discCount  = Convert.ToInt32(DiscsCount_txtBox.Text),
                    treckCount = Convert.ToInt32(TreckCount_textBox.Text),

                    selfCost  = Convert.ToDecimal(SelfCost_txtBox.Text),
                    sellPrice = Convert.ToDecimal(SellPrice_txtBox.Text)
                };

                if (NewBand_txtBox.Text == null || NewBand_txtBox.Text == "")
                {
                    foreach (Band item in dB.bands)
                    {
                        if (item.name == BandName_cmbBox.Text)
                        {
                            d.band = item;
                        }
                    }
                }
                else
                {
                    Band b = new Band {
                        name = NewBand_txtBox.Text
                    };
                    d.band = b;
                    dB.bands.Add(b);
                }

                if (NewPublisher_txtBox.Text == null || NewPublisher_txtBox.Text == "")
                {
                    foreach (Publisher item in dB.publishers)
                    {
                        if (item.name == Publisher_cmbBox.Text)
                        {
                            d.publisher = item;
                        }
                    }
                }
                else
                {
                    Publisher p = new Publisher {
                        name = NewPublisher_txtBox.Text
                    };
                    d.publisher = p;
                    dB.publishers.Add(p);
                }

                if (NewGeners_txtBox.Text == null || NewGeners_txtBox.Text == "")
                {
                    foreach (Genre item in dB.genres)
                    {
                        if (item.name == Geners_cmbBox.Text)
                        {
                            d.genre = item;
                        }
                    }
                }
                else
                {
                    Genre g = new Genre {
                        name = NewGeners_txtBox.Text
                    };
                    d.genre = g;
                    dB.genres.Add(g);
                }

                dB.discs.Add(d);
                dB.SaveChanges();

                Hide();
            }
        }
Ejemplo n.º 48
0
 /// <summary>
 /// Adds a disc (from the model!!!) to the tower viewmodel
 /// </summary>
 /// <param name="disc">The disc from the model to add to the tower viewmodel.</param>
 private void AddDisc(Disc disc)
 {
     Discs.Add(new Disc_ViewModel(disc));
 }
Ejemplo n.º 49
0
        public override void Activate()
        {
            if (_content == null)
            {
                _content = _content = new ContentManager(ScreenManager.Game.Services, "Content");
            }

            font            = _content.Load <SpriteFont>("GoudyStout");
            high_score_font = _content.Load <SpriteFont>("Score");

            disc          = new Disc();
            disc.Position = new Vector2(200, 750);

            basket = new DiscBasket(new Vector2(1750, 100));

            //Generate random wind for the start
            windAngle     = (float)(rand.NextDouble() * 2 * Math.PI);
            windDirection = new Vector2((float)Math.Cos(windAngle), (float)Math.Sin(windAngle));

            bushes = new Bush[]
            {
                new Bush(new Vector2(800, 0), GameProject1.Direction.Up, true),
                new Bush(new Vector2(540, 1000), GameProject1.Direction.Right, false),
                new Bush(new Vector2(1700, 700), GameProject1.Direction.Left, false),
                new Bush(new Vector2(400, 700), GameProject1.Direction.Up, true),
                new Bush(new Vector2(600, 1000), GameProject1.Direction.Right, false),
                new Bush(new Vector2(250, 125), GameProject1.Direction.Right, false),
                new Bush(new Vector2(1500, 750), GameProject1.Direction.Up, true),
                new Bush(new Vector2(1125, 350), GameProject1.Direction.Down, true),
                new Bush(new Vector2(1600, 10), GameProject1.Direction.Down, true),
            };
            trees = new Tree[]
            {
                new Tree(new Vector2(960, 540), TreeType.tall_green_tree),
                new Tree(new Vector2(200, 25), TreeType.tall_green_tree),
                new Tree(new Vector2(700, 700), TreeType.tall_green_tree),
                new Tree(new Vector2(960, 200), TreeType.stump),
                new Tree(new Vector2(375, 175), TreeType.stump),
                new Tree(new Vector2(1150, 150), TreeType.normal_green_tree),
                new Tree(new Vector2(200, 400), TreeType.normal_green_tree),
                new Tree(new Vector2(1000, 800), TreeType.pink_tree),
                new Tree(new Vector2(600, 400), TreeType.pink_tree),
                new Tree(new Vector2(1600, 700), TreeType.normal_brown_tree),
                new Tree(new Vector2(150, 850), TreeType.normal_brown_tree),
                new Tree(new Vector2(575, 700), TreeType.stump),
                new Tree(new Vector2(1500, 225), TreeType.dead_tree),
                new Tree(new Vector2(75, 700), TreeType.dead_tree),
                new Tree(new Vector2(1250, 625), TreeType.normal_green_tree)
            };
            basket.LoadContent(_content);
            windArrow = _content.Load <Texture2D>("windArrow");
            foreach (Bush bush in bushes)
            {
                bush.LoadContent(_content);
            }
            foreach (Tree tree in trees)
            {
                tree.LoadContent(_content);
            }
            disc.LoadContent(_content);
            font            = _content.Load <SpriteFont>("GoudyStout");
            high_score_font = _content.Load <SpriteFont>("Score");

            //Particle engine stuff
            Rectangle source = windAngle < Math.PI ? new Rectangle(-960, -20, 1920 * 2, 10) : new Rectangle(-960, 1100, 1920 * 2, 10);

            windParticleSystem = new WindParticleSystem(ScreenManager.Game, source, windDirection);
            ScreenManager.Game.Components.Add(windParticleSystem);

            Color[] fireworkColors = new Color[]
            {
                Color.Fuchsia,
                Color.Red,
                Color.Crimson,
                Color.CadetBlue,
                Color.Aqua,
                Color.HotPink,
                Color.LimeGreen
            };

            Color[] bushHitColors = new Color[]
            {
                Color.Brown,
                Color.DarkGreen,
                Color.Tan,
                Color.SandyBrown,
                Color.DarkRed,
                Color.LightGreen
            };
            basketParticleSystem = new ExplosionParticleSystem(ScreenManager.Game, 20, fireworkColors, true);
            ScreenManager.Game.Components.Add(basketParticleSystem);

            bushParticleSystem = new ExplosionParticleSystem(ScreenManager.Game, 20, bushHitColors, false);
            ScreenManager.Game.Components.Add(bushParticleSystem);

            //Music/Sound effects
            sfxBushHit              = _content.Load <SoundEffect>("bush_hit");
            sfxChains               = _content.Load <SoundEffect>("DG-Putt");
            backgroundMusic         = _content.Load <Song>("background_music");
            MediaPlayer.IsRepeating = true;
            MediaPlayer.Play(backgroundMusic);
            base.Activate();
        }
Ejemplo n.º 50
0
 public ScsiCDBus(PCEngine pce, Disc disc)
 {
     this.pce         = pce;
     this.disc        = disc;
     DiscSectorReader = new DiscSectorReader(disc);
 }
Ejemplo n.º 51
0
        public void ClassDiscExists()
        {
            Disc Disc = null;

            Assert.Null(Disc);
        }
Ejemplo n.º 52
0
        public bool LoadRom(string path, CoreComm nextComm, bool forceAccurateCore = false,
                            int recursiveCount = 0) // forceAccurateCore is currently just for Quicknes vs Neshawk but could be used for other situations
        {
            if (recursiveCount > 1)                 // hack to stop recursive calls from endlessly rerunning if we can't load it
            {
                DoLoadErrorCallback("Failed multiple attempts to load ROM.", "");
                return(false);
            }

            bool cancel = false;

            if (path == null)
            {
                return(false);
            }

            using (var file = new HawkFile())
            {
                //only try mounting a file if a filename was given
                if (!string.IsNullOrEmpty(path))
                {
                    // lets not use this unless we need to
                    // file.NonArchiveExtensions = romExtensions;
                    file.Open(path);

                    // if the provided file doesnt even exist, give up!
                    if (!file.Exists)
                    {
                        return(false);
                    }
                }

                CanonicalFullPath = file.CanonicalFullPath;

                IEmulator nextEmulator = null;
                RomGame   rom          = null;
                GameInfo  game         = null;

                try
                {
                    string ext = null;

                    if (AsLibretro)
                    {
                        string codePathPart = Path.GetFileNameWithoutExtension(nextComm.LaunchLibretroCore);

                        var retro = new LibRetroEmulator(nextComm, nextComm.LaunchLibretroCore);
                        nextEmulator = retro;

                        //kind of dirty.. we need to stash this, and then we can unstash it in a moment, in case the core doesnt fail
                        var oldGame = Global.Game;

                        if (retro.Description.SupportsNoGame && string.IsNullOrEmpty(path))
                        {
                            //must be done before LoadNoGame (which triggers retro_init and the paths to be consumed by the core)
                            //game name == name of core
                            var gameName = codePathPart;
                            Global.Game = game = new GameInfo {
                                Name = gameName, System = "Libretro"
                            };

                            //if we are allowed to run NoGame and we dont have a game, boot up the core that way
                            bool ret = retro.LoadNoGame();

                            Global.Game = oldGame;

                            if (!ret)
                            {
                                DoLoadErrorCallback("LibretroNoGame failed to load. This is weird", "Libretro");
                                retro.Dispose();
                                return(false);
                            }
                        }
                        else
                        {
                            bool ret;

                            //must be done before LoadNoGame (which triggers retro_init and the paths to be consumed by the core)
                            //game name == name of core + extensionless_game_filename
                            var gameName = Path.Combine(codePathPart, Path.GetFileNameWithoutExtension(file.Name));
                            Global.Game = game = new GameInfo {
                                Name = gameName, System = "Libretro"
                            };

                            //if the core requires an archive file, then try passing the filename of the archive
                            //(but do we ever need to actually load the contents of the archive file into ram?)
                            if (retro.Description.NeedsArchives)
                            {
                                if (file.IsArchiveMember)
                                {
                                    throw new InvalidOperationException("Should not have bound file member for libretro block_extract core");
                                }
                                ret = retro.LoadPath(file.FullPathWithoutMember);
                            }
                            else
                            {
                                //otherwise load the data or pass the filename, as requested. but..
                                if (retro.Description.NeedsRomAsPath && file.IsArchiveMember)
                                {
                                    throw new InvalidOperationException("Cannot pass archive member to libretro needs_fullpath core");
                                }

                                if (retro.Description.NeedsRomAsPath)
                                {
                                    ret = retro.LoadPath(file.FullPathWithoutMember);
                                }
                                else
                                {
                                    ret = HandleArchiveBinding(file);
                                    if (ret)
                                    {
                                        ret = retro.LoadData(file.ReadAllBytes());
                                    }
                                }
                            }

                            Global.Game = oldGame;

                            if (!ret)
                            {
                                DoLoadErrorCallback("Libretro failed to load the given file. This is probably due to a core/content mismatch. Moreover, the process is now likely to be hosed. We suggest you restart the program.", "Libretro");
                                retro.Dispose();
                                return(false);
                            }
                        }
                    }
                    else
                    {
                        //if not libretro:

                        //do extension checknig
                        ext = file.Extension.ToLowerInvariant();

                        //do the archive binding we had to skip
                        if (!HandleArchiveBinding(file))
                        {
                            return(false);
                        }
                    }

                    if (string.IsNullOrEmpty(ext))
                    {
                    }
                    else if (ext == ".m3u")
                    {
                        //HACK ZONE - currently only psx supports m3u
                        M3U_File m3u;
                        using (var sr = new StreamReader(path))
                            m3u = M3U_File.Read(sr);
                        if (m3u.Entries.Count == 0)
                        {
                            throw new InvalidOperationException("Can't load an empty M3U");
                        }
                        //load discs for all the m3u
                        m3u.Rebase(Path.GetDirectoryName(path));
                        List <Disc>   discs     = new List <Disc>();
                        List <string> discNames = new List <string>();
                        StringWriter  sw        = new StringWriter();
                        foreach (var e in m3u.Entries)
                        {
                            Disc   disc     = null;
                            string discPath = e.Path;

                            //--- load the disc in a context which will let us abort if it's going to take too long
                            var discMountJob = new DiscMountJob {
                                IN_FromPath = discPath
                            };
                            discMountJob.IN_SlowLoadAbortThreshold = 8;
                            discMountJob.Run();
                            disc = discMountJob.OUT_Disc;

                            if (discMountJob.OUT_SlowLoadAborted)
                            {
                                DoLoadErrorCallback("This disc would take too long to load. Run it through discohawk first, or find a new rip because this one is probably junk", "", LoadErrorType.DiscError);
                                return(false);
                            }

                            if (discMountJob.OUT_ErrorLevel)
                            {
                                throw new InvalidOperationException("\r\n" + discMountJob.OUT_Log);
                            }

                            if (disc == null)
                            {
                                throw new InvalidOperationException("Can't load one of the files specified in the M3U");
                            }

                            var discName = Path.GetFileNameWithoutExtension(discPath);
                            discNames.Add(discName);
                            discs.Add(disc);

                            var discType = new DiscIdentifier(disc).DetectDiscType();
                            sw.WriteLine("{0}", Path.GetFileName(discPath));
                            if (discType == DiscType.SonyPSX)
                            {
                                string discHash = new DiscHasher(disc).Calculate_PSX_BizIDHash().ToString("X8");
                                game = Database.CheckDatabase(discHash);
                                if (game == null || game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase)
                                {
                                    sw.WriteLine("Disc could not be identified as known-good. Look for a better rip.");
                                }
                                else
                                {
                                    sw.WriteLine("Disc was identified (99.99% confidently) as known good with disc id hash CRC32:{0:X8}", discHash);
                                    sw.WriteLine("Nonetheless it could be an unrecognized romhack or patched version.");
                                    sw.WriteLine("According to redump.org, the ideal hash for entire disc is: CRC32:{0:X8}", game.GetStringValue("dh"));
                                    sw.WriteLine("The file you loaded hasn't been hashed entirely (it would take too long)");
                                    sw.WriteLine("Compare it with the full hash calculated by the PSX menu's Hash Discs tool");
                                }
                            }
                            else
                            {
                                sw.WriteLine("Not a PSX disc");
                            }
                            sw.WriteLine("-------------------------");
                        }

                        nextEmulator = new Octoshock(nextComm, discs, discNames, null, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                        nextEmulator.CoreComm.RomStatusDetails = sw.ToString();
                        game = new GameInfo {
                            Name = Path.GetFileNameWithoutExtension(file.Name)
                        };
                        game.System = "PSX";
                    }
                    else if (ext == ".iso" || ext == ".cue" || ext == ".ccd")
                    {
                        if (file.IsArchive)
                        {
                            throw new InvalidOperationException("Can't load CD files from archives!");
                        }

                        string discHash = null;

                        //--- load the disc in a context which will let us abort if it's going to take too long
                        var discMountJob = new DiscMountJob {
                            IN_FromPath = path
                        };
                        discMountJob.IN_SlowLoadAbortThreshold = 8;
                        discMountJob.Run();

                        if (discMountJob.OUT_SlowLoadAborted)
                        {
                            DoLoadErrorCallback("This disc would take too long to load. Run it through discohawk first, or find a new rip because this one is probably junk", "", LoadErrorType.DiscError);
                            return(false);
                        }

                        if (discMountJob.OUT_ErrorLevel)
                        {
                            throw new InvalidOperationException("\r\n" + discMountJob.OUT_Log);
                        }

                        var disc = discMountJob.OUT_Disc;
                        //-----------

                        //TODO - use more sophisticated IDer
                        var discType = new DiscIdentifier(disc).DetectDiscType();
                        if (discType == DiscType.SonyPSX)
                        {
                            discHash = new DiscHasher(disc).Calculate_PSX_BizIDHash().ToString("X8");
                        }
                        else
                        {
                            discHash = new DiscHasher(disc).OldHash();
                        }

                        game = Database.CheckDatabase(discHash);
                        if (game == null)
                        {
                            // try to use our wizard methods
                            game = new GameInfo {
                                Name = Path.GetFileNameWithoutExtension(file.Name), Hash = discHash
                            };

                            switch (new DiscIdentifier(disc).DetectDiscType())
                            {
                            case DiscType.SegaSaturn:
                                game.System = "SAT";
                                break;

                            case DiscType.SonyPSP:
                                game.System = "PSP";
                                break;

                            default:
                            case DiscType.SonyPSX:
                                game.System = "PSX";
                                break;

                            case DiscType.MegaCD:
                                game.System = "GEN";
                                break;

                            case DiscType.AudioDisc:
                            case DiscType.TurboCD:
                            case DiscType.UnknownCDFS:
                            case DiscType.UnknownFormat:
                                game.System = "PCECD";
                                break;
                            }
                        }

                        switch (game.System)
                        {
                        case "GEN":
                            var genesis = new GPGX(
                                nextComm, null, disc, GetCoreSettings <GPGX>(), GetCoreSyncSettings <GPGX>());
                            nextEmulator = genesis;
                            break;

                        case "SAT":
                            nextEmulator = new Yabause(nextComm, disc, GetCoreSyncSettings <Yabause>());
                            break;

                        case "PSP":
                            nextEmulator = new PSP(nextComm, file.Name);
                            break;

                        case "PSX":
                            nextEmulator = new Octoshock(nextComm, new List <Disc>(new[] { disc }), new List <string>(new[] { Path.GetFileNameWithoutExtension(path) }), null, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                            if (game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase)
                            {
                                nextEmulator.CoreComm.RomStatusDetails = "Disc could not be identified as known-good. Look for a better rip.";
                            }
                            else
                            {
                                StringWriter sw = new StringWriter();
                                sw.WriteLine("Disc was identified (99.99% confidently) as known good with disc id hash CRC32:{0:X8}", discHash);
                                sw.WriteLine("Nonetheless it could be an unrecognized romhack or patched version.");
                                sw.WriteLine("According to redump.org, the ideal hash for entire disc is: CRC32:{0:X8}", game.GetStringValue("dh"));
                                sw.WriteLine("The file you loaded hasn't been hashed entirely (it would take too long)");
                                sw.WriteLine("Compare it with the full hash calculated by the PSX menu's Hash Discs tool");
                                nextEmulator.CoreComm.RomStatusDetails = sw.ToString();
                            }
                            break;

                        case "PCE":
                        case "PCECD":
                            nextEmulator = new PCEngine(nextComm, game, disc, GetCoreSettings <PCEngine>(), GetCoreSyncSettings <PCEngine>());
                            break;
                        }
                    }
                    else if (file.Extension.ToLowerInvariant() == ".xml")
                    {
                        try
                        {
                            var xmlGame = XmlGame.Create(file);                             // if load fails, are we supposed to retry as a bsnes XML????????
                            game = xmlGame.GI;

                            switch (game.System)
                            {
                            case "GB":
                            case "DGB":
                                // adelikat: remove need for tags to be hardcoded to left and right, we should clean this up, also maybe the DGB core should just take the xml file and handle it itself
                                var leftBytes  = xmlGame.Assets.First().Value;
                                var rightBytes = xmlGame.Assets.Skip(1).First().Value;

                                var left  = Database.GetGameInfo(leftBytes, "left.gb");
                                var right = Database.GetGameInfo(rightBytes, "right.gb");
                                nextEmulator = new GambatteLink(
                                    nextComm,
                                    left,
                                    leftBytes,
                                    right,
                                    rightBytes,
                                    GetCoreSettings <GambatteLink>(),
                                    GetCoreSyncSettings <GambatteLink>(),
                                    Deterministic);

                                // other stuff todo
                                break;

                            case "AppleII":
                                var assets = xmlGame.Assets.Select(a => Database.GetGameInfo(a.Value, a.Key));
                                var roms   = xmlGame.Assets.Select(a => a.Value);
                                nextEmulator = new AppleII(
                                    nextComm,
                                    assets,
                                    roms,
                                    (AppleII.Settings)GetCoreSettings <AppleII>());
                                break;

                            case "C64":
                                nextEmulator = new C64(
                                    nextComm,
                                    xmlGame.Assets.Select(a => a.Value),
                                    (C64.C64Settings)GetCoreSettings <C64>(),
                                    (C64.C64SyncSettings)GetCoreSyncSettings <C64>()
                                    );
                                break;

                            case "PSX":
                                var entries   = xmlGame.AssetFullPaths;
                                var discs     = new List <Disc>();
                                var discNames = new List <string>();
                                var sw        = new StringWriter();
                                foreach (var e in entries)
                                {
                                    Disc   disc     = null;
                                    string discPath = e;

                                    //--- load the disc in a context which will let us abort if it's going to take too long
                                    var discMountJob = new DiscMountJob {
                                        IN_FromPath = discPath
                                    };
                                    discMountJob.IN_SlowLoadAbortThreshold = 8;
                                    discMountJob.Run();
                                    disc = discMountJob.OUT_Disc;

                                    if (discMountJob.OUT_SlowLoadAborted)
                                    {
                                        DoLoadErrorCallback("This disc would take too long to load. Run it through discohawk first, or find a new rip because this one is probably junk", "PSX", LoadErrorType.DiscError);
                                        return(false);
                                    }

                                    if (discMountJob.OUT_ErrorLevel)
                                    {
                                        throw new InvalidOperationException("\r\n" + discMountJob.OUT_Log);
                                    }

                                    if (disc == null)
                                    {
                                        throw new InvalidOperationException("Can't load one of the files specified in the M3U");
                                    }

                                    var discName = Path.GetFileNameWithoutExtension(discPath);
                                    discNames.Add(discName);
                                    discs.Add(disc);

                                    var discType = new DiscIdentifier(disc).DetectDiscType();
                                    sw.WriteLine("{0}", Path.GetFileName(discPath));
                                    if (discType == DiscType.SonyPSX)
                                    {
                                        string discHash = new DiscHasher(disc).Calculate_PSX_BizIDHash().ToString("X8");
                                        game = Database.CheckDatabase(discHash);
                                        if (game == null || game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase)
                                        {
                                            sw.WriteLine("Disc could not be identified as known-good. Look for a better rip.");
                                        }
                                        else
                                        {
                                            sw.WriteLine("Disc was identified (99.99% confidently) as known good with disc id hash CRC32:{0:X8}", discHash);
                                            sw.WriteLine("Nonetheless it could be an unrecognized romhack or patched version.");
                                            sw.WriteLine("According to redump.org, the ideal hash for entire disc is: CRC32:{0:X8}", game.GetStringValue("dh"));
                                            sw.WriteLine("The file you loaded hasn't been hashed entirely (it would take too long)");
                                            sw.WriteLine("Compare it with the full hash calculated by the PSX menu's Hash Discs tool");
                                        }
                                    }
                                    else
                                    {
                                        sw.WriteLine("Not a PSX disc");
                                    }
                                    sw.WriteLine("-------------------------");
                                }

                                // todo: copy pasta from PSX .cue section
                                nextEmulator = new Octoshock(nextComm, discs, discNames, null, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                                nextEmulator.CoreComm.RomStatusDetails = sw.ToString();
                                game = new GameInfo {
                                    Name = Path.GetFileNameWithoutExtension(file.Name)
                                };
                                game.System = "PSX";

                                break;

                            default:
                                return(false);
                            }
                        }
                        catch (Exception ex)
                        {
                            try
                            {
                                // need to get rid of this hack at some point
                                rom = new RomGame(file);
                                ((CoreFileProvider)nextComm.CoreFileProvider).SubfileDirectory = Path.GetDirectoryName(path.Replace("|", string.Empty));                                 // Dirty hack to get around archive filenames (since we are just getting the directory path, it is safe to mangle the filename
                                byte[] romData = null;
                                byte[] xmlData = rom.FileData;

                                game        = rom.GameInfo;
                                game.System = "SNES";

                                var snes = new LibsnesCore(game, romData, Deterministic, xmlData, nextComm, GetCoreSettings <LibsnesCore>(), GetCoreSyncSettings <LibsnesCore>());
                                nextEmulator = snes;
                            }
                            catch
                            {
                                DoLoadErrorCallback(ex.ToString(), "DGB", LoadErrorType.XML);
                                return(false);
                            }
                        }
                    }
                    else if (file.Extension.ToLowerInvariant() == ".psf" || file.Extension.ToLowerInvariant() == ".minipsf")
                    {
                        Func <Stream, int, byte[]> cbDeflater = (Stream instream, int size) =>
                        {
                            var          inflater = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater(false);
                            var          iis      = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream(instream, inflater);
                            MemoryStream ret      = new MemoryStream();
                            iis.CopyTo(ret);
                            return(ret.ToArray());
                        };
                        PSF psf = new PSF();
                        psf.Load(path, cbDeflater);
                        nextEmulator = new Octoshock(nextComm, psf, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                        nextEmulator.CoreComm.RomStatusDetails = "It's a PSF, what do you want. Oh, tags maybe?";

                        //total garbage, this
                        rom  = new RomGame(file);
                        game = rom.GameInfo;
                    }
                    else if (ext != null)                     // most extensions
                    {
                        rom = new RomGame(file);

                        //hacky for now
                        if (file.Extension.ToLowerInvariant() == ".exe")
                        {
                            rom.GameInfo.System = "PSX";
                        }
                        else if (file.Extension.ToLowerInvariant() == ".nsf")
                        {
                            rom.GameInfo.System = "NES";
                        }


                        if (string.IsNullOrEmpty(rom.GameInfo.System))
                        {
                            // Has the user picked a preference for this extension?
                            if (PreferredPlatformIsDefined(rom.Extension.ToLowerInvariant()))
                            {
                                rom.GameInfo.System = Global.Config.PreferredPlatformsForExtensions[rom.Extension.ToLowerInvariant()];
                            }
                            else if (ChoosePlatform != null)
                            {
                                var result = ChoosePlatform(rom);
                                if (!string.IsNullOrEmpty(result))
                                {
                                    rom.GameInfo.System = result;
                                }
                                else
                                {
                                    cancel = true;
                                }
                            }
                        }

                        game = rom.GameInfo;

                        var isXml = false;

                        // other xml has already been handled
                        if (file.Extension.ToLowerInvariant() == ".xml")
                        {
                            game.System = "SNES";
                            isXml       = true;
                        }


                        CoreInventory.Core core = null;

                        switch (game.System)
                        {
                        default:
                            core = CoreInventory.Instance[game.System];
                            break;

                        case null:
                            // The user picked nothing in the Core picker
                            break;

                        case "83P":
                            var ti83Bios     = ((CoreFileProvider)nextComm.CoreFileProvider).GetFirmware("TI83", "Rom", true);
                            var ti83BiosPath = ((CoreFileProvider)nextComm.CoreFileProvider).GetFirmwarePath("TI83", "Rom", true);
                            using (var ti83AsHawkFile = new HawkFile())
                            {
                                ti83AsHawkFile.Open(ti83BiosPath);
                                var ti83BiosAsRom = new RomGame(ti83AsHawkFile);
                                var ti83          = new TI83(nextComm, ti83BiosAsRom.GameInfo, ti83Bios, GetCoreSettings <TI83>());
                                ti83.LinkPort.SendFileToCalc(File.OpenRead(path), false);
                                nextEmulator = ti83;
                            }
                            break;

                        case "SNES":
                            if (Global.Config.SNES_InSnes9x && VersionInfo.DeveloperBuild)
                            {
                                core = CoreInventory.Instance["SNES", "Snes9x"];
                            }
                            else
                            {
                                // need to get rid of this hack at some point
                                ((CoreFileProvider)nextComm.CoreFileProvider).SubfileDirectory = Path.GetDirectoryName(path.Replace("|", String.Empty));                                         // Dirty hack to get around archive filenames (since we are just getting the directory path, it is safe to mangle the filename
                                var romData = isXml ? null : rom.FileData;
                                var xmlData = isXml ? rom.FileData : null;
                                var snes    = new LibsnesCore(game, romData, Deterministic, xmlData, nextComm, GetCoreSettings <LibsnesCore>(), GetCoreSyncSettings <LibsnesCore>());
                                nextEmulator = snes;
                            }

                            break;

                        case "NES":
                            if (!Global.Config.NES_InQuickNES || forceAccurateCore)
                            {
                                core = CoreInventory.Instance["NES", "NesHawk"];
                            }
                            else
                            {
                                core = CoreInventory.Instance["NES", "QuickNes"];
                            }

                            break;

                        case "GB":
                        case "GBC":
                            if (!Global.Config.GB_AsSGB)
                            {
                                core = CoreInventory.Instance["GB", "Gambatte"];
                            }
                            else
                            {
                                try
                                {
                                    game.System = "SNES";
                                    game.AddOption("SGB");
                                    var snes = new LibsnesCore(game, rom.FileData, Deterministic, null, nextComm, GetCoreSettings <LibsnesCore>(), GetCoreSyncSettings <LibsnesCore>());
                                    nextEmulator = snes;
                                }
                                catch
                                {
                                    // failed to load SGB bios or game does not support SGB mode.
                                    // To avoid catch-22, disable SGB mode
                                    Global.Config.GB_AsSGB = false;
                                    throw;
                                }
                            }

                            break;

                        case "A78":
                            var gamedbpath = Path.Combine(PathManager.GetExeDirectoryAbsolute(), "gamedb", "EMU7800.csv");
                            nextEmulator = new Atari7800(nextComm, game, rom.RomData, gamedbpath);
                            break;

                        case "C64":
                            var c64 = new C64(nextComm, Enumerable.Repeat(rom.RomData, 1), GetCoreSettings <C64>(), GetCoreSyncSettings <C64>());
                            nextEmulator = c64;
                            break;

                        case "GBA":
                            //core = CoreInventory.Instance["GBA", "Meteor"];
                            if (Global.Config.GBA_UsemGBA)
                            {
                                core = CoreInventory.Instance["GBA", "mGBA"];
                            }
                            else
                            {
                                core = CoreInventory.Instance["GBA", "VBA-Next"];
                            }
                            break;

                        case "PSX":
                            nextEmulator = new Octoshock(nextComm, null, null, rom.FileData, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                            nextEmulator.CoreComm.RomStatusDetails = "PSX etc.";
                            break;

                        case "GEN":
                            // discard "Genplus-gx64", auto-added due to implementing IEmulator
                            core = CoreInventory.Instance["GEN", "Genplus-gx"];
                            break;
                        }

                        if (core != null)
                        {
                            // use coreinventory
                            nextEmulator = core.Create(nextComm, game, rom.RomData, rom.FileData, Deterministic, GetCoreSettings(core.Type), GetCoreSyncSettings(core.Type));
                        }
                    }

                    if (nextEmulator == null)
                    {
                        if (!cancel)
                        {
                            DoLoadErrorCallback("No core could load the rom.", null);
                        }
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    string system = null;
                    if (game != null)
                    {
                        system = game.System;
                    }

                    // all of the specific exceptions we're trying to catch here aren't expected to have inner exceptions,
                    // so drill down in case we got a TargetInvocationException or something like that
                    while (ex.InnerException != null)
                    {
                        ex = ex.InnerException;
                    }

                    // Specific hack here, as we get more cores of the same system, this isn't scalable
                    if (ex is UnsupportedGameException)
                    {
                        if (system == "NES")
                        {
                            DoMessageCallback("Unable to use quicknes, using NESHawk instead");
                        }

                        return(LoadRom(path, nextComm, true, recursiveCount + 1));
                    }
                    else if (ex is MissingFirmwareException)
                    {
                        DoLoadErrorCallback(ex.Message, system, path, Deterministic, LoadErrorType.MissingFirmware);
                    }
                    else if (ex is CGBNotSupportedException)
                    {
                        // Note: GB as SGB was set to false by this point, otherwise we would want to do it here
                        DoMessageCallback("Failed to load a GB rom in SGB mode.  Disabling SGB Mode.");
                        return(LoadRom(path, nextComm, false, recursiveCount + 1));
                    }
                    else
                    {
                        DoLoadErrorCallback("A core accepted the rom, but threw an exception while loading it:\n\n" + ex, system);
                    }

                    return(false);
                }

                Rom            = rom;
                LoadedEmulator = nextEmulator;
                Game           = game;
                return(true);
            }
        }
Ejemplo n.º 53
0
 public void TowerTopLevelDiscIsReadOnlyProperty()
 {
     var  Tower = new Tower();
     Disc Disc  = Tower.TopLevelDisc;
 }
Ejemplo n.º 54
0
        public Dictionary <string, Tuple <string, string> > Diff(AudioTag other)
        {
            var output = new Dictionary <string, Tuple <string, string> >();

            if (!IsValid || !other.IsValid)
            {
                return(output);
            }

            if (Title != other.Title)
            {
                output.Add("Title", Tuple.Create(Title, other.Title));
            }

            if (!Performers.SequenceEqual(other.Performers))
            {
                var oldValue = Performers.Any() ? string.Join(" / ", Performers) : null;
                var newValue = other.Performers.Any() ? string.Join(" / ", other.Performers) : null;

                output.Add("Author", Tuple.Create(oldValue, newValue));
            }

            if (Book != other.Book)
            {
                output.Add("Book", Tuple.Create(Book, other.Book));
            }

            if (!BookAuthors.SequenceEqual(other.BookAuthors))
            {
                var oldValue = BookAuthors.Any() ? string.Join(" / ", BookAuthors) : null;
                var newValue = other.BookAuthors.Any() ? string.Join(" / ", other.BookAuthors) : null;

                output.Add("Book Author", Tuple.Create(oldValue, newValue));
            }

            if (Track != other.Track)
            {
                output.Add("Track", Tuple.Create(Track.ToString(), other.Track.ToString()));
            }

            if (TrackCount != other.TrackCount)
            {
                output.Add("Track Count", Tuple.Create(TrackCount.ToString(), other.TrackCount.ToString()));
            }

            if (Disc != other.Disc)
            {
                output.Add("Disc", Tuple.Create(Disc.ToString(), other.Disc.ToString()));
            }

            if (DiscCount != other.DiscCount)
            {
                output.Add("Disc Count", Tuple.Create(DiscCount.ToString(), other.DiscCount.ToString()));
            }

            if (Media != other.Media)
            {
                output.Add("Media Format", Tuple.Create(Media, other.Media));
            }

            if (Date != other.Date)
            {
                var oldValue = Date.HasValue ? Date.Value.ToString("yyyy-MM-dd") : null;
                var newValue = other.Date.HasValue ? other.Date.Value.ToString("yyyy-MM-dd") : null;
                output.Add("Date", Tuple.Create(oldValue, newValue));
            }

            if (OriginalReleaseDate != other.OriginalReleaseDate)
            {
                // Id3v2.3 tags can only store the year, not the full date
                if (OriginalReleaseDate.HasValue &&
                    OriginalReleaseDate.Value.Month == 1 &&
                    OriginalReleaseDate.Value.Day == 1)
                {
                    if (OriginalReleaseDate.Value.Year != other.OriginalReleaseDate.Value.Year)
                    {
                        output.Add("Original Year", Tuple.Create(OriginalReleaseDate.Value.Year.ToString(), other.OriginalReleaseDate.Value.Year.ToString()));
                    }
                }
                else
                {
                    var oldValue = OriginalReleaseDate.HasValue ? OriginalReleaseDate.Value.ToString("yyyy-MM-dd") : null;
                    var newValue = other.OriginalReleaseDate.HasValue ? other.OriginalReleaseDate.Value.ToString("yyyy-MM-dd") : null;
                    output.Add("Original Release Date", Tuple.Create(oldValue, newValue));
                }
            }

            if (Publisher != other.Publisher)
            {
                output.Add("Label", Tuple.Create(Publisher, other.Publisher));
            }

            if (!Genres.SequenceEqual(other.Genres))
            {
                output.Add("Genres", Tuple.Create(string.Join(" / ", Genres), string.Join(" / ", other.Genres)));
            }

            if (ImageSize != other.ImageSize)
            {
                output.Add("Image Size", Tuple.Create(ImageSize.ToString(), other.ImageSize.ToString()));
            }

            return(output);
        }
Ejemplo n.º 55
0
        public void DiscDiameterValueViaConstructor(int diameter)
        {
            var Disc = new Disc(diameter);

            Assert.Equal(diameter, Disc.Diameter);
        }
Ejemplo n.º 56
0
 // Start is called before the first frame update
 void Start()
 {
     disc     = GetComponent <Disc>();
     animTime = 0;
     Spawn(0);
 }
 //TODO: Refactor...move to a conversion class
 string ConvertDiscToFillColor(Disc disc)
 {
     if (disc == Disc.Red) {
     return "Red";
       }
       if (disc == Disc.Black) {
     return "Black";
       }
       return "AliceBlue";
 }
Ejemplo n.º 58
0
        public override string ToString()
        {
            var d = Disc == null ? "empty" : Disc.ToString();

            return($"C={Column} R={Row} Disc={d}");
        }
 void SwitchTurn(Disc disc)
 {
     BlackPlayersTurn = disc == Disc.Red ? "Visible" : "Hidden";
       RedPlayersTurn = disc == Disc.Black ? "Visible" : "Hidden";
       CurrentPlayerDisc = disc == Disc.Red ? Disc.Black : Disc.Red;
 }
Ejemplo n.º 60
0
 public void AddDisc(Disc disc)
 {
     discs.Add(disc);
 }