x01.Tetris: 俄羅斯方塊

来源:http://www.cnblogs.com/china_x01/archive/2016/03/08/5253556.html
-Advertisement-
Play Games

最強大腦有個小孩玩俄羅斯方塊游戲神乎其技,那麼,就寫一個吧,玩玩而已。 由於邏輯簡單,又作了一些簡化,所以代碼並不多。 using System; using System.Collections.Generic; using System.Linq; using System.Windows; u


最強大腦有個小孩玩俄羅斯方塊游戲神乎其技,那麼,就寫一個吧,玩玩而已。

由於邏輯簡單,又作了一些簡化,所以代碼並不多。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace x01.Tetris
{
    public enum BlockType
    {
        Straight, T, Square, Bent
    }

    public struct Square
    {
        public int Row, Col;
    }

    public partial class MainWindow : Window
    {
        const int MaxRow = 20;
        const int MaxCol = 11;
        double size = 0;
        static bool isStarted = false;
        int top = 0, down = 0;
        Random rand = new Random();
        DispatcherTimer timer = new DispatcherTimer();
        Rectangle[,] rects = new Rectangle[MaxRow, MaxCol];
        Square[] current = new Square[4];
        List<Square> backup = new List<Square>();
        BlockType blockType = BlockType.T;

        public MainWindow()
        {
            InitializeComponent();
            Init();

            timer.Tick += Timer_Tick;
            timer.Interval = TimeSpan.FromSeconds(0.5);
            timer.Start();
        }

        bool isPressing = false;
        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);

            if (e.Key == Key.Escape) {
                for (int r = 0; r < MaxRow; r++) {
                    for (int c = 0; c < MaxCol; c++) {
                        rects[r, c].Visibility = Visibility.Hidden;
                    }
                }
                isStarted = false;
                isStarting = false;
            }

            if (!isStarted) return;

            isPressing = true;

            if (e.Key == Key.Left) {
                for (int i = 0; i < 4; i++) {
                    var c = current[i];
                    if (HasSquare(c.Row, c.Col - 1) || !InRange(c.Row, c.Col - 1)) {
                        isPressing = false;
                        return;
                    }
                }
                backup.AddRange(current);
                for (int i = 0; i < 4; i++) {
                    current[i].Col--;
                }
            } else if (e.Key == Key.Right) {
                for (int i = 0; i < 4; i++) {
                    var c = current[i];
                    if (HasSquare(c.Row, c.Col + 1) || !InRange(c.Row, c.Col + 1)) {
                        isPressing = false;
                        return;
                    }
                }
                backup.AddRange(current);
                for (int i = 0; i < 4; i++) {
                    current[i].Col++;
                }
            } else if (e.Key == Key.Up) {
                Rotate();
            } else if (e.Key == Key.Down) {
                for (int i = 0; i < 5; i++) {
                    Down();
                    ReDraw();
                }
            }

            isPressing = false;
        }

        bool HasSquare(int row, int col)
        {
            return InRange(row, col) && !current.Any(s => s.Row == row && s.Col == col)
                && rects[row, col].Visibility == Visibility.Visible;
        }

        int rotateCount = 0;
        Square[] rotateBack = null;
        private void Rotate()
        {
            rotateBack = (Square[])current.Clone();

            switch (blockType) {
                case BlockType.Straight:
                    if (rotateCount % 4 == 0 || rotateCount % 4 == 2) {
                        for (int i = 0; i < 4; i++) {
                            rotateBack[i].Row = top;
                            rotateBack[i].Col += i;
                        }
                    } else if (rotateCount % 4 == 1 || rotateCount % 4 == 3) {
                        for (int i = 0; i < 4; i++) {
                            rotateBack[i].Row += i;
                            rotateBack[i].Col = rotateBack[0].Col;
                        }
                    }
                    break;
                case BlockType.T:
                    if (rotateCount % 4 == 0) {
                        rotateBack[0].Row--;
                        rotateBack[0].Col++;
                        rotateBack[1].Row++;
                        rotateBack[1].Col++;
                        rotateBack[3].Row--;
                        rotateBack[3].Col--;
                    } else if (rotateCount % 4 == 1) {
                        rotateBack[0].Row--;
                        rotateBack[0].Col--;
                        rotateBack[1].Row--;
                        rotateBack[1].Col++;
                        rotateBack[3].Row++;
                        rotateBack[3].Col--;
                    } else if (rotateCount % 4 == 2) {
                        rotateBack[0].Row++;
                        rotateBack[0].Col--;
                        rotateBack[1].Row--;
                        rotateBack[1].Col--;
                        rotateBack[3].Row++;
                        rotateBack[3].Col++;
                    } else if (rotateCount % 4 == 3) {
                        rotateBack[0].Row++;
                        rotateBack[0].Col++;
                        rotateBack[1].Row++;
                        rotateBack[1].Col--;
                        rotateBack[3].Row--;
                        rotateBack[3].Col++;
                    }
                    break;
                case BlockType.Square:
                    break;
                case BlockType.Bent:
                    if (rotateCount % 4 == 0 || rotateCount % 4 == 2) {
                        rotateBack[2].Col += 2;
                        rotateBack[1].Row -= 2;
                    } else if (rotateCount % 4 == 1 || rotateCount % 4 == 3) {
                        rotateBack[2].Col -= 2;
                        rotateBack[1].Row += 2;
                    }
                    break;
                default:
                    break;
            }

            for (int i = 0; i < 4; i++) {
                var r = rotateBack[i];
                if (HasSquare(r.Row, r.Col) || !InRange(r.Row, r.Col)) {
                    return;
                }
            }

            current = (Square[])rotateBack.Clone();
            backup.AddRange(current);
            rotateCount++;
            if (rotateCount == 4) rotateCount = 0;
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            if (isPressing) return;
            if (isStarting) return;

            if (isStarted == false)
                Start();

            Down();
            ReDraw();
        }

        private void Down()
        {
            if (isStarted == false) return;
            if (current.Any(s => s.Row + 1 == MaxRow)) return;

            foreach (var b in backup) {
                if (InRange(b.Row, b.Col))
                    rects[b.Row, b.Col].Visibility = Visibility.Hidden;
            }

            backup.Clear();
            top = down = current[0].Row;
            for (int i = 0; i < 4; i++) {
                int row = ++current[i].Row;
                int col = current[i].Col;
                if (InRange(row, col)) {
                    rects[row, col].Visibility = Visibility.Visible;
                }

                if (top > row) top = row;
                if (down < row) down = row;
            }

            backup.AddRange(current);
        }

        bool InRange(int row, int col)
        {
            return row >= 0 && row < MaxRow && col >= 0 && col < MaxCol;
        }

        bool isStarting = false;
        private void Start()
        {
            isStarting = true;

            if (isStarted) return;
            isStarted = true;

            for (int i = 0; i < 4; i++) {
                current[i].Row = current[i].Col = 0;
            }
            rotateCount = 0;

            blockType = (BlockType)rand.Next(4);
            switch (blockType) {
                case BlockType.Straight:
                    for (int i = 0; i < 4; i++) {
                        current[i].Col = (MaxCol - 1) / 2;
                        current[i].Row = -i;
                    }
                    break;
                case BlockType.T:
                    for (int i = 0; i < 4; i++) {
                        current[0].Row = 0;
                        current[0].Col = (MaxCol - 1) / 2;
                        if (i > 0) {
                            current[i].Row = -1;
                            current[i].Col = (MaxCol - 1) / 2 + (i - 2);
                        }
                    }
                    break;
                case BlockType.Square:
                    for (int i = 0; i < 4; i++) {
                        if (i <= 1) {
                            current[i].Row = 0;
                            current[i].Col = (MaxCol - 1) / 2 + i;
                        } else {
                            current[i].Row = -1;
                            current[i].Col = (MaxCol - 1) / 2 + (i - 2);
                        }
                    }
                    break;
                case BlockType.Bent:
                    for (int i = 0; i < 4; i++) {
                        if (i <= 1) {
                            current[i].Row = 0;
                            current[i].Col = (MaxCol - 1) / 2 + i;
                        } else {
                            current[i].Row = -1;
                            current[i].Col = (MaxCol - 1) / 2 + (i - 3);
                        }
                    }
                    break;
            }

            isStarting = false;
        }

        private void Init()
        {
            size = (Height - 50) / MaxRow;
            canvas.Width = size * MaxCol;
            canvas.Height = size * MaxRow;

            for (int r = 0; r < MaxRow; r++) {
                for (int c = 0; c < MaxCol; c++) {
                    rects[r, c] = new Rectangle();
                    rects[r, c].Width = rects[r, c].Height = size;
                    rects[r, c].Fill = Brushes.Gray;
                    rects[r, c].Stroke = Brushes.LightGray;
                    rects[r, c].Visibility = Visibility.Hidden;
                    canvas.Children.Add(rects[r, c]);
                    Canvas.SetLeft(rects[r, c], c * size);
                    Canvas.SetTop(rects[r, c], r * size);
                }
            }

            for (int i = 0; i < 4; i++) {
                current[i].Col = current[i].Row = 0;
            }
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);

            size = (ActualHeight - 50) / MaxRow;
            canvas.Width = size * MaxCol;
            canvas.Height = size * MaxRow;
            ReDraw();
        }

        private void ReDraw()
        {
            if (isStarted == false) return;

            for (int r = 0; r < MaxRow; r++) {
                for (int c = 0; c < MaxCol; c++) {
                    rects[r, c].Width = rects[r, c].Height = size;
                    Canvas.SetLeft(rects[r, c], c * size);
                    Canvas.SetTop(rects[r, c], r * size);

                    bool hasSquare = current.Any(s => s.Col == c && s.Row + 1 == r
                        && rects[r, c].Visibility == Visibility.Visible)
                        && !current.Any(s => s.Row == r && s.Col == c);
                    if (down == MaxRow - 1 || hasSquare) {
                        top = down = 0;
                        isStarted = false;
                        backup.Clear();
                        ClearLines();
                        return;
                    }
                }
            }
        }

        List<int> cols = new List<int>();
        List<int> rows = new List<int>();
        void ClearLines()
        {
            cols.Clear();
            rows.Clear();

            bool isClear;
            for (int r = 0; r < MaxRow; r++) {
                for (int c = 0; c < MaxCol; c++) {
                    cols.Add(c);
                    if (c == MaxCol - 1) {
                        isClear = true;
                        foreach (var col in cols) {
                            if (rects[r, col].Visibility != Visibility.Visible) {
                                isClear = false;
                                break;
                            }
                        }
                        cols.Clear();
                        if (isClear) rows.Add(r);
                    }
                }
            }

            foreach (var r in rows) {
                for (int c = 0; c < MaxCol; c++) {
                    rects[r, c].Visibility = Visibility.Hidden;
                }
            }

            foreach (var r in rows) {
                for (int i = r - 1; i >= 0; i--) {
                    for (int j = 0; j < MaxCol; j++) {
                        rects[i + 1, j].Visibility = rects[i, j].Visibility;
                    }
                }
            }
        }
    }
}
View Code

