Change Splitter Highlighting/Resize Line - c#

I noticed when I resize an element in Visual Studio the Splitter Line is painted in a solid transparent black like this:
However in my own Winforms application I get this resize line:
I am wondering how I can change the painting of this resize line?

If you take a look at Splitter source code, you will see drawing of the highlight is performed in the DrawSplitHelper private method.
Since splitter methods are tightly deppending on private members of the control, overriding members or handling events of the control which use this method doesn't provides such transparent highlight simply. Also if you decide to darw a solid highlight, you can not have a filcker-free drawing because of the halftone highlight which the control draws in private methods.
The idea of showing a transparent highlight is based on showing a top-most semi-transparent window which doesn't activate on showing. Also you can use PatBlt method to draw a reversible rectangle using a brush.
As an option I started by Splitter.cs and changed it to draw desired transparent highlight as you see in image below:
Code
As an option I started by Splitter.cs and changed it to draw desired transparent highlight. I used a Form to show transparent highlight. I showed the form without activating, as top-most and with a suitable opacity.
Probably you can create a splitter using less code, but I preferred to use source code of Splitter instead of writing my own splitter. Thanks to Microsoft for sharing source code.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Drawing.Drawing2D;
using System.Reflection;
[ComVisible(true)]
[DefaultEvent("SplitterMoved")]
[DefaultProperty("Dock")]
[Designer(typeof(MySplitterDesigner))]
public class MySplitter : Control
{
private Point anchor = Point.Empty;
private System.Windows.Forms.BorderStyle borderStyle;
private const int defaultWidth = 3;
private const int DRAW_END = 3;
private const int DRAW_MOVE = 2;
private const int DRAW_START = 1;
private static readonly object EVENT_MOVED = new object();
private static readonly object EVENT_MOVING = new object();
private int initTargetSize;
private int lastDrawSplit = -1;
private int maxSize;
private int minExtra = 25;
private int minSize = 25;
private int splitSize = -1;
private Control splitTarget;
private SplitterMessageFilter splitterMessageFilter;
private int splitterThickness = 3;
[Category("Behavior")]
[Description("Occurs when the splitter is done being moved.")]
public event SplitterEventHandler SplitterMoved
{
add
{
base.Events.AddHandler(EVENT_MOVED, value);
}
remove
{
base.Events.RemoveHandler(EVENT_MOVED, value);
}
}
[Category("Behavior")]
[Description("Occurs when the splitter is being moved.")]
public event SplitterEventHandler SplitterMoving
{
add
{
base.Events.AddHandler(EVENT_MOVING, value);
}
remove
{
base.Events.RemoveHandler(EVENT_MOVING, value);
}
}
HighLight highlight;
public MySplitter()
{
base.SetStyle(ControlStyles.Selectable, false);
this.TabStop = false;
this.minSize = 0x19;
this.minExtra = 0x19;
this.Dock = DockStyle.Left;
highlight = new HighLight();
}
private void ApplySplitPosition()
{
this.SplitPosition = this.splitSize;
}
private SplitData CalcSplitBounds()
{
SplitData data = new SplitData();
Control control = this.FindTarget();
data.target = control;
if (control != null)
{
switch (control.Dock)
{
case DockStyle.Top:
case DockStyle.Bottom:
this.initTargetSize = control.Bounds.Height;
break;
case DockStyle.Left:
case DockStyle.Right:
this.initTargetSize = control.Bounds.Width;
break;
}
Control parentInternal = this.Parent;
Control.ControlCollection controls = parentInternal.Controls;
int count = controls.Count;
int num2 = 0;
int num3 = 0;
for (int i = 0; i < count; i++)
{
Control control3 = controls[i];
if (control3 != control)
{
switch (control3.Dock)
{
case DockStyle.Top:
case DockStyle.Bottom:
num3 += control3.Height;
break;
case DockStyle.Left:
case DockStyle.Right:
num2 += control3.Width;
break;
}
}
}
Size clientSize = parentInternal.ClientSize;
if (this.Horizontal)
{
this.maxSize = (clientSize.Width - num2) - this.minExtra;
}
else
{
this.maxSize = (clientSize.Height - num3) - this.minExtra;
}
data.dockWidth = num2;
data.dockHeight = num3;
}
return data;
}
private Rectangle CalcSplitLine(int splitSize, int minWeight)
{
Rectangle bounds = base.Bounds;
Rectangle rectangle2 = this.splitTarget.Bounds;
switch (this.Dock)
{
case DockStyle.Top:
if (bounds.Height < minWeight)
{
bounds.Height = minWeight;
}
bounds.Y = rectangle2.Y + splitSize;
return bounds;
case DockStyle.Bottom:
if (bounds.Height < minWeight)
{
bounds.Height = minWeight;
}
bounds.Y = ((rectangle2.Y + rectangle2.Height) - splitSize) - bounds.Height;
return bounds;
case DockStyle.Left:
if (bounds.Width < minWeight)
{
bounds.Width = minWeight;
}
bounds.X = rectangle2.X + splitSize;
return bounds;
case DockStyle.Right:
if (bounds.Width < minWeight)
{
bounds.Width = minWeight;
}
bounds.X = ((rectangle2.X + rectangle2.Width) - splitSize) - bounds.Width;
return bounds;
}
return bounds;
}
private int CalcSplitSize()
{
Control control = this.FindTarget();
if (control != null)
{
Rectangle bounds = control.Bounds;
switch (this.Dock)
{
case DockStyle.Top:
case DockStyle.Bottom:
return bounds.Height;
case DockStyle.Left:
case DockStyle.Right:
return bounds.Width;
}
}
return -1;
}
private void DrawSplitBar(int mode)
{
if ((mode != 1) && (this.lastDrawSplit != -1))
{
this.DrawSplitHelper(this.lastDrawSplit);
this.lastDrawSplit = -1;
}
else if ((mode != 1) && (this.lastDrawSplit == -1))
{
return;
}
if (mode != 3)
{
this.DrawSplitHelper(this.splitSize);
this.lastDrawSplit = this.splitSize;
}
else
{
if (this.lastDrawSplit != -1)
{
this.DrawSplitHelper(this.lastDrawSplit);
}
this.lastDrawSplit = -1;
highlight.Hide();
}
Console.WriteLine(mode);
}
private void DrawSplitHelper(int splitSize)
{
if (this.splitTarget != null)
{
Rectangle rectangle = this.CalcSplitLine(splitSize, 3);
var r = this.Parent.RectangleToScreen(rectangle);
if (!highlight.Visible)
highlight.ShowInactiveTopmost();
highlight.Location = r.Location;
highlight.Size = r.Size;
}
}
private Control FindTarget()
{
Control parentInternal = this.Parent;
if (parentInternal != null)
{
Control.ControlCollection controls = parentInternal.Controls;
int count = controls.Count;
DockStyle dock = this.Dock;
for (int i = 0; i < count; i++)
{
Control control2 = controls[i];
if (control2 != this)
{
switch (dock)
{
case DockStyle.Top:
if (control2.Bottom != base.Top)
{
break;
}
return control2;
case DockStyle.Bottom:
if (control2.Top != base.Bottom)
{
break;
}
return control2;
case DockStyle.Left:
if (control2.Right != base.Left)
{
break;
}
return control2;
case DockStyle.Right:
if (control2.Left != base.Right)
{
break;
}
return control2;
}
}
}
}
return null;
}
private int GetSplitSize(int x, int y)
{
int num;
if (this.Horizontal)
num = x - this.anchor.X;
else
num = y - this.anchor.Y;
int num2 = 0;
switch (this.Dock)
{
case DockStyle.Top:
num2 = this.splitTarget.Height + num;
break;
case DockStyle.Bottom:
num2 = this.splitTarget.Height - num;
break;
case DockStyle.Left:
num2 = this.splitTarget.Width + num;
break;
case DockStyle.Right:
num2 = this.splitTarget.Width - num;
break;
}
return Math.Max(Math.Min(num2, this.maxSize), this.minSize);
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if ((this.splitTarget != null) && (e.KeyCode == Keys.Escape))
this.SplitEnd(false);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if ((e.Button == MouseButtons.Left) && (e.Clicks == 1))
this.SplitBegin(e.X, e.Y);
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (this.splitTarget != null)
{
int x = e.X + base.Left;
int y = e.Y + base.Top;
Rectangle rectangle = this.CalcSplitLine(this.GetSplitSize(e.X, e.Y), 0);
int splitX = rectangle.X;
int splitY = rectangle.Y;
this.OnSplitterMoving(new SplitterEventArgs(x, y, splitX, splitY));
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (this.splitTarget != null)
{
Rectangle rectangle = this.CalcSplitLine(this.GetSplitSize(e.X, e.Y), 0);
this.SplitEnd(true);
}
}
protected virtual void OnSplitterMoved(SplitterEventArgs sevent)
{
SplitterEventHandler handler = (SplitterEventHandler)base.Events[EVENT_MOVED];
if (handler != null)
handler(this, sevent);
if (this.splitTarget != null)
this.SplitMove(sevent.SplitX, sevent.SplitY);
}
protected virtual void OnSplitterMoving(SplitterEventArgs sevent)
{
SplitterEventHandler handler = (SplitterEventHandler)base.Events[EVENT_MOVING];
if (handler != null)
handler(this, sevent);
if (this.splitTarget != null)
this.SplitMove(sevent.SplitX, sevent.SplitY);
}
protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified)
{
if (this.Horizontal)
{
if (width < 1)
width = 3;
this.splitterThickness = width;
}
else
{
if (height < 1)
height = 3;
this.splitterThickness = height;
}
base.SetBoundsCore(x, y, width, height, specified);
}
private void SplitBegin(int x, int y)
{
SplitData data = this.CalcSplitBounds();
if ((data.target != null) && (this.minSize < this.maxSize))
{
this.anchor = new Point(x, y);
this.splitTarget = data.target;
this.splitSize = this.GetSplitSize(x, y);
try
{
if (this.splitterMessageFilter != null)
this.splitterMessageFilter = new SplitterMessageFilter(this);
Application.AddMessageFilter(this.splitterMessageFilter);
}
finally { }
this.Capture = true;
this.DrawSplitBar(1);
}
}
private void SplitEnd(bool accept)
{
this.DrawSplitBar(3);
this.splitTarget = null;
this.Capture = false;
if (this.splitterMessageFilter != null)
{
Application.RemoveMessageFilter(this.splitterMessageFilter);
this.splitterMessageFilter = null;
}
if (accept)
this.ApplySplitPosition();
else if (this.splitSize != this.initTargetSize)
this.SplitPosition = this.initTargetSize;
this.anchor = Point.Empty;
}
private void SplitMove(int x, int y)
{
int splitSize = this.GetSplitSize((x - base.Left) + this.anchor.X, (y - base.Top) + this.anchor.Y);
if (this.splitSize != splitSize)
{
this.splitSize = splitSize;
this.DrawSplitBar(2);
}
}
public override string ToString()
{
string str = base.ToString();
string[] textArray1 = new string[] { str, ", MinExtra: ", this.MinExtra.ToString(CultureInfo.CurrentCulture), ", MinSize: ", this.MinSize.ToString(CultureInfo.CurrentCulture) };
return string.Concat(textArray1);
}
[DefaultValue(0)]
[Category("Appearance")]
[Description("The border type of the control.")]
public System.Windows.Forms.BorderStyle BorderStyle
{
get
{
return this.borderStyle;
}
set
{
if (!IsEnumValid(value, (int)value, 0, 2))
throw new InvalidEnumArgumentException("value", (int)value, typeof(System.Windows.Forms.BorderStyle));
if (this.borderStyle != value)
{
this.borderStyle = value;
base.UpdateStyles();
}
}
}
protected override System.Windows.Forms.CreateParams CreateParams
{
get
{
System.Windows.Forms.CreateParams createParams = base.CreateParams;
createParams.ExStyle &= -513;
createParams.Style &= -8388609;
System.Windows.Forms.BorderStyle borderStyle = this.borderStyle;
if (borderStyle != System.Windows.Forms.BorderStyle.FixedSingle)
{
if (borderStyle == System.Windows.Forms.BorderStyle.Fixed3D)
{
createParams.ExStyle |= 0x200;
}
return createParams;
}
createParams.Style |= 0x800000;
return createParams;
}
}
protected override Cursor DefaultCursor
{
get
{
switch (this.Dock)
{
case DockStyle.Top:
case DockStyle.Bottom:
return Cursors.HSplit;
case DockStyle.Left:
case DockStyle.Right:
return Cursors.VSplit;
}
return base.DefaultCursor;
}
}
protected override System.Windows.Forms.ImeMode DefaultImeMode
{
get
{
return System.Windows.Forms.ImeMode.Disable;
}
}
protected override Size DefaultSize
{
get { return new Size(3, 3); }
}
[Localizable(true), DefaultValue(3)]
public override DockStyle Dock
{
get { return base.Dock; }
set
{
if (((value != DockStyle.Top) && (value != DockStyle.Bottom)) && ((value != DockStyle.Left) && (value != DockStyle.Right)))
throw new ArgumentException("Splitter control must be docked left, right, top, or bottom.");
int splitterThickness = this.splitterThickness;
base.Dock = value;
switch (this.Dock)
{
case DockStyle.Top:
case DockStyle.Bottom:
if (this.splitterThickness == -1)
break;
base.Height = splitterThickness;
return;
case DockStyle.Left:
case DockStyle.Right:
if (this.splitterThickness != -1)
base.Width = splitterThickness;
break;
default:
return;
}
}
}
private bool Horizontal
{
get
{
DockStyle dock = this.Dock;
if (dock != DockStyle.Left)
return (dock == DockStyle.Right);
return true;
}
}
[Category("Behavior")]
[Localizable(true)]
[DefaultValue(25)]
[Description("Specifies the minimum size of the undocked area.")]
public int MinExtra
{
get { return this.minExtra; }
set
{
if (value < 0)
value = 0;
this.minExtra = value;
}
}
[Category("Behavior")]
[Localizable(true)]
[DefaultValue(25)]
[Description("Specifies the minimum size of the control being resized.")]
public int MinSize
{
get { return this.minSize; }
set
{
if (value < 0)
value = 0;
this.minSize = value;
}
}
[Category("Layout")]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("The current position of the splitter, or -1 if it is not bound to a control.")]
public int SplitPosition
{
get
{
if (this.splitSize == -1)
{
this.splitSize = this.CalcSplitSize();
}
return this.splitSize;
}
set
{
SplitData data = this.CalcSplitBounds();
if (value > this.maxSize)
{
value = this.maxSize;
}
if (value < this.minSize)
{
value = this.minSize;
}
this.splitSize = value;
this.DrawSplitBar(3);
if (data.target == null)
{
this.splitSize = -1;
}
else
{
Rectangle bounds = data.target.Bounds;
switch (this.Dock)
{
case DockStyle.Top:
bounds.Height = value;
break;
case DockStyle.Bottom:
bounds.Y += bounds.Height - this.splitSize;
bounds.Height = value;
break;
case DockStyle.Left:
bounds.Width = value;
break;
case DockStyle.Right:
bounds.X += bounds.Width - this.splitSize;
bounds.Width = value;
break;
}
data.target.Bounds = bounds;
Application.DoEvents();
this.OnSplitterMoved(new SplitterEventArgs(base.Left, base.Top, base.Left + (bounds.Width / 2), base.Top + (bounds.Height / 2)));
}
}
}
private class SplitData
{
public int dockHeight = -1;
public int dockWidth = -1;
internal Control target;
}
private class SplitterMessageFilter : IMessageFilter
{
private MySplitter owner;
public SplitterMessageFilter(MySplitter splitter)
{
this.owner = splitter;
}
public bool PreFilterMessage(ref Message m)
{
if ((m.Msg < 0x100) || (m.Msg > 0x108))
{
return false;
}
if ((m.Msg == 0x100) && (((int)((long)m.WParam)) == 0x1b))
{
this.owner.SplitEnd(false);
}
return true;
}
}
private static bool IsEnumValid(Enum enumValue, int value, int minValue, int maxValue)
{
return ((value >= minValue) && (value <= maxValue));
}
}
public class MySplitterDesigner : ControlDesigner
{
public MySplitterDesigner() { base.AutoResizeHandles = true; }
private void DrawBorder(Graphics graphics)
{
Color white;
Control control = this.Control;
Rectangle clientRectangle = control.ClientRectangle;
if (control.BackColor.GetBrightness() < 0.5)
white = Color.White;
else
white = Color.Black;
using (Pen pen = new Pen(white))
{
pen.DashStyle = DashStyle.Dash;
clientRectangle.Width--;
clientRectangle.Height--;
graphics.DrawRectangle(pen, clientRectangle);
}
}
protected override void OnPaintAdornments(PaintEventArgs pe)
{
base.OnPaintAdornments(pe);
if (((MySplitter)base.Component).BorderStyle == BorderStyle.None)
this.DrawBorder(pe.Graphics);
}
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x47)
this.Control.Invalidate();
base.WndProc(ref m);
}
}
Here is highlight form:
public class HighLight : Form
{
public HighLight()
{
FormBorderStyle = FormBorderStyle.None;
BackColor = Color.Black;
Opacity = 0;
ShowInTaskbar = false;
StartPosition = FormStartPosition.Manual;
}
protected override void OnDeactivate(EventArgs e)
{
base.OnDeactivate(e);
this.Hide();
}
private const int SW_SHOWNOACTIVATE = 4;
private const int HWND_TOPMOST = -1;
private const uint SWP_NOACTIVATE = 0x0010;
[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
static extern bool SetWindowPos(int hWnd, int hWndInsertAfter,
int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
public void ShowInactiveTopmost()
{
ShowWindow(this.Handle, SW_SHOWNOACTIVATE);
SetWindowPos(this.Handle.ToInt32(), HWND_TOPMOST,
this.Left, this.Top, this.Width, this.Height,
SWP_NOACTIVATE);
this.Opacity = 0.3;
}
}

Related

How to get random int values to a prefab which is called multiple times(without repeating same value)?

I have created a prefab which contains text (a*b=) and input field (to get user's answer). and I am calling this prefab 5 times using c# script. I have assigned a & b to random.range(1,10) so i can get 5 different sums. but in my case i am getting same values to all 5 sums.
I tried foreach loop and it is getting random numbers out of given range and on clicking check button it shows even correct answers in red(as incorrect).
This is the first time i am dealing with calling prefab multiple times via script. so need some help to solve it please.
TestModeQuestionUI.cs
using Helper.Keyboard;
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class TestModeQuestionUI : MonoBehaviour
{
internal RectTransform refRectTransform;
[SerializeField]
TextMeshProUGUI valueA; // valueB;
[SerializeField]
MyInputField AnswerInputField;
internal int id;
internal Action<TestModeQuestionUI> onSubmitValueOfInputFieldAction;
internal Action<TestModeQuestionUI> onSelectInputFieldAction;
Color defaultColorOfAnswer = new Color(0.19f, 0.19f, 0.19f, 1f);
Color correctColorOfAnswer = new Color(0f, 0.44f, 0f, 1f);
Color incorrectColorOfAnswer = new Color(1f, 0f, 0f, 1f);
public static TestModeQuestionUI curSelectedAnswerInputField;
//-------------------------------------------------------------------------
void Awake()
{
refRectTransform = GetComponent<RectTransform>();
}
private void SetNextAnswerInputFieldAsSelected(TestModeQuestionUI
curSelectedAnswerInputField)
{
throw new NotImplementedException();
}
public void SetQuestionLabel(string v)
{
valueA.text = v;
}
public void ActiveAnswerInputField(bool active)
{
AnswerInputField.gameObject.SetActive(active);
}
public int GetAnswerInputField()
{
int result = -1;
int.TryParse(AnswerInputField.textComponent.text, out result);
return result;
}
public void SetAnswerInputField(string msg)
{
AnswerInputField.textComponent.text = msg;
}
public void SelectAnswerInputField()
{
DeSelectCurSelectedAnswerInputField();
AnswerInputField.ActivateInputField();
curSelectedAnswerInputField = this;
}
public static void DeSelectCurSelectedAnswerInputField()
{
if (curSelectedAnswerInputField != null)
{
curSelectedAnswerInputField.AnswerInputField.DeactivateInputField();
}
curSelectedAnswerInputField = null;
}
public void SetResultOfAnswerInputField(int result)
{
switch (result)
{
//==================================
// Default Color For Answer Has Not Checked
case 0:
AnswerInputField.textComponent.color = defaultColorOfAnswer;
break;
//==================================
// Correct Color For Answer Has Checked Correct
case 1:
AnswerInputField.textComponent.color = correctColorOfAnswer;
break;
//==================================
// Incorrect Color For Answer Has Checked Incorrect
case 2:
AnswerInputField.textComponent.color = incorrectColorOfAnswer;
break;
}
}
public void OnSelectInputField()
{
//Debug.Log("On Select : " + id);
if (curSelectedAnswerInputField != this)
DeSelectCurSelectedAnswerInputField();
curSelectedAnswerInputField = this;
if (onSelectInputFieldAction != null)
onSelectInputFieldAction(this);
}
public void OnSubmitValueOfInputField()
{
if (onSubmitValueOfInputFieldAction != null)
onSubmitValueOfInputFieldAction(this);
}
}
TestModeManager.cs
public class TestModeManager : MonoBehaviour
{
public static TestModeManager instance;
[SerializeField]
GameObject refTestModeQuestionExampleParent;
[SerializeField]
GameObject refTestModeQuestionExamplePrefab;
[SerializeField]
GameObject checkButton;
[SerializeField]
GameObject nextButton;
private int a, b;
List<TestModeQuestionUI> testModeQuestionExampleList;
void Start()
{
CreateUI();
}
void Update()
{
#if UNITY_EDITOR
if (Input.GetKeyDown(KeyCode.KeypadEnter))
{ SetNextAnswerInputFieldAsSelected(TestModeQuestionUI.curSelectedAnswerInputField);
}
#endif
if (Input.GetKeyDown(KeyCode.Escape))
{
if (Keyboard.instance.gameObject.activeInHierarchy)
Keyboard.Close();
else
Application.Quit();
}
}
void CreateUI()
{
GameObject _GO;
TestModeQuestionUI _TestModeQuestionUIRefrence;
if (testModeQuestionExampleList == null)
testModeQuestionExampleList = new List<TestModeQuestionUI>();
// a = UnityEngine.Random.Range(1, 20);
// b = UnityEngine.Random.Range(1, 10);
for (int id = 1; id <= 5; id++)
{
_GO = Instantiate(refTestModeQuestionExamplePrefab,
refTestModeQuestionExampleParent.transform);
_GO.name = "TestModeQuestion Example " + id;
_TestModeQuestionUIRefrence = _GO.GetComponent<TestModeQuestionUI>
();
_TestModeQuestionUIRefrence.id = id;
_TestModeQuestionUIRefrence.onSubmitValueOfInputFieldAction =
SetNextAnswerInputFieldAsSelected;
testModeQuestionExampleList.Add(_TestModeQuestionUIRefrence);
}
ResetUI();
}
void ResetUI()
{
// Reset Multiplication Examples
a = UnityEngine.Random.Range(1, 10);
b = UnityEngine.Random.Range(1, 10);
foreach (TestModeQuestionUI _TestModeQuestionUIRefrence in
testModeQuestionExampleList)
{
_TestModeQuestionUIRefrence.SetQuestionLabel(a + " " + b + " = ");
//loop to get 5 different sums
var questions = GameObject.FindGameObjectsWithTag("question");
foreach (var question in questions)
{
// a++;
//b++;
}
}
//==================================
// Set First Answer Input Field As Selected
SetNextAnswerInputFieldAsSelected();
}
void SetNextAnswerInputFieldAsSelected(TestModeQuestionUI _
TestModeQuestionUIRefrence = null)
{
if (_TestModeQuestionUIRefrence == null)
{
//==================================
// Get First Input Field And Set As Selected
_TestModeQuestionUIRefrence = GettestModeQuestionExampleList(1);
if (_TestModeQuestionUIRefrence != null)
_TestModeQuestionUIRefrence.SelectAnswerInputField();
}
else
{
//==================================
// Get Next Input Field And Set As Selected
_TestModeQuestionUIRefrence =
GettestModeQuestionExampleList(_TestModeQuestionUIRefrence.id + 1);
if (_TestModeQuestionUIRefrence != null)
_TestModeQuestionUIRefrence.SelectAnswerInputField();
else
{
Keyboard.Close();
StartCoroutine(highlighCheckButton());
}
}
}
TestModeQuestionUI GettestModeQuestionExampleList(int id)
{
foreach (TestModeQuestionUI _TestModeQuestionUIRefrence in
testModeQuestionExampleList)
{
if (_TestModeQuestionUIRefrence.id == id)
{
return _TestModeQuestionUIRefrence;
}
}
return null;
}
IEnumerator EnableKeyboardAfterSometime(float time)
{
yield return new WaitForSeconds(time);
Keyboard.Open();
}
IEnumerator highlighCheckButton()
{
checkButton.transform.localScale = new Vector3(1f, 1f, 1f);
float animtionTime = 0.3f;
float scaleUpTo = 1.2f;
for (int i = 0; i < 4; i++)
{
yield return AnimationController.animate(scaleCheckButton,
animtionTime, 1f, scaleUpTo);
yield return AnimationController.animate(scaleCheckButton,
animtionTime, scaleUpTo, 1f);
}
checkButton.transform.localScale = new Vector3(1f, 1f, 1f);
}
void scaleCheckButton(float value)
{
checkButton.transform.localScale = new Vector3(value, value, value);
}
public void CheckButton()
{
int answer;
foreach (TestModeQuestionUI _TestModeQuestionUIRefrence in
testModeQuestionExampleList)
{
answer = _TestModeQuestionUIRefrence.GetAnswerInputField();
if ((a * b) == answer)
{
_TestModeQuestionUIRefrence.SetResultOfAnswerInputField(1);
}
else
{
_TestModeQuestionUIRefrence.SetResultOfAnswerInputField(2);
}
}
checkButton.SetActive(false);
nextButton.SetActive(true);
}
public void NextButton()
{
ResetUI();
nextButton.SetActive(false);
}
You should get the random value inside the loop, otherwise you get the same values.
foreach (TestModeQuestionUI _TestModeQuestionUIRefrence in testModeQuestionExampleList)
{
int a = UnityEngine.Random.Range(1, 10);
int b = UnityEngine.Random.Range(1, 10);
_TestModeQuestionUIRefrence.SetQuestionLabel(a, b);
}
You also should save a and b in TestModeQuestionUI because they are different betweent instances.
public class TestModeQuestionUI : MonoBehaviour
{
private int a, b;
public void SetQuestionLabel(int a, int b)
{
this.a = a;
this.b = b;
valueA.text = a + " " + b + " = ";
}
}
You have a lot of UI stuff but if i were you and if i do not want to get duplicates i would create a separate script for getting random values like this:
public class RandomIntegers {
private static List<int> myNumbersA = new List<int>();
private static List<int> myNumbersB = new List<int>();
public static void RandomValues(out int a,out int b)
{
if (myNumbersA.Count == 0)
{
for (int i = 0; i < 10; i++)
{
myNumbersA.Add(i + 1);
myNumbersB.Add(i + 1);
}
}
int indexA = Random.Range(0, myNumbersA.Count);
int indexB = Random.Range(0, myNumbersB.Count);
a = myNumbersA[indexA];
b = myNumbersB[indexB];
myNumbersA.RemoveAt(indexA);
myNumbersB.RemoveAt(indexB);
}
}
Then in your ResetUI function you can call this function using
RandomIntegers.RandomValues(out a,out b); The reason why i implemented it this way is instances of your prefab can access it when they are instantiated and since it is static you will not get same random results for a and b. But lets say you might get 6 for a and 8 for b but also 8 for a and 6 for b both will result as 48 at the end.

C# drag mouse down

I'm trying to make a program where when I click left click it drags the mouse down without me moving my mouse down for a game but it does not move the game at all. It moves my cursor outside of the game but does not move inside the game.
public static Point Position { get; set; }
public Anti_Recoil()
{
InitializeComponent();
}
private void Anti_Recoil_Load(object sender, EventArgs e)
{
this.BackColor = Color.Wheat;
this.TransparencyKey = Color.Wheat;
this.TopMost = true;
int initialStyle = GetWindowLong(this.Handle, -20);
SetWindowLong(this.Handle, -20, initialStyle | 0x80000 | 0x20);
PointConverter pc = new PointConverter();
Point pt = new Point();
pt = (Point)pc.ConvertFromString("765, 500");
Cursor.Position = pt;
}
private void Anti_Recoil_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Z)
Hide();
}
Use my class
First, add my class to your project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Windows.Input;
namespace Hector.Framework.Utils
{
public class Peripherals
{
public class Mouse
{
public static int X
{
get => Cursor.Position.X;
}
public static int Y
{
get => Cursor.Position.Y;
}
public static void MoveToPoint(int X, int Y)
{
Win32.SetCursorPos(X, Y);
}
public static void Hide()
{
Cursor.Hide();
}
public static void Show()
{
Cursor.Show();
}
public static bool IsHidden
{
get => Cursor.Current == null;
}
/// <summary>
/// ButtonNumber: 0-None 1-Left 2-Middle 3-Right 4-XButton1 5-XButton2
/// </summary>
public static bool MouseButtonIsDown(int ButtonNumber)
{
bool outValue = false;
bool isLeft = Control.MouseButtons == MouseButtons.Left;
bool isRight = Control.MouseButtons == MouseButtons.Right;
bool isMiddle = Control.MouseButtons == MouseButtons.Middle;
bool isXButton1 = Control.MouseButtons == MouseButtons.XButton1;
bool isXButton2 = Control.MouseButtons == MouseButtons.XButton2;
switch (ButtonNumber)
{
case 0:
outValue = false;
break;
case 1:
outValue = isLeft;
break;
case 2:
outValue = isMiddle;
break;
case 3:
outValue = isRight;
break;
case 4:
outValue = isXButton1;
break;
case 5:
outValue = isXButton2;
break;
}
return outValue;
}
/// <summary>
/// This function is in Alpha Phase
/// </summary>
/// <param name="FocusedControl">The control that is scrolled; If the control has no focus, it will be applied automatically</param>
/// <param name="FontSize">This is used to calculate the number of pixels to move, its default value is 20</param>
static int delta = 0;
static int numberOfTextLinesToMove = 0;
static int numberOfPixelsToMove = 0;
public static bool GetWheelValues(Control FocusedControl, out int Delta, out int NumberOfTextLinesToMove, out int NumberOfPixelsToMove, int FontSize = 20)
{
try
{
if (FocusedControl == null) throw new NullReferenceException("The FocusedControl can not bel null");
if (!FocusedControl.Focused) FocusedControl.Focus();
FocusedControl.MouseWheel += (object sender, MouseEventArgs e) =>
{
delta = e.Delta;
numberOfTextLinesToMove = e.Delta * SystemInformation.MouseWheelScrollLines / 120;
numberOfPixelsToMove = numberOfTextLinesToMove * FontSize;
};
Delta = delta;
NumberOfTextLinesToMove = numberOfTextLinesToMove;
NumberOfPixelsToMove = numberOfPixelsToMove;
return true;
}
catch
{
Delta = 0;
NumberOfTextLinesToMove = 0;
NumberOfPixelsToMove = numberOfPixelsToMove;
return false;
}
}
private class Win32
{
[DllImport("User32.Dll")]
public static extern long SetCursorPos(int x, int y);
[DllImport("User32.Dll")]
public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int x;
public int y;
}
}
}
}
}
Then where you need to check the mouse's status,
bool MouseLeftButton = Hector.Framework.Utils.Peripherals.Mouse.MouseButtonIsDown(1);
And try this:
private void Form2_Load(object sender, EventArgs e)
{
Hector.Framework.Utils.Peripherals.Mouse.MoveToPoint(300, 0); //Move the cursor to Top
}
//Then use timer to move the cursor
int a = 0;
private void timer1_Tick(object sender, EventArgs e)
{
Hector.Framework.Utils.Peripherals.Mouse.MoveToPoint(300, a += 1);
}
if(MouseLeftButton)
{
timer1.Start(); //timer is initialized
}

C# unable to move character in ASCII Console game

I have a C# project for school. I am unable to move my character in this ASCII console game. It has to be OO. After I run the code I get this:
After I press left or right I get
Can someone help me on this? Any help is appreciated.
program.cs:
class Program
{
static void Main(string[] args)
{
SuperConsole.Init(50, 44);
// create the game
Game game = new Game(30, 30);
//create objects
Entity spaceship = new Entity(1, 15, '#', SuperConsoleColor.Cyan);
// start the game loop
RunGameLoop(game);
}
protected static void RunGameLoop(Game game)
{
SuperConsole.BackgroundColor = SuperConsoleColor.DarkBlue;
SuperConsole.ForegroundColor = SuperConsoleColor.Gray;
int refreshRate = 20;
SuperConsole.CursorVisible = false;
SuperConsole.BackgroundColor = SuperConsoleColor.DarkBlue;
SuperConsole.ForegroundColor = SuperConsoleColor.Gray;
SuperConsole.Clear();
Reset(game);
game.Draw(0.0f);
SuperConsole.Flush();
/*
SuperConsole.SetCursorPosition(0, 0);*/
while (true)
{
while (SuperConsole.KeyAvailable)
{
ConsoleKeyInfo key = SuperConsole.ReadKey(true);
game.OnInput(key.Key);
}
System.Threading.Thread.Sleep(1000 / refreshRate);
Reset(game);
game.Draw(1.0f / (float)refreshRate);
SuperConsole.Flush();
}
}
protected static void Reset(Game game)
{
SuperConsole.BackgroundColor = SuperConsoleColor.Black;
SuperConsole.ForegroundColor = SuperConsoleColor.Black;
SuperConsole.SetCursorPosition(0, 0);
for (int y = 0; y < game.GetHeight(); ++y)
{
for (int x = 0; x < game.GetWidth(); ++x)
{
SuperConsole.Write(" ");
}
SuperConsole.WriteLine();
}
SuperConsole.SetCursorPosition(0, 0);
}
}
}
game.cs:
class Game : Entity
{
protected int width, height;
Entity spaceship = new Entity(1, 15, '#', SuperConsoleColor.Cyan);
public Game(int newWidth, int newHeight)
{
// set the size
width = newWidth;
height = newHeight;
// set the window
Console.WindowWidth = width+1;
Console.WindowHeight = height+1;
}
public int GetWidth()
{
return width;
}
public int GetHeight()
{
return height;
}
public void Draw(float dt)
{
SuperConsole.SetCursorPosition(spaceship.GetX(), spaceship.GetY());
SuperConsole.ForegroundColor = spaceship.GetColour();
SuperConsole.Write(spaceship.GetChar());
}
public void OnInput(ConsoleKey key)
{
int redo = 0;
ConsoleKey pressedKey = key;
do
{
Console.Clear();
switch (pressedKey)
{
case ConsoleKey.LeftArrow:
SuperConsole.SetCursorPosition(spaceship.GetX() - 1, spaceship.GetY());
break;
case ConsoleKey.UpArrow:
break;
case ConsoleKey.RightArrow:
SuperConsole.SetCursorPosition(spaceship.GetX()+1, spaceship.GetY());
break;
case ConsoleKey.DownArrow:
break;
}
} while (redo == 0);
}
}
}
entity.cs:
class Entity
{
protected int xPos;
protected int yPos;
protected char character;
protected SuperConsoleColor colour;
public Entity()
{
}
public Entity(int xPosNew, int yPosNew, char newCharacter, SuperConsoleColor newColour)
{
//define position
xPos = xPosNew;
yPos = yPosNew;
//define character
character = newCharacter;
//define colour
colour = newColour;
}
public char GetChar()
{
return character;
}
public int GetX()
{
return xPos;
}
public int GetY()
{
return yPos;
}
public SuperConsoleColor GetColour()
{
return colour;
}
}
}
I see two issues:
Within RunGameLoop(Game game) you should replace while (SuperConsole.KeyAvailable) with if (SuperConsole.KeyAvailable).
Within Game.OnInput(ConsoleKey) you change the cursor position instead of the spaceship position
Also try using breakpoints to Check if the code reaches Game.Draw() and check if the spaceship position and the cursor position are correct.
Also you should get a bit more into C#.
Instead of
public char GetChar()
{
return character;
}
private character;
.Net allows you to use Properties:
public char Character
{
get; private set;
}
or
public char Character
{
get { return character; }
}
private character = '#';
Hope this helps.
Apart from that: No offense, but this question isn't really what Stackoverflow is for. In future, please be more patient and try to googling debugging tips instead of letting Stackoverflow do the 'dirty work' for you.

