Текущее время: Пт, июл 18 2025, 17:53

Часовой пояс: UTC + 3 часа


Правила форума


ВНИМАНИЕ!

Вопросы по SAP Query и Quick View - сюда



Начать новую тему Ответить на тему  [ Сообщений: 13 ] 
Автор Сообщение
 Заголовок сообщения: Тетрис
СообщениеДобавлено: Чт, окт 22 2009, 13:11 
Гуру-эксперт
Гуру-эксперт
Аватара пользователя

Зарегистрирован:
Вс, янв 11 2009, 14:41
Сообщения: 902
Откуда: Москва
Пол: Мужской
Это программа в общее пользование

Code:
REPORT ZTETRIS NO STANDARD PAGE HEADING.

  include <icon>.

* логический тип
  types:
    TBool type c.

  constants:
    true type TBool value 'X',
    false type TBool value space.

* поле
  data:
    C_FIELD_WIDTH type i,
    C_FIELD_HEIGHT type i.

  C_FIELD_WIDTH = 15.
  C_FIELD_HEIGHT = sy-srows / 2.

  types:
    begin of TCell,
      X type i,
      Y type i,
      content(4) type c,
    end of TCell.

  data:
    g_t_cell type hashed table of TCell
    with unique key Y X.

* поле для сброса
  types:
    TTCell type table of TCell with default key,
    TTRow type table of TTCell.

* фигуры
  constants:
    C_NUM_FIGURES type i value 7.

  types:
    begin of TPos,
      X type i,
      Y type i,
    end of TPos,

    TTPos type table of TPos with default key,

    begin of TFigure,
      fig_num type i,
      rot_num type i,
      t_pos type TTPos,
    end of TFigure,

    TTFigure type hashed table of TFigure
    with unique key fig_num rot_num.

  data:
    g_t_figure type TTFigure,

    begin of g_act_figure,
      fig_num type i,
      rot_num type i,
      X type i,
      Y type i,
    end of g_act_figure.

* заствака
  perform show_top_users.
  return.

* очки
  data:
    g_score type i,
    g_speed type i,
    g_is_game_over type TBool.

*ЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖ
*
* процесс...
*
*ЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖ

form process.

  g_speed = 500.

  perform init_figures.
  perform init_field.
  perform init_field_figure.
  perform redraw.

  call function 'ZDELAY'
  starting new task 'TETRIS'
  performing return_info on end of task
  exporting
    p_milsec = g_speed
  exceptions
    others = 1.
endform.

*ЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖ
*
* движение...
*
*ЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖ

* асинхронный вызов
form return_info using taskname.

  receive results from function 'ZDELAY'
  exceptions
    others = 1.

  set user-command 'MOVE'.
endform.

* движение
at user-command.

  if sy-ucomm = 'MOVE'.

    data:
      v_old_figure like g_act_figure,
      v_new_figure like g_act_figure.

    v_old_figure = v_new_figure = g_act_figure.
    v_new_figure-Y = v_new_figure-Y + 1.

    perform move_figure
    using
      v_old_figure
      v_new_figure
      true.

    if sy-subrc <> 0.

      perform check_field.

      perform init_field_figure.

      if sy-subrc <> 0.
        perform game_over.
      else.
        perform redraw.

        call function 'ZDELAY'
        starting new task 'TETRIS'
        performing return_info on end of task
        exporting
          p_milsec = g_speed
        exceptions
          others = 1.
      endif.
    endif.
  endif.

* перевернуть фигуру
at pf7.

  if g_is_game_over = true or g_speed = 0.
    exit.
  endif.

  v_old_figure = v_new_figure = g_act_figure.

  if v_new_figure-rot_num = 4.
    clear v_new_figure-rot_num.
  endif.

  v_new_figure-rot_num = v_new_figure-rot_num + 1.

  perform move_figure
  using
    v_old_figure
    v_new_figure
    false.

* сдвинуть фигуру влево
at pf6.

  if g_is_game_over = true or g_speed = 0.
    exit.
  endif.

  v_old_figure = v_new_figure = g_act_figure.
  v_new_figure-X = v_new_figure-X - 1.

  perform move_figure
  using
    v_old_figure
    v_new_figure
    false.

* сдвинуть фигуру вправо
at pf8.

  if g_is_game_over = true or g_speed = 0.
    exit.
  endif.

  v_old_figure = v_new_figure = g_act_figure.
  v_new_figure-X = v_new_figure-X + 1.

  perform move_figure
  using
    v_old_figure
    v_new_figure
    false.

* бросить вниз
at pf5.

  if g_is_game_over = true or g_speed = 0.
    exit.
  endif.

  do.
    v_old_figure = v_new_figure = g_act_figure.
    v_new_figure-Y = v_new_figure-Y + 1.

    perform move_figure
    using
      v_old_figure
      v_new_figure
      false.

    if sy-subrc <> 0.

      perform check_field.

      perform init_field_figure.
      perform redraw.

      call function 'ZDELAY'
      starting new task 'TETRIS'
      performing return_info on end of task
      exporting
        p_milsec = g_speed
      exceptions
        others = 1.

      exit.
    endif.
  enddo.

* сдвинуть фигуру
* {
*   sy-subrc = 0 - успешно
* }
form move_figure
using
  p_old_figure like g_act_figure
  p_new_figure like g_act_figure
  p_do_more type TBool.

  clear sy-lsind.

  perform set_field_figure
  using
    space
    false.

  g_act_figure = p_new_figure.

  perform set_field_figure
  using
    ICON_STATUS_BEST
    true.

  if sy-subrc = 0.

    perform set_field_figure
    using
      ICON_STATUS_BEST
      false.

    perform redraw.

    if p_do_more = true.

      call function 'ZDELAY'
      starting new task 'TETRIS'
      performing return_info on end of task
      exporting
        p_milsec = g_speed
      exceptions
        others = 1.
    endif.

    clear sy-subrc.
  else.
    g_act_figure = p_old_figure.

    perform set_field_figure
    using
      ICON_STATUS_BEST
      false.

    sy-subrc = 1.
  endif.
endform.

* проверить поле и сбросить строки
form check_field.

* копируем во временную таблицу
  data:
    v_t_row type TTRow,
    v_cell like line of g_t_cell[].

  do C_FIELD_HEIGHT times.
    v_cell-Y = sy-index.

    field-symbols:
      <row> like line of v_t_row[].

    append initial line to v_t_row assigning <row>.

    do C_FIELD_WIDTH times.
      v_cell-X = sy-index.

      field-symbols:
        <cell> like line of g_t_cell[].

      read table g_t_cell
      with table key
        Y = v_cell-Y
        X = v_cell-X
      assigning
        <cell>.

      append <cell> to <row>.
    enddo.
  enddo.

* удаляем заполненные строки
  loop at v_t_row assigning <row>.

    data:
      v_row_num type i.

    v_row_num = sy-tabix.

    loop at <row> assigning <cell>.

      if sy-tabix = 1.
        continue.
      endif.

      if <cell>-content <> ICON_STATUS_BEST.
        exit.
      endif.
    endloop.

    if <cell>-X = C_FIELD_WIDTH.
      delete v_t_row index v_row_num.
    endif.
  endloop.

* удаляем заполненные строки
  v_row_num = C_FIELD_HEIGHT - lines( v_t_row ).

  data:
    v_row like <row>.

  do C_FIELD_WIDTH times.
    v_cell-X = sy-index.

    if v_cell-X = 1 or v_cell-X = C_FIELD_WIDTH.
      v_cell-content = ICON_OO_CLASS.
    else.
      v_cell-content = space.
    endif.

    append v_cell to v_row.
  enddo.

  do v_row_num times.
    insert v_row into v_t_row index 1.
    g_score = g_score + 100.
    g_speed = g_speed - 2.
  enddo.

* переписываем строки в хэш таблицу
  loop at v_t_row assigning <row>.
    v_row_num = sy-tabix.

    loop at <row> assigning <cell>.

      field-symbols:
        <cell2> like line of g_t_cell[].

      read table g_t_cell
      with table key
        Y = v_row_num
        X = sy-tabix
      assigning
        <cell2>.

      <cell2>-content = <cell>-content.
    endloop.
  endloop.
endform.

*ЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖ
*
* подпрограммы...
*
*ЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖ

* подготовить фигуры
form init_figures.

  data:
    v_figures type string.

  define DEF_FIGURE.
    concatenate v_figures &1 into v_figures.
  end-of-definition.

  DEF_FIGURE `0 0 0 -1 0 1 1 1 0 0 -1 0 1 0 1 -1 0 0 0 -1 -1 -1 0 1 0 0 -1 0 1 0 -1 1`.
  DEF_FIGURE ` 0 0 0 -1 1 -1 1 0 0 0 0 -1 1 -1 1 0 0 0 0 -1 1 -1 1 0 0 0 0 -1 1 -1 1 0`.
  DEF_FIGURE ` 0 0 0 -1 1 0 1 1 0 0 -1 0 0 -1 1 -1 0 0 0 -1 1 0 1 1 0 0 -1 0 0 -1 1 -1`.
  DEF_FIGURE ` 0 0 0 -1 0 1 0 2 0 0 -1 0 1 0 2 0 0 0 0 -1 0 1 0 2 0 0 -1 0 1 0 2 0`.
  DEF_FIGURE ` 0 0 0 -1 0 1 -1 1 0 0 1 0 -1 0 -1 -1 0 0 0 -1 1 -1 0 1 0 0 -1 0 1 0 1 1`.
  DEF_FIGURE ` 0 0 1 0 1 -1 0 1 0 0 -1 0 0 1 1 1 0 0 1 0 1 -1 0 1 0 0 -1 0 0 1 1 1`.
  DEF_FIGURE ` 0 0 -1 0 1 0 0 1 0 0 0 -1 0 1 1 0 0 0 -1 0 1 0 0 -1 0 0 0 -1 0 1 -1 0`.

  data:
    v_t_figure_str type table of string with header line.

  split v_figures at space into table v_t_figure_str.

  data:
    v_figure like line of g_t_figure[],
    v_index type i.

  field-symbols:
    <pos> like line of v_figure-t_pos[].

  do C_NUM_FIGURES times.

    v_figure-fig_num = sy-index.
    clear v_figure-rot_num.

    do 4 times.

      v_figure-rot_num = sy-index.
      refresh v_figure-t_pos[].

      do 4 times.

        append initial line to v_figure-t_pos assigning <pos>.

        v_index = v_index + 1.
        read table v_t_figure_str index v_index.
        <pos>-X = v_t_figure_str.

        v_index = v_index + 1.
        read table v_t_figure_str index v_index.
        <pos>-Y = v_t_figure_str.
      enddo.

      insert v_figure into table g_t_figure.
    enddo.
  enddo.
endform.

* инициировать поле
form init_field.

  data:
    v_cell like line of g_t_cell[].

  do C_FIELD_HEIGHT times.
    v_cell-Y = sy-index.

    do C_FIELD_WIDTH times.
      v_cell-X = sy-index.

      if v_cell-X = 1 or v_cell-X = C_FIELD_WIDTH or v_cell-Y = C_FIELD_HEIGHT.
        v_cell-content = ICON_OO_CLASS.
      else.
        v_cell-content = space.
      endif.

      insert v_cell into table g_t_cell.
    enddo.
  enddo.
endform.

* разместить фигуру на поле
* {
*   sy-subrc = 0 - успешно
* }
form init_field_figure.

  data:
    v_value type f.

  perform get_random_value
  changing
    v_value.

  g_act_figure-fig_num = trunc( v_value * 100 / ( 100 / C_NUM_FIGURES ) ) + 1.
  g_act_figure-rot_num = 1.

  g_act_figure-X = 7.
  g_act_figure-Y = 2.

  perform set_field_figure
  using
    ICON_STATUS_BEST
    true.

  if sy-subrc = 0.

    perform set_field_figure
    using
      ICON_STATUS_BEST
      false.

    g_score = g_score + 10.
  endif.
endform.

* установить фигуру на поле
* {
*   sy-subrc = 0 - успешно
* }
form set_field_figure
using
  p_content type TCell-content
  p_check type TBool.

  field-symbols:
    <figure> like line of g_t_figure[].

  read table g_t_figure
  with table key
    fig_num = g_act_figure-fig_num
    rot_num = g_act_figure-rot_num
  assigning
    <figure>.

  field-symbols:
    <pos> like line of <figure>-t_pos[].

  loop at <figure>-t_pos assigning <pos>.

    perform set_field_cell
    using
      g_act_figure-X
      g_act_figure-Y
      <pos>-X
      <pos>-Y
      p_content
      p_check.

    if sy-subrc <> 0.
      return.
    endif.
  endloop.

  clear sy-subrc.
endform.

* установить ячейку поля
* {
*   sy-subrc = 0 - успешно
* }
form set_field_cell
using
  value(p_X) type TCell-X
  value(p_Y) type TCell-Y
  p_X_offs type TPos-X
  p_Y_offs type TPos-Y
  p_content type TCell-content
  p_check type TBool.

  p_X = p_X + p_X_offs.
  p_Y = p_Y + p_Y_offs.

  field-symbols:
    <cell> like line of g_t_cell[].

  read table g_t_cell
  with table key
    Y = p_Y
    X = p_X
  assigning
    <cell>.

  if not <cell>-content is initial and not p_content is initial.
    sy-subrc = 1.
  else.
    if p_check = false.
      <cell>-content = p_content.
    endif.
    clear sy-subrc.
  endif.
endform.

* перерисовать поле
form redraw.

  sy-linno = 1.

  data:
    v_X type i,
    v_Y type i,
    v_score_Y type i.

  v_score_Y = C_FIELD_HEIGHT / 2 - 1.

  do C_FIELD_HEIGHT times.
    v_Y = sy-index.

    do C_FIELD_WIDTH times.
      v_X = sy-index.

      field-symbols:
        <cell> like line of g_t_cell[].

      read table g_t_cell
      with table key
        Y = v_Y
        X = v_X
      assigning
        <cell>.

      if sy-subrc = 0.

        data:
          v_show_X type i.

        v_show_X = v_X * 4.
        write at v_show_X <cell>-content.
      endif.
    enddo.

    if v_score_Y = v_Y.

      data:
        v_score_str type string.

      v_score_str = g_score.
      condense v_score_str.

      concatenate `Очки: ` v_score_str into v_score_str.

      data:
        v_score_X type i.

      v_score_X = C_FIELD_WIDTH * 4 + ( sy-scols - C_FIELD_WIDTH * 4 - ( strlen( ICON_READ_FILE ) + 8 ) ) / 2.

      if v_score_X <= C_FIELD_WIDTH.
        v_score_X = C_FIELD_WIDTH * 4 + 5.
      endif.

      write: at v_score_X ICON_READ_FILE as icon, v_score_str.
    endif.

    write /.
  enddo.
endform.

* получить случайное число в диапазоне от 0..1
form get_random_value
changing
  p_value type f.

  statics:
    v_random_seed type i.

  constants:
    v_s type i value 16807,
    v_m(6) type p value 2147483648.

  data:
    v_ks type string.

  if v_random_seed is initial.
    v_ks = sy-uzeit.

    shift v_ks circular.
    shift v_ks circular.
    shift v_ks circular.
    shift v_ks circular.

    v_random_seed = v_ks * v_ks mod ( v_m - 1 ).
  endif.

  v_random_seed = ( v_random_seed * v_s ) mod ( v_m - 1 ).
  p_value = v_random_seed / v_m.
endform.

* показать чемпионов
form show_top_users.

  data:
    v_t_user type table of ztetuser with header line.

  select
    *
  into table
    v_t_user
  from
    ztetuser.

  sort v_t_user by score descending.

  loop at v_t_user.
    if sy-tabix > 10.
      delete v_t_user index sy-tabix.
    endif.
  endloop.

  data:
    v_col type i,
    v_row type i.

  v_row = ( sy-srows - ( lines( v_t_user ) + 14 ) * 2 ) / 2.
  do v_row times.
    write /.
  enddo.

  v_col = ( sy-scols - 68 ) / 2 + 33.
  write: /, at v_col 'ТЕТРИС', /, /.
  v_col = v_col - 33.

  v_col = v_col + 17.
  write: /,
    at v_col ICON_COLUMN_LEFT as icon, '- (F6)',
    ICON_MODIFY as icon, '- (F7)',
    ICON_COLUMN_RIGHT as icon, '- (F8)',
    ICON_PREVIOUS_VALUE as icon, '- (F5)', /, /.
  v_col = v_col - 17.

  v_col = v_col + 25.
  write: /, at v_col 'Список бездельников!'.
  write: /, at v_col '--------------------', /.
  v_col = v_col - 25.

  loop at v_t_user.

    data:
      v_user type USR03,
      v_full_name type string.

    v_full_name = sy-tabix.

    clear v_user.

    CALL FUNCTION 'SUSR_SHOW_USER_DETAILS'
    EXPORTING
      BNAME = v_t_user-username
      NO_DISPLAY = 'X'
    CHANGING
      USER_USR03 = v_user.

    concatenate
      v_full_name ` ` v_t_user-username ` (` v_user-name1 ` ` v_user-name2 `)`
    into
      v_full_name.

    write: /, at v_col v_full_name.

    v_col = v_col + 60.
    write at v_col v_t_user-score.
    v_col = v_col - 60.

  endloop.

  call function 'ZDELAY'
  starting new task 'TETRIS0'
  performing return_info0 on end of task
    exporting
  p_milsec = 5000
    exceptions
  others = 1.
endform.

* задержка
form return_info0 using taskname.

  receive results from function 'ZDELAY'
  exceptions
    others = 1.

  perform process.
endform.

* конец игры
form game_over.

  g_is_game_over = true.

  constants:
    C_GAME_OVER type string value 'Конец игры!'.

  sy-linno = 1.

  data:
    v_cnt type i.

  v_cnt = sy-srows / 2 - 1.

  do v_cnt times.
    write /.
  enddo.

  v_cnt = ( sy-scols - strlen( C_GAME_OVER ) ) / 2.

  write at v_cnt C_GAME_OVER.

  data:
    v_user type ztetuser.

  select single
    *
  into
    v_user
  from
    ztetuser
  where
    username = sy-uname.

  if sy-subrc = 0.
    if v_user-score >= g_score.
      exit.
    endif.
  endif.

  v_user-username = sy-uname.
  v_user-score = g_score.
  modify ztetuser from v_user.
endform.

FUNCTION ZDELAY.
*"----------------------------------------------------------------------
*"*"Локальный интерфейс:
*"  IMPORTING
*"     VALUE(P_MILSEC) TYPE  I
*"----------------------------------------------------------------------

  data:
    v_ts type timestampl,
    v_ts_new type timestampl,
    v_delta type i.

  get time stamp field v_ts.

  while v_delta <= p_milsec.

    get time stamp field v_ts_new.
    v_delta = ( v_ts_new - v_ts ) * 1000.
  endwhile.

ENDFUNCTION.


Последний раз редактировалось murmur Чт, окт 22 2009, 14:54, всего редактировалось 1 раз.

Принять этот ответ
Вернуться к началу
 Профиль Отправить email  
 
 Заголовок сообщения: Re: Очень важный код
СообщениеДобавлено: Чт, окт 22 2009, 17:10 
Гуру-эксперт
Гуру-эксперт
Аватара пользователя

Зарегистрирован:
Чт, ноя 11 2004, 16:25
Сообщения: 3109
Пол: Мужской
The type "ZTETUSER" is unknown.


Принять этот ответ
Вернуться к началу
 Профиль  
 
 Заголовок сообщения: Re: Очень важный код
СообщениеДобавлено: Пт, окт 23 2009, 09:10 
Специалист
Специалист
Аватара пользователя

Зарегистрирован:
Пт, ноя 25 2005, 15:06
Сообщения: 143
Besa написал:
The type "ZTETUSER" is unknown.

Я так понимаю надо создать таблицу ZTETUSER такой структуры:
Code:
MANDT  MANDT
USERNAME   UNAME
FULL_NAME  SYTABIX
SCORE        INT4

Все равно идет ошибка:
The main program of the function "ZDELAY" does not begin with
"FUNCTION-POOL".


Принять этот ответ
Вернуться к началу
 Профиль  
 
 Заголовок сообщения: Re: Тетрис
СообщениеДобавлено: Пт, окт 23 2009, 09:17 
Специалист
Специалист
Аватара пользователя

Зарегистрирован:
Пт, ноя 25 2005, 15:06
Сообщения: 143
Удалость запустить если заменить
Code:
REPORT ZTETRIS NO STANDARD PAGE HEADING.
на
Code:
FUNCTION-POOL

и объявить
Code:
DATA: p_milsec type i.
:D


Принять этот ответ
Вернуться к началу
 Профиль  
 
 Заголовок сообщения: Re: Тетрис
СообщениеДобавлено: Пт, окт 23 2009, 11:55 
Ассистент
Ассистент
Аватара пользователя

Зарегистрирован:
Пн, окт 06 2008, 14:27
Сообщения: 46
:)
Молодость вспоминается ))))))))) Первая самостоятельная разработка...
Я тогда бросил это на полдороге - не хватило упорности побороть ограничение 1fps... хотя и догадывался, как нужно...
Тут, как я понимаю, ускорение со временем все же есть? просто сейчас нет прав на установку программ, полюбоваться не могу :(

PS мой недоделанный вариант все еще валяется на http://www.erpgenie.com/sap/abap/code/abap24.htm странно что его до сей поры никто не попытался улучшить :)


Принять этот ответ
Вернуться к началу
 Профиль  
 
 Заголовок сообщения: Re: Тетрис
СообщениеДобавлено: Пт, окт 23 2009, 12:03 
Гуру-эксперт
Гуру-эксперт
Аватара пользователя

Зарегистрирован:
Вс, янв 11 2009, 14:41
Сообщения: 902
Откуда: Москва
Пол: Мужской
ZDELAY должен быть дистанционным (RFC)


Принять этот ответ
Вернуться к началу
 Профиль Отправить email  
 
 Заголовок сообщения: Re: Тетрис
СообщениеДобавлено: Пн, окт 26 2009, 10:53 
Почетный гуру
Почетный гуру
Аватара пользователя

Зарегистрирован:
Чт, окт 06 2005, 16:44
Сообщения: 3080
Откуда: Москва
У нас консультанта SAP выгнали с проекта после того, как обнаружили ZTETRIS в продуктиве в результате аудита :roll:

_________________
С уважением,
Удав.


Принять этот ответ
Вернуться к началу
 Профиль  
 
 Заголовок сообщения: Re: Тетрис
СообщениеДобавлено: Сб, окт 31 2009, 22:56 
Гуру-эксперт
Гуру-эксперт
Аватара пользователя

Зарегистрирован:
Вс, янв 11 2009, 14:41
Сообщения: 902
Откуда: Москва
Пол: Мужской
Ну да... ТЕТРИС к SAP-у как-то не очень подходит... :roll:
Могу выложить версию САПЕР-а... он по-моему в тему будет :D


Принять этот ответ
Вернуться к началу
 Профиль Отправить email  
 
 Заголовок сообщения: Re: Тетрис
СообщениеДобавлено: Пн, ноя 02 2009, 10:37 
Начинающий
Начинающий

Зарегистрирован:
Вт, июл 28 2009, 11:40
Сообщения: 10
Давай сапера!!! :D


Принять этот ответ
Вернуться к началу
 Профиль Отправить email  
 
 Заголовок сообщения: Re: Тетрис
СообщениеДобавлено: Вт, ноя 03 2009, 15:09 
Гуру-эксперт
Гуру-эксперт
Аватара пользователя

Зарегистрирован:
Вс, янв 11 2009, 14:41
Сообщения: 902
Откуда: Москва
Пол: Мужской
Только статус MAIN сами уж как-нить... и модераторам не говорите, а то они ругаются и делают мне ай-я-яй :roll:


Code:
*&---------------------------------------------------------------------*
*& Report  ZSAPER                                                 *
*&                                                                     *
*&---------------------------------------------------------------------*
*&                                                                     *
*&                                                                     *
*&---------------------------------------------------------------------*

REPORT ZSAPER LINE-SIZE 300 NO STANDARD PAGE HEADING.

include <icon>.

types:
  TBool(1) type c.

constants:
  TRUE type TBool value '1',
  FALSE type TBool value '0'.

*ЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖ
*
* ячейка
*
*ЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖ

* itfc
class TCell definition.

  public section.

    types:
      TCellType(1) type c.

    constants:
      C_MINE type TCellType value 'M',
      C_EMPTY type TCellType value 'E'.

*   конструктор
    methods constructor
    importing
      p_x type i
      p_y type i
      value(p_mine_percent) type i.

*   получить X-координату в матрице
    methods get_x returning value(p_x) type i.
*   получить Y-координату в матрице
    methods get_y returning value(p_y) type i.
*   получить тип ячейки
    methods get_cell_type returning value(p_cell_type) type TCellType.

*   открыть ячейку
    methods open.
*   проверить, открыта ли ячейка
    methods is_opened returning value(p_is_opened) type TBool.

*   отметить ячейку
    methods check_on.
*   снять отметку с ячейки
    methods check_off.
*   проверить, отмечена ли ячейка
    methods is_checked returning value(p_is_checked) type TBool.

*   указать количество мин вокруг
    methods set_mine_count importing p_mine_count type i.
*   получить количество мин вокруг
    methods get_mine_count returning value(p_mine_count) type i.

*   нарисовать ячейку
    methods show_cell.

  private section.

    class-data:
      v_random_seed type i.

    data:
      v_x type i,
      v_y type i,
      v_cell_type type TCellType,
      v_is_opened type TBool,
      v_is_checked type TBool,
      v_mine_count type i.

* получить случайное число в диапазоне от 0..1
  methods get_random_value returning value(p_value) type f.

endclass.

* impl
class TCell implementation.

* конструктор
  method constructor.

    data:
      v_rnd type i,
      v_level type i.

    v_x = p_x.
    v_y = p_y.

    if not p_mine_percent between 1 and 99.
      p_mine_percent = 10.
    endif.

    v_rnd = get_random_value( ) * 10000.
    v_level = 10000 * p_mine_percent / 100.

    if v_rnd < v_level.
      v_cell_type = C_MINE.
    else.
      v_cell_type = C_EMPTY.
    endif.

    v_is_opened = FALSE.
    v_is_checked = FALSE.
  endmethod.

* получить X-координату в матрице
  method get_x.
    p_x = v_x.
  endmethod.

* получить Y-координату в матрице
  method get_y.
    p_y = v_y.
  endmethod.

* получить тип ячейки
  method get_cell_type.
    p_cell_type = v_cell_type.
  endmethod.

* открыть ячейку
  method open.
    v_is_opened = TRUE.
  endmethod.

* проверить, открыта ли ячейка
  method is_opened.
    p_is_opened = v_is_opened.
  endmethod.

* отметить ячейку
  method check_on.
    v_is_checked = TRUE.
  endmethod.

* снять отметку с ячейки
  method check_off.
    v_is_checked = FALSE.
  endmethod.

* проверить, отмечена ли ячейка
  method is_checked.
    p_is_checked = v_is_checked.
  endmethod.

* указать количество мин вокруг
  method set_mine_count.
    v_mine_count = p_mine_count.
  endmethod.

* получить количество мин вокруг
  method get_mine_count.
    p_mine_count = v_mine_count.
  endmethod.

* нарисовать ячейку
  method show_cell.
    data:
      v_icon like icon_oo_object,
      v_cnt(2) type c.

    if v_is_checked = TRUE.
      v_icon = icon_defect.

    elseif v_is_opened = FALSE.
      v_icon = icon_oo_object.

    elseif v_cell_type = C_MINE.
      v_icon = icon_cancel.

    elseif v_mine_count <> 0.
      v_cnt = v_mine_count.

      format hotspot on.
      write: v_cnt, ' '.
      format hotspot off.

      return.

    elseif v_cell_type = C_EMPTY.
      v_icon = icon_oo_class.

    else.
      return.
    endif.

    format hotspot on.
    write: v_icon as icon, ' '.
    format hotspot off.
  endmethod.

* private

* получить случайное число в диапазоне от 0..1
  method get_random_value.

    constants:
      v_s type i value 16807,
      v_m(6) type p value 2147483648.

    data:
      v_ks type string.

    if v_random_seed is initial.
      v_ks = sy-uzeit.

      shift v_ks circular.
      shift v_ks circular.
      shift v_ks circular.
      shift v_ks circular.

      v_random_seed = v_ks * v_ks mod ( v_m - 1 ).
    endif.

    v_random_seed = ( v_random_seed * v_s ) mod ( v_m - 1 ).
    p_value = v_random_seed / v_m.
  endmethod.

endclass.

*ЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖ
*
* строка ячеек
*
*ЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖ

class TRow definition.

  public section.

    methods add_cell
    importing
      p_cell type ref to TCell.

    methods get_cell
    importing
      p_index type i
    returning value(p_cell) type ref to TCell.

    methods get_count
    returning value(p_count) type i.

  private section.

    data:
      v_row type table of ref to TCell.

endclass.

class TRow implementation.

  method add_cell.
    append p_cell to v_row.
  endmethod.

  method get_cell.
    read table v_row index p_index into p_cell.
  endmethod.

  method get_count.
    p_count = lines( v_row ).
  endmethod.

endclass.

*ЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖ
*
* зона
*
*ЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖ

* itfc
class TZone definition.

  public section.

    types:
      TCellOffset type i.

    constants:
      C_LEFT type TCellOffset value -1,
      C_RIGHT type TCellOffset value 1,
      C_TOP type TCellOffset value -1,
      C_BOTTOM type TCellOffset value 1.

*   конструктор
    methods constructor
    importing
      p_x_size type i
      p_y_size type i
      p_mine_percent type i.

*   матрица
    methods show_matrix.

*   получить ячейку по координатам курсора
    methods get_cell_by_cursor
    importing
      value(p_cucol) like sy-cucol
      value(p_curow) like sy-curow
    returning value(p_cell) type ref to TCell.

*   открыть ячейку
    methods open_cell
    importing
      p_cell type ref to TCell.

*   игра остановлена
    methods is_game_overed returning value(p_is_game_overed) type TBool.

  private section.

    types:
      TStack type table of ref to TCell.

    data:
      v_x_size type i,
      v_y_size type i,
      v_mine_percent type i,
      v_matrix type table of ref to TRow,
      v_stack type TStack,
      v_is_game_over type TBool,
      v_is_explosived type TBool.

*   построить матрицу
    methods generate_matrix.

*   получить по координатам
    methods get_cell
    importing
      p_x type i
      p_y type i
    returning value(p_cell) type ref to TCell.

*   получить соседнюю ячейку
    methods get_sibling_cell
    importing
      p_cell type ref to TCell
      p_offset_x type TCellOffset optional
      p_offset_y type TCellOffset optional
    returning value(p_sibling_cell) type ref to TCell.

*   проверить, есть ли мина
    methods is_mine
    importing
      p_cell type ref to TCell
      p_offset_x type TCellOffset optional
      p_offset_y type TCellOffset optional
    returning value(p_is_mine) type TBool.

*   получить количество мин вокруг указанной ячейки
    methods get_near_mine_count
    importing
      p_cell type ref to TCell
    returning value(p_mine_count) type i.

*   проанализировать соседнюю ячейку
    methods analyze_sibling_cell
    importing
      p_cell type ref to TCell
      p_offset_x type TCellOffset optional
      p_offset_y type TCellOffset optional.

endclass.

* impl
class TZone implementation.

* public

  method constructor.
    v_x_size = p_x_size.
    v_y_size = p_y_size.
    v_mine_percent = p_mine_percent.

    v_is_explosived = FALSE.
    v_is_game_over = FALSE.

    call method generate_matrix.
  endmethod.

* отобразить матрицу
  method show_matrix.

    data:
      v_row type ref to TRow,
      v_cell type ref to TCell,
      v_cnt type i,
      v_save_staco like sy-staco,
      v_save_staro like sy-staro.

    v_save_staco = sy-staco.
    v_save_staro = sy-staro.

    sy-lsind = 0.
    sy-colno = 1.
    sy-linno = 1.

    v_is_game_over = TRUE.

    loop at v_matrix into v_row.
      v_cnt = v_row->get_count( ).

      do v_cnt times.
        v_cell = v_row->get_cell( sy-index ).
        v_cell->show_cell( ).

        if v_cell->is_opened( ) = TRUE and v_cell->get_cell_type( ) = TCell=>C_MINE.
          v_is_explosived = TRUE.

        elseif v_cell->is_checked( ) = FALSE and v_cell->is_opened( ) = FALSE.
          v_is_game_over = FALSE.

        endif.
      enddo.

      skip.
    endloop.

    scroll list index 1 to column v_save_staco.
    scroll list to first page index 1 line v_save_staro.

    if v_is_explosived = TRUE.
      message 'Хреновый из тебя сапер! Читай RTFM на HELP.SAP.COM' type 'I'.

    elseif v_is_game_over = TRUE.

      data:
        v_sum(6) type p,
        v_sum_str(10) type c,
        v_str_len type i,
        v_msg type string value 'Можешь смело требовать прибавки к окладу в размере'.

      v_sum = v_x_size * v_y_size * v_mine_percent.
      v_sum_str = v_sum.
      v_str_len = strlen( v_sum_str ).
      v_sum_str+v_str_len(1) = '$'.

      condense v_sum_str.
      concatenate v_msg v_sum_str into v_msg separated by space.

      message v_msg type 'I'.
    endif.
  endmethod.

* получить ячейку по координатам курсора
  method get_cell_by_cursor.
    p_cucol = ( p_cucol + 3 ) / 5.
    p_curow = ( p_curow + 1 ) / 2.

    p_cell = get_cell( p_x = p_cucol p_y = p_curow ).
  endmethod.

* алгоритм открытия ячейки
  method open_cell.

    data:
      v_cell type ref to TCell,
      v_sibling_cell type ref to TCell.

    if not p_cell is bound.
      return.

    elseif p_cell->is_opened( ) = TRUE.
      return.

    endif.

    clear v_stack[].

    p_cell->open( ).
    append p_cell to v_stack.

    do.
      if sy-index > 500.
        write: / '[censored]'.
        exit.
      endif.

      read table v_stack index 1 into v_cell.

      if sy-subrc <> 0.
        exit.
      endif.

      if v_cell->get_mine_count( ) = 0.
        analyze_sibling_cell( p_cell = v_cell p_offset_x = C_LEFT ).
        analyze_sibling_cell( p_cell = v_cell p_offset_x = C_RIGHT ).
        analyze_sibling_cell( p_cell = v_cell p_offset_y = C_TOP ).
        analyze_sibling_cell( p_cell = v_cell p_offset_y = C_BOTTOM ).
      endif.

      delete v_stack index 1.
    enddo.
  endmethod.

* игра остановлена
  method is_game_overed.
    if v_is_explosived = TRUE or v_is_game_over = TRUE.
      p_is_game_overed = TRUE.
    else.
      p_is_game_overed = FALSE.
    endif.
  endmethod.

* private

* построить матрицу
  method generate_matrix.

    data:
      v_y like sy-index,
      v_cell type ref to TCell,
      v_row type ref to TRow.

    do v_y_size times.
      create object v_row.
      v_y = sy-index.

      do v_x_size times.
        create object v_cell
        exporting
          p_x = sy-index
          p_y = v_y
          p_mine_percent = v_mine_percent.

        v_row->add_cell( v_cell ).
      enddo.

      append v_row to v_matrix.
    enddo.

    data:
      v_mine_count type i.

    do v_y_size times.
      v_y = sy-index.
      do v_x_size times.

        v_cell = get_cell( p_x = sy-index p_y = v_y ).
        v_mine_count = get_near_mine_count( v_cell ).
        v_cell->set_mine_count( v_mine_count ).

      enddo.
    enddo.
  endmethod.

* получить ячейку по строке и столбцу
  method get_cell.

    data:
      v_row type ref to TRow.

    read table v_matrix index p_y into v_row.

    if not v_row is bound.
      return.
    endif.

    p_cell = v_row->get_cell( p_x ).
  endmethod.

* получить соседнюю ячейку
  method get_sibling_cell.

    data:
      v_x type i,
      v_y type i.

    v_x = p_cell->get_x( ) + p_offset_x.
    v_y = p_cell->get_y( ) + p_offset_y.

    p_sibling_cell = get_cell( p_x = v_x p_y = v_y ).
  endmethod.

* проверить, есть ли мина
  method is_mine.

    data:
      v_cell type ref to TCell.

    v_cell = get_sibling_cell( p_cell = p_cell p_offset_x = p_offset_x p_offset_y = p_offset_y ).

    if v_cell is bound.
      if v_cell->get_cell_type( ) = TCell=>C_MINE.
        p_is_mine = TRUE.
        return.
      endif.
    endif.

    p_is_mine = FALSE.
  endmethod.

* получить количество мин вокруг указанной ячейки
  method get_near_mine_count.

    p_mine_count = p_mine_count + is_mine( p_cell = p_cell p_offset_x = C_LEFT ).
    p_mine_count = p_mine_count + is_mine( p_cell = p_cell p_offset_x = C_RIGHT ).
    p_mine_count = p_mine_count + is_mine( p_cell = p_cell p_offset_y = C_TOP ).
    p_mine_count = p_mine_count + is_mine( p_cell = p_cell p_offset_y = C_BOTTOM ).
    p_mine_count = p_mine_count + is_mine( p_cell = p_cell p_offset_x = C_LEFT p_offset_y = C_TOP ).
    p_mine_count = p_mine_count + is_mine( p_cell = p_cell p_offset_x = C_RIGHT p_offset_y = C_TOP ).
    p_mine_count = p_mine_count + is_mine( p_cell = p_cell p_offset_x = C_LEFT p_offset_y = C_BOTTOM ).
    p_mine_count = p_mine_count + is_mine( p_cell = p_cell p_offset_x = C_RIGHT p_offset_y = C_BOTTOM ).
  endmethod.

* проанализировать соседнюю ячейку
  method analyze_sibling_cell.

    data:
      v_sibling_cell type ref to TCell.

    v_sibling_cell = get_sibling_cell( p_cell = p_cell p_offset_x = p_offset_x p_offset_y = p_offset_y ).

    if not v_sibling_cell is bound.
      return.

    elseif v_sibling_cell->is_opened( ) = TRUE.
      return.

    elseif v_sibling_cell->get_cell_type( ) = TCell=>C_MINE.
      return.

    endif.

    v_sibling_cell->open( ).
    append v_sibling_cell to v_stack.
  endmethod.

endclass.

*ЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖЖ

* селекционный экран
PARAMETERS v_x_size TYPE I DEFAULT 10.
SELECTION-SCREEN SKIP.

PARAMETERS v_y_size TYPE I DEFAULT 10.
SELECTION-SCREEN SKIP.

PARAMETERS v_prcnt TYPE I DEFAULT 10.
SELECTION-SCREEN SKIP.

* после выбора
START-OF-SELECTION.

  if not v_x_size between 1 and 50.
    message 'Допустимый размер поля по оси X от 1 до 50' type 'I'.
    exit.
  elseif not v_y_size between 1 and 50.
    message 'Допустимый размер поля по оси Y от 1 до 50' type 'I'.
    exit.
  elseif not v_prcnt between 1 and 99.
    message 'Допустимый процент мин от 1 до 99' type 'I'.
    exit.
  endif.

  if v_prcnt > 100.
    exit.
  endif.

  set pf-status 'MAIN'.

  data:
    v_zone type ref to TZone.

  create object v_zone
  exporting
    p_x_size = v_x_size
    p_y_size = v_y_size
    p_mine_percent = v_prcnt.

  v_zone->show_matrix( ).

* открыть ячейку
AT LINE-SELECTION.

  data:
    v_cell type ref to TCell,
    v_cucol like sy-cucol,
    v_curow like sy-curow.

  if v_zone->is_game_overed( ) = TRUE.
    exit.
  endif.

  v_cucol = sy-staco + sy-cucol - 1.
  v_curow = sy-staro + sy-curow - 1.

  v_cell = v_zone->get_cell_by_cursor( p_cucol = v_cucol p_curow = v_curow ).

  if v_cell is bound.
    v_zone->open_cell( v_cell ).
    v_zone->show_matrix( ).
  endif.

* пометить ячейку
FORM on_ctmenu_request USING l_menu TYPE REF TO cl_ctmenu.

  data:
    v_cell type ref to TCell.

  if v_zone->is_game_overed( ) = TRUE.
    exit.
  endif.

  get cursor line v_curow offset v_cucol.
  v_cucol = v_cucol + 2.

  v_cell = v_zone->get_cell_by_cursor( p_cucol = v_cucol p_curow = v_curow ).

  if v_cell is bound.
    if v_cell->is_checked( ) = TRUE.
      v_cell->check_off( ).
    else.
      v_cell->check_on( ).
    endif.
    v_zone->show_matrix( ).
  endif.
ENDFORM.


Принять этот ответ
Вернуться к началу
 Профиль Отправить email  
 
 Заголовок сообщения: Re: Тетрис
СообщениеДобавлено: Вт, ноя 03 2009, 16:50 
Старший специалист
Старший специалист

Зарегистрирован:
Пт, ноя 12 2004, 10:44
Сообщения: 370
Откуда: Москва
тут тоже есть аналоги


Принять этот ответ
Вернуться к началу
 Профиль  
 
 Заголовок сообщения: Re: Тетрис
СообщениеДобавлено: Пн, дек 21 2009, 14:28 
Почетный гуру
Почетный гуру
Аватара пользователя

Зарегистрирован:
Чт, авг 19 2004, 17:37
Сообщения: 1962
Откуда: Москва
Пол: Мужской
Короче, чувствую, что доделать руки не дойдут, но основа работает.
Было это давно, еще на IBM PC-XT, когда в тетрис уже все наигрались, кто то притаранил тетрис для двоих. Старая игра обрела новую жизнь, ибо нет больше радости, чем напакостить ближнему. Когда один сбрасывает у себя две и больше линий, столько же линий добавляется снизу у противника.
Вот здесь лежит исходничек ZTESTIS.txt, вроде всё работает, только по оконочании игры косячки остались. Было любопытно покумекать над проблемой межпрограмного обмена данными в реальном времени. Может кто еще чего придумает?!

_________________
"For all entries" не в SAP-ах, "for all entries" в головах! :)


Принять этот ответ
Вернуться к началу
 Профиль  
 
 Заголовок сообщения: Re: Тетрис
СообщениеДобавлено: Пн, дек 21 2009, 14:31 
Специалист
Специалист
Аватара пользователя

Зарегистрирован:
Ср, окт 04 2006, 15:30
Сообщения: 248
Откуда: от туда..
Лучше SAP RPG on-line забомбите :D


Принять этот ответ
Вернуться к началу
 Профиль  
 
Показать сообщения за:  Поле сортировки  
Начать новую тему Ответить на тему  [ Сообщений: 13 ] 

Часовой пояс: UTC + 3 часа


Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей


Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете добавлять вложения

Найти:
Перейти:  
cron
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
Русская поддержка phpBB