When using gtext command, can I force the text to be placed in a specific area that nearby where a user places it.

3 views (last 30 days)
I am creating a program for two players to play a game of Tic Tac Toe. I created the board using axis([0 3 0 3]) and xline, yline commands. Then to give the ability to place the X’s and O’s I used gtext command. The problem is that the X’s and O’s can cross over the lines and go out of the box. I’m trying to say when the user clicks anywhere inside the upper left box then the X or O will automatically fix to that box’s center point. Is this possible?

Accepted Answer

Walter Roberson
Walter Roberson on 14 Mar 2021
Edited: Walter Roberson on 14 Mar 2021
No, gtext() cannot do that automatically.
You have two choices:
  1. record the output handle from gtext(), and examine its Position property, quantize as appropriate, and change the Position property; or
  2. use ginput() to get the position, quantize as appropriate, and text() at that location; gtext() would not be used in this case. If you took this approach you would have more control for refusing an input click in a location that was already occupied.
  6 Comments
Walter Roberson
Walter Roberson on 14 Mar 2021
In this context, x and y are pure numeric coordinates. isempty(x) is a test for the case where the user simply pressed return instead of clicking.
The code I posted makes not attempt to check to see whether a cell is occupied. It is only the logic for accepting clicks and drawing at the center. It addresses your question,
The problem is that the X’s and O’s can cross over the lines and go out of the box. I’m trying to say when the user clicks anywhere inside the upper left box then the X or O will automatically fix to that box’s center point.
It does not validate the move before it draws the letter, other than checking to be sure that it is inside the box. You need to build upon it... and that is something you will need to think about yourself, as this is homework.
Some things to keep in mind:
  • you choose to work in terms of coordinates in the range 0 to 3
  • the code has a bug for the situation in which the user managed to click exactly at the 3
  • the x and y that are used to text() are data coordinates for drawing purposes, and are not array indices.
  • array indices cannot not be fractions and cannot be less than 1
The changes are pretty simple, really, but it is your homework to think about.

Sign in to comment.

More Answers (0)

Categories

Find more on Labels and Annotations in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!