運行效果圖如下:

            

源代碼:https://github.com/chinax01/x01.Tetris


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 已ubuntu為例在linux上安裝drupal
  • 這幾天突發奇想,想學習一下Python。看了點基礎,覺得有點枯燥,所以想搞點什麼。想了想,就隨便弄個檢測Linux用戶登錄的小工具吧~ 首先,明確一下功能: 1、能夠捕獲 linux 用戶登錄的信息。(這個很容易,方法比較多) 2、能夠將捕捉的信息記錄下來。(不然要這信息幹嘛……) 3、最好能夠一發
  • 最近好久沒有更新文章了,因為好久沒有寫代碼了,以至於我不知道同大家分享些什麼,剛好,今天突然叫我學習下jenkins每日構建,我就把今天的學習筆記記錄下來,這其中很多東西都是公司同事之前調研總結的,我在他的基礎上進行了更加詳細的整理,並自己一步一步的對著實現了一下。 環境準備 下載jenkins的w
  • 由於在官方下載的ueditor包是在vs2012下開發的,可以在vs2010中使用,但在vs2008中就會報錯。折騰了一翻,現將解決方法分享給需要的朋友,其實就是把裡面包含.net4.0的元素換成.net3.5的 1、下載.net framework 3.5版的Newtonsoft.Json.dll
  • 原來用的是Kindeditor這個編輯器,但很久沒更新了,最新版是13年更新的。現在要換成百度的Ueditor, 在這裡記錄Ueditor的使用流程和遇到的問題。 一、下載 1.Ueditor官網 這裡有三個版本:1.UBuilder:可以自定義選擇自已需要的功能,然後會下載對應的文件。 2.開發版
  • 那天在調試API的時候,發現用c#寫的SHA1加密出來的結果和PHP中sha1()出來的不一樣,找了半天的原因後來才弄出來 在調試微信介面的時候大多的幫助文檔都是提供的是PHP的方法,所以在.net中實現的時候會出現很多的問題,最典型的就是token通不過驗證 現在提供一個結果與Php一樣 的SHA
  • 本次將考察三類工具,它們是每一位 MVC 程式員工具庫的成員:DI容器、單元測試框架和模仿工具。 1.創建一個示例項目 創建一個空 ASP.NET MVC 4 項目 EssentiaTools 。 1.1 創建模型類 在 Models 文件夾下新建 Product.cs 類文件 using Syst
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...