xamarin ViewPager Android

I was trying to create a Sliding-Tab-Layout. I followed this tutorial Sliding Tab Layout
and it was great, but I wanted to Load Specific Layout in each TabView
I also want to make each one loaded, when I select it or scroll to it just like facebook application.
The reason is not to take so much time to load for each View in ViewPager
and there is the classes:
SlidingTabStrip
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Graphics;
using Android.Util;
namespace SlidingTabLayoutTutorial
{
public class SlidingTabStrip : LinearLayout
{
//Copy and paste from here................................................................
private const int DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS = 0;
private const byte DEFAULT_BOTTOM_BORDER_COLOR_ALPHA = 0X26;
private const int SELECTED_INDICATOR_THICKNESS_DIPS = 3;
private int[] INDICATOR_COLORS = { 0xffffff };
private int[] DIVIDER_COLORS = { 0xffffff };
private const int DEFAULT_DIVIDER_THICKNESS_DIPS = 1;
private const float DEFAULT_DIVIDER_HEIGHT = 0.5f;
//Bottom border
private int mBottomBorderThickness;
private Paint mBottomBorderPaint;
private int mDefaultBottomBorderColor;
//Indicator
private int mSelectedIndicatorThickness;
private Paint mSelectedIndicatorPaint;
//Divider
private Paint mDividerPaint;
private float mDividerHeight;
//Selected position and offset
private int mSelectedPosition;
private float mSelectionOffset;
//Tab colorizer
private SlidingTabScrollView.TabColorizer mCustomTabColorizer;
private SimpleTabColorizer mDefaultTabColorizer;
//Stop copy and paste here........................................................................
//Constructors
public SlidingTabStrip (Context context) : this(context, null)
{ }
public SlidingTabStrip (Context context, IAttributeSet attrs) : base(context, attrs)
{
SetWillNotDraw(false);
float density = Resources.DisplayMetrics.Density;
TypedValue outValue = new TypedValue();
context.Theme.ResolveAttribute(Android.Resource.Attribute.ColorForeground, outValue, true);
int themeForeGround = outValue.Data;
mDefaultBottomBorderColor = SetColorAlpha(themeForeGround, DEFAULT_BOTTOM_BORDER_COLOR_ALPHA);
mDefaultTabColorizer = new SimpleTabColorizer();
mDefaultTabColorizer.IndicatorColors = INDICATOR_COLORS;
mDefaultTabColorizer.DividerColors = DIVIDER_COLORS;
mBottomBorderThickness = (int)(DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density);
mBottomBorderPaint = new Paint();
mBottomBorderPaint.Color = GetColorFromInteger(0x1B729E); //Gray
mSelectedIndicatorThickness = (int)(SELECTED_INDICATOR_THICKNESS_DIPS * density);
mSelectedIndicatorPaint = new Paint();
mDividerHeight = DEFAULT_DIVIDER_HEIGHT;
mDividerPaint = new Paint();
mDividerPaint.StrokeWidth = (int)(DEFAULT_DIVIDER_THICKNESS_DIPS * density);
}
public SlidingTabScrollView.TabColorizer CustomTabColorizer
{
set
{
mCustomTabColorizer = value;
this.Invalidate();
}
}
public int [] SelectedIndicatorColors
{
set
{
mCustomTabColorizer = null;
mDefaultTabColorizer.IndicatorColors = value;
this.Invalidate();
}
}
public int [] DividerColors
{
set
{
mDefaultTabColorizer = null;
mDefaultTabColorizer.DividerColors = value;
this.Invalidate();
}
}
private Color GetColorFromInteger(int color)
{
return Color.Rgb(Color.GetRedComponent(color), Color.GetGreenComponent(color), Color.GetBlueComponent(color));
}
private int SetColorAlpha(int color, byte alpha)
{
return Color.Argb(alpha, Color.GetRedComponent(color), Color.GetGreenComponent(color), Color.GetBlueComponent(color));
}
public void OnViewPagerPageChanged(int position, float positionOffset)
{
mSelectedPosition = position;
mSelectionOffset = positionOffset;
this.Invalidate();
}
protected override void OnDraw(Canvas canvas)
{
int height = Height;
int tabCount = ChildCount;
int dividerHeightPx = (int)(Math.Min(Math.Max(0f, mDividerHeight), 1f) * height);
SlidingTabScrollView.TabColorizer tabColorizer = mCustomTabColorizer != null ? mCustomTabColorizer : mDefaultTabColorizer;
//Thick colored underline below the current selection
if (tabCount > 0)
{
View selectedTitle = GetChildAt(mSelectedPosition);
int left = selectedTitle.Left;
int right = selectedTitle.Right;
int color = tabColorizer.GetIndicatorColor(mSelectedPosition);
if (mSelectionOffset > 0f && mSelectedPosition < (tabCount - 1))
{
int nextColor = tabColorizer.GetIndicatorColor(mSelectedPosition + 1);
if (color != nextColor)
{
color = blendColor(nextColor, color, mSelectionOffset);
}
View nextTitle = GetChildAt(mSelectedPosition + 1);
left = (int)(mSelectionOffset * nextTitle.Left + (1.0f - mSelectionOffset) * left);
right = (int)(mSelectionOffset * nextTitle.Right + (1.0f - mSelectionOffset) * right);
}
mSelectedIndicatorPaint.Color = GetColorFromInteger(color);
canvas.DrawRect(left, height - mSelectedIndicatorThickness, right, height, mSelectedIndicatorPaint);
//Creat vertical dividers between tabs
int separatorTop = (height - dividerHeightPx) / 2;
for (int i = 0; i < ChildCount -1; i++)
{
View child = GetChildAt(i);
mDividerPaint.Color = GetColorFromInteger(tabColorizer.GetDividerColor(i));
canvas.DrawLine(child.Right, separatorTop, child.Right, separatorTop + dividerHeightPx, mDividerPaint);
}
canvas.DrawRect(0, height - mBottomBorderThickness, Width, height, mBottomBorderPaint);
}
}
private int blendColor(int color1, int color2, float ratio)
{
float inverseRatio = 1f - ratio;
float r = (Color.GetRedComponent(color1) * ratio) + (Color.GetRedComponent(color2) * inverseRatio);
float g = (Color.GetGreenComponent(color1) * ratio) + (Color.GetGreenComponent(color2) * inverseRatio);
float b = (Color.GetBlueComponent(color1) * ratio) + (Color.GetBlueComponent(color2) * inverseRatio);
return Color.Rgb((int)r, (int)g, (int)b);
}
private class SimpleTabColorizer : SlidingTabScrollView.TabColorizer
{
private int[] mIndicatorColors;
private int[] mDividerColors;
public int GetIndicatorColor(int position)
{
return mIndicatorColors[position % mIndicatorColors.Length];
}
public int GetDividerColor (int position)
{
return mDividerColors[position % mDividerColors.Length];
}
public int[] IndicatorColors
{
set { mIndicatorColors = value; }
}
public int[] DividerColors
{
set { mDividerColors = value; }
}
}
}
}
SlidingTabScrollView
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Support.V4.View;
using Android.Util;
using Android.Graphics;
namespace SlidingTabLayoutTutorial
{
public class SlidingTabScrollView : HorizontalScrollView
{
private const int TITLE_OFFSET_DIPS = 15;
private const int TAB_VIEW_PADDING_DIPS = 15;
private const int TAB_VIEW_TEXT_SIZE_SP = 20;
private int mTitleOffset;
//private int mTabViewLayoutID;
//private int mTabViewTextViewID;
private ViewPager mViewPager;
private ViewPager.IOnPageChangeListener mViewPagerPageChangeListener;
private static SlidingTabStrip mTabStrip;
private int mScrollState;
public interface TabColorizer
{
int GetIndicatorColor(int position);
int GetDividerColor(int position);
}
public SlidingTabScrollView(Context context) : this(context, null) { }
public SlidingTabScrollView(Context context, IAttributeSet attrs) : this(context, attrs, 0) { }
public SlidingTabScrollView (Context context, IAttributeSet attrs, int defaultStyle) : base(context, attrs, defaultStyle)
{
//Disable the scroll bar
HorizontalScrollBarEnabled = false;
//Make sure the tab strips fill the view
FillViewport = true;
this.SetBackgroundColor(Android.Graphics.Color.ParseColor("#0078FF")); //Gray color
mTitleOffset = (int)(TITLE_OFFSET_DIPS * Resources.DisplayMetrics.Density);
mTabStrip = new SlidingTabStrip(context);
mTabStrip.WeightSum = 3;
this.AddView(mTabStrip, LayoutParams.MatchParent, LayoutParams.MatchParent);
}
public TabColorizer CustomTabColorizer
{
set { mTabStrip.CustomTabColorizer = value; }
}
public int [] SelectedIndicatorColor
{
set { mTabStrip.SelectedIndicatorColors = value; }
}
public int [] DividerColors
{
set { mTabStrip.DividerColors = value; }
}
public ViewPager.IOnPageChangeListener OnPageListener
{
set { mViewPagerPageChangeListener = value; }
}
public ViewPager ViewPager
{
set
{
mTabStrip.RemoveAllViews();
mViewPager = value;
if (value != null)
{
value.PageSelected += value_PageSelected;
value.PageScrollStateChanged += value_PageScrollStateChanged;
value.PageScrolled += value_PageScrolled;
PopulateTabStrip();
}
}
}
void value_PageScrolled(object sender, ViewPager.PageScrolledEventArgs e)
{
int tabCount = mTabStrip.ChildCount;
if ((tabCount == 0) || (e.Position < 0) || (e.Position >= tabCount))
{
//if any of these conditions apply, return, no need to scroll
return;
}
mTabStrip.OnViewPagerPageChanged(e.Position, e.PositionOffset);
View selectedTitle = mTabStrip.GetChildAt(e.Position);
int extraOffset = (selectedTitle != null ? (int)(e.Position * selectedTitle.Width) : 0);
ScrollToTab(e.Position, extraOffset);
if (mViewPagerPageChangeListener != null)
{
mViewPagerPageChangeListener.OnPageScrolled(e.Position, e.PositionOffset, e.PositionOffsetPixels);
}
}
void value_PageScrollStateChanged(object sender, ViewPager.PageScrollStateChangedEventArgs e)
{
mScrollState = e.State;
if (mViewPagerPageChangeListener != null)
{
mViewPagerPageChangeListener.OnPageScrollStateChanged(e.State);
}
}
void value_PageSelected(object sender, ViewPager.PageSelectedEventArgs e)
{
if (mScrollState == ViewPager.ScrollStateIdle)
{
mTabStrip.OnViewPagerPageChanged(e.Position, 0f);
ScrollToTab(e.Position, 0);
}
if (mViewPagerPageChangeListener != null)
{
mViewPagerPageChangeListener.OnPageSelected(e.Position);
}
}
private void PopulateTabStrip()
{
PagerAdapter adapter = mViewPager.Adapter;
for (int i = 0; i < adapter.Count; i++)
{
TextView tabView = CreateDefaultTabView(Context);
tabView.Text = ((SlidingTabsFragment.SamplePagerAdapter)adapter).GetHeaderTitle(i);
tabView.SetTextColor(Android.Graphics.Color.White);
tabView.Tag = i;
tabView.Click += tabView_Click;
mTabStrip.AddView(tabView);
}
}
void tabView_Click(object sender, EventArgs e)
{
TextView clickTab = (TextView)sender;
int pageToScrollTo = (int)clickTab.Tag;
mViewPager.CurrentItem = pageToScrollTo;
}
private TextView CreateDefaultTabView(Android.Content.Context context )
{
TextView textView = new TextView(context);
textView.Gravity = GravityFlags.Center;
textView.SetTextSize(ComplexUnitType.Sp, TAB_VIEW_TEXT_SIZE_SP);
textView.Typeface = Android.Graphics.Typeface.Default;
textView.LayoutParameters = new LinearLayout.LayoutParams(0, LayoutParams.MatchParent, 1);
if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Honeycomb)
{
TypedValue outValue = new TypedValue();
Context.Theme.ResolveAttribute(Android.Resource.Attribute.SelectableItemBackground, outValue, false);
textView.SetBackgroundResource(outValue.ResourceId);
}
if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.IceCreamSandwich)
{
textView.SetAllCaps(true);
}
int padding = (int)(TAB_VIEW_PADDING_DIPS * Resources.DisplayMetrics.Density);
textView.SetPadding(padding, padding, padding, padding);
return textView;
}
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
if (mViewPager != null)
{
ScrollToTab(mViewPager.CurrentItem, 0);
}
}
private void ScrollToTab(int tabIndex, int extraOffset)
{
int tabCount = mTabStrip.ChildCount;
if (tabCount == 0 || tabIndex < 0 || tabIndex >= tabCount)
{
//No need to go further, dont scroll
return;
}
View selectedChild = mTabStrip.GetChildAt(tabIndex);
if (selectedChild != null)
{
int scrollAmountX = selectedChild.Left + extraOffset;
if (tabIndex >0 || extraOffset > 0)
{
scrollAmountX -= mTitleOffset;
}
this.ScrollTo(scrollAmountX, 0);
}
}
}
}
SlidingTabsFragment
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Android.Support.V4.View;
namespace SlidingTabLayoutTutorial
{
public class SlidingTabsFragment : Fragment
{
private SlidingTabScrollView mSlidingTabScrollView;
private ViewPager mViewPager;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.Inflate(Resource.Layout.fragment_sample, container, false);
}
public override void OnViewCreated(View view, Bundle savedInstanceState)
{
mSlidingTabScrollView = view.FindViewById<SlidingTabScrollView>(Resource.Id.sliding_tabs);
mViewPager = view.FindViewById<ViewPager>(Resource.Id.viewpager);
mViewPager.Adapter = new SamplePagerAdapter();
mSlidingTabScrollView.ViewPager = mViewPager;
}
public class SamplePagerAdapter : PagerAdapter
{
List<string> items = new List<string>();
public SamplePagerAdapter() : base()
{
items.Add("Home");
items.Add("Sell");
items.Add("Rent");
}
public override int Count
{
get { return items.Count; }
}
public override bool IsViewFromObject(View view, Java.Lang.Object obj)
{
return view == obj;
}
public override Java.Lang.Object InstantiateItem(ViewGroup container, int position)
{
View view = LayoutInflater.From(container.Context).Inflate(Resource.Layout.pager_item, container, false);
container.AddView(view);
TextView txtTitle = view.FindViewById<TextView>(Resource.Id.item_title);
int pos = position + 1;
txtTitle.Text = pos.ToString();
return view;
}
public string GetHeaderTitle (int position)
{
return items[position];
}
public override void DestroyItem(ViewGroup container, int position, Java.Lang.Object obj)
{
container.RemoveView((View)obj);
}
}
}
}
MainActivity
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Support.V4.View;
namespace SlidingTabLayoutTutorial
{
[Activity(Label = "Sliding Tab Layout", MainLauncher = true, Icon = "#drawable/xs")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
FragmentTransaction transaction = FragmentManager.BeginTransaction();
SlidingTabsFragment fragment = new SlidingTabsFragment();
transaction.Replace(Resource.Id.sample_content_fragment, fragment);
transaction.Commit();
}
public override bool OnCreateOptionsMenu(IMenu menu)
{
MenuInflater.Inflate(Resource.Menu.actionbar_main, menu);
return base.OnCreateOptionsMenu(menu);
}
}
}
I think you need to add in your code something like this : (in OnCreateView() )
position => comes from the adapter..
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
switch (position)
{
case 0:
view = (ViewGroup)inflater.Inflate(Resource.Layout.Page1, container, false);
break;
case 1:
view = (ViewGroup)inflater.Inflate(Resource.Layout.Page2, container, false);
btn_forexample = view.FindViewById<Button>(Resource.Id.btn_forexample);
break;
case 2:
view = (ViewGroup)inflater.Inflate(Resource.Layout.Page3, container, false);
break;
default:
view = (ViewGroup)inflater.Inflate(Resource.Layout.DefaultPage, container, false);
break;
}
return view;
}
Hope it helps ;)

