필터 지우기
필터 지우기

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

조회 수: 4 (최근 30일)
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?

채택된 답변

Walter Roberson
Walter Roberson 2021년 3월 14일
편집: Walter Roberson 2021년 3월 14일
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
Walter Roberson
Walter Roberson 2021년 3월 14일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Labels and Annotations에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by