How to implement movement in a chess game ?

I am learning to make a small variant of chess game using windows forms C#, the game includes only the pawns of both sides, i have drew the board and organized the pieces on there places, but i honestly do not know how to start implementing the moves by clicking the mouse on the piece and then the location where i want to move it.
as references the black pawn is named piece, and white pawn is named pieceW
here is my code for the board
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AIchess
{
public partial class Form1 : Form
{
static System.Drawing.Bitmap piece = AIchess.Properties.Resources.piece;
ChessPiece Piece = new ChessPiece(piece, ChessColor.Black);
static System.Drawing.Bitmap pieceW = AIchess.Properties.Resources.pieceW;
ChessPiece PieceW = new ChessPiece(pieceW, ChessColor.White);
Square[,] square = new Square[8, 8];
public Form1()
{
InitializeComponent();
int i, j;
for (i = 0; i < 8; i++)
{
for (j = 0; j < 8; j++)
{
this.square[i, j] = new Square();
this.square[i, j].BackColor = System.Drawing.SystemColors.ActiveCaption;
this.square[i, j].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.square[i, j].Location = new System.Drawing.Point(57 + i * 60, 109 + j * 60);
this.square[i, j].Name = i.ToString()+j.ToString();
this.square[i, j].Size = new System.Drawing.Size(60, 60);
this.square[i, j].TabIndex = 2;
this.square[i, j].TabStop = false;
this.Controls.Add(this.square[i, j]);
if (j == 1)
{
this.square[i, j].Image = piece;
this.square[i, j].AllocatedBy = "black";
}
if (j == 6)
{
this.square[i, j].Image = pieceW;
this.square[i, j].AllocatedBy = "white";
}
if (((i+j) % 2) ==0)
this.square[i, j].BackColor = Color.RoyalBlue;
else
this.square[i, j].BackColor = Color.LightBlue;
}
}
}
}
public enum ChessColor
{
White,
Black,
};
class ChessPiece
{
private Image DisplayedImage;
private ChessColor DisplayedColor;
private Point CurrentSquare;
public ChessPiece(Image image, ChessColor color)
{
DisplayedImage = image;
DisplayedColor = color;
}
}
class Square:PictureBox
{
private bool color;
public string AllocatedBy;
}
}
Here's a really simple implementation, I hope you won't mind that I did it from scratch.
Obviously it's very simple, there's no drag and drop and no animation but it fulfills your requirement.
I'll go through each part and explain them
InitializeGame
There you do set your images dimensions (they should be identical obviously)
You add in the dictionary the relationship between piece type/color and your bitmap
Note : the grid will be scaled so you can throw any size of bitmap you like
CreateBoard, DrawGame, DrawPieces
Nothing exceptional in there, note that for keeping things simple I do that every time a user clicks but it shouldn't be much of an issue, it's not Crysis after all :D
PickOrDropPiece
This is the logic where picking/dropping happens, it's really trivial and I'll let you take a look by yourself.
Differences between your code
I've created a Board type which holds the pieces and that you can easily update.
Note : do not remove the equality members in Piece they are here to help the dictionary.
Make sure to use 32-bit bitmaps with transparent borders
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
pictureBox1.MouseDown += pictureBox1_MouseDown;
}
#region Properties
private Board Board { get; set; }
private Piece CurrentPiece { get; set; }
private Dictionary<Piece, Bitmap> PieceBitmaps { get; set; }
private int TileWidth { get; set; }
private int TileHeight { get; set; }
#endregion
#region Events
private void Form1_Load(object sender, EventArgs e)
{
InitializeGame();
DrawGame();
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
PickOrDropPiece(e);
DrawGame();
}
#endregion
#region Methods
private void InitializeGame()
{
TileWidth = 64;
TileHeight = 64;
Board = new Board();
PieceBitmaps = new Dictionary<Piece, Bitmap>();
PieceBitmaps.Add(new Piece(PieceType.Pawn, PieceColor.Black), new Bitmap("pawnblack.png"));
PieceBitmaps.Add(new Piece(PieceType.Pawn, PieceColor.White), new Bitmap("pawnwhite.png"));
}
private void DrawGame()
{
var tileSize = new Size(TileWidth, TileHeight);
Bitmap bitmap = CreateBoard(tileSize);
DrawPieces(bitmap);
pictureBox1.Image = bitmap;
}
private Bitmap CreateBoard(Size tileSize)
{
int tileWidth = tileSize.Width;
int tileHeight = tileSize.Height;
var bitmap = new Bitmap(tileWidth*8, tileHeight*8);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
Brush brush = (x%2 == 0 && y%2 == 0) || (x%2 != 0 && y%2 != 0) ? Brushes.Black : Brushes.White;
graphics.FillRectangle(brush, new Rectangle(x*tileWidth, y*tileHeight, tileWidth, tileHeight));
}
}
}
return bitmap;
}
private void DrawPieces(Bitmap bitmap)
{
using (Graphics graphics = Graphics.FromImage(bitmap))
{
Board board = Board;
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
Piece piece = board.GetPiece(x, y);
if (piece != null)
{
Bitmap bitmap1 = PieceBitmaps[piece];
graphics.DrawImageUnscaled(bitmap1, new Point(x*TileWidth, y*TileHeight));
}
}
}
}
}
private void PickOrDropPiece(MouseEventArgs e)
{
Point location = e.Location;
int x = location.X/TileWidth;
int y = location.Y/TileHeight;
bool pickOrDrop = CurrentPiece == null;
if (pickOrDrop)
{
// Pick a piece
Piece piece = Board.GetPiece(x, y);
Board.SetPiece(x, y, null);
if (piece != null)
{
label1.Text = string.Format("You picked a {0} {1} at location {2},{3}", piece.Color, piece.Type, x,
y);
}
else
{
label1.Text = "Nothing there !";
}
CurrentPiece = piece;
}
else
{
// Drop picked piece
Board.SetPiece(x, y, CurrentPiece);
label1.Text = string.Format("You dropped a {0} {1} at location {2},{3}", CurrentPiece.Color,
CurrentPiece.Type, x,
y);
CurrentPiece = null;
}
}
#endregion
}
public class Board
{
private readonly Piece[] _pieces;
public Board()
{
_pieces = new Piece[8*8];
PopulatePieces();
}
public Piece GetPiece(int x, int y)
{
int i = y*8 + x;
return _pieces[i];
}
public void SetPiece(int x, int y, Piece piece)
{
int i = y*8 + x;
_pieces[i] = piece;
}
private void PopulatePieces()
{
for (int i = 0; i < 8; i++)
{
SetPiece(i, 1, new Piece(PieceType.Pawn, PieceColor.Black));
SetPiece(i, 7, new Piece(PieceType.Pawn, PieceColor.White));
}
}
}
public class Piece
{
private readonly PieceColor _color;
private readonly PieceType _type;
public Piece(PieceType type, PieceColor color)
{
_type = type;
_color = color;
}
public PieceType Type
{
get { return _type; }
}
public PieceColor Color
{
get { return _color; }
}
protected bool Equals(Piece other)
{
return _color == other._color && _type == other._type;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((Piece) obj);
}
public override int GetHashCode()
{
unchecked
{
return ((int) _color*397) ^ (int) _type;
}
}
public static bool operator ==(Piece left, Piece right)
{
return Equals(left, right);
}
public static bool operator !=(Piece left, Piece right)
{
return !Equals(left, right);
}
}
public enum PieceType
{
Pawn
}
public enum PieceColor
{
Black,
White
}
}

Categories

Resources