Git Product home page Git Product logo

hexlet-codebattle / codebattle Goto Github PK

View Code? Open in Web Editor NEW
518.0 21.0 200.0 28.36 MB

Codebattle - Game for programmers, where you solved algorithmic problems with other players in real time. You can fight with other players in single player mode or join massive tournaments.

Home Page: https://codebattle.hexlet.io/

JavaScript 41.82% Elixir 49.02% HTML 5.02% Makefile 0.39% Shell 0.01% Ruby 0.06% Python 0.15% PHP 0.06% Dockerfile 0.23% Clojure 0.05% Haskell 0.10% HCL 0.29% Go 0.12% C++ 0.26% Dart 0.08% Java 0.17% Kotlin 0.10% C# 0.17% SCSS 1.88% Slim 0.02%
phoenix elixir reactjs javascript docker hacktoberfest learn-to-code

codebattle's Introduction

Codebattle

Actions Status codecov Maintainability codebeat badge Hits

Codebattle - is an open source game being developed by the Hexlet community. The current version of the application is available at codebattle.hexlet.io. We also have chrome extension. Which allow to subscribe on last game updates.

This project exists thanks to all the people who contribute. [Contribute].

Alt

Requirements

  • Mac / Linux
  • docker

Install

$ git clone [email protected]:hexlet-codebattle/codebattle.git
$ cd codebattle
$ make setup

Start Server

$ make compose

Run Tests

$ make compose-test

Lint

$ make compose-lint

# To run specific
$ make compose-mix-format
$ make compose-mix-credo
$ make compose-lint-js-fix

Useful

$ mix upload_langs

$ mix dockers.push # all
$ mix dockers.push elixir

$ mix dockers.build # all
$ mix dockers.build elixir

$ mix dockers.pull # all
$ mix dockers.pull elixir

$ mix issues.upload # Upsert issues by name in db

#If you use docker in dev env, run commands in make compose-bash

Profile js bundle

To build stat.json and see details in browser run:

yarn profile:build
yarn profile:visualize

Support

Troubleshooting

  • Install and run docker

Make sure you have installed docker for your OS.

https://docs.docker.com/install/

Make sure your docker daemon is running. You can run it manually by typing:

sudo dockerd

or you can add it to startup by typing:

sudo systemctl enable docker

Close and open your terminal if docker daemon didn't start immediately.

  • Manage Docker as a non-root user

https://docs.docker.com/install/linux/linux-postinstall/

Create the docker group.

sudo groupadd docker

Add your user to the docker group.

sudo usermod -aG docker $USER

Star History

Star History Chart


Hexlet Ltd. logo

This repository is created and maintained by the team and the community of Hexlet, an educational project. Read more about Hexlet.

See most active contributors on hexlet-friends.

codebattle's People

Contributors

abbath avatar ayshvab avatar dependabot[bot] avatar disheg avatar guryanov-maksim avatar igor-i avatar imamatory avatar jougene avatar kjubybot avatar krivtsov avatar lazycoder9 avatar mimikria96 avatar mityadementiy avatar nunsez avatar peresvets avatar plugin73 avatar possesion avatar redbrother avatar rexemtoxa avatar skhrv avatar solar05 avatar thepry avatar ushachev avatar v1valasvegan avatar vicimpa avatar vladimirafanasievfs avatar voitd avatar vtm9 avatar yoffic avatar zipofar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

codebattle's Issues

Подключение спектаторов к игровому процессу

Пользователь авторизовался, его перекинуло на предыигровую страницу #64. Далее он перешёл на страницу со списком игр #65. Она нажимает на любую игру и попадает в игровой процесс(по id игры узнаём Pid игры из памяти процесса, хранящего это в коллекции). Теперь он спектатор (зритель , spectator) и может переписываться в чате, просто быть в игровом процессе или выйти из него. Нужно реализовать данную логику.

Создать страницу со списком игр

Страница со списком игр должна быть доступна только авторизованному пользователю и содержать список игр со ссылками на них (/game/:id)

Не собирается статика при первой сборки проекта

main_page
phoenix router norouteerror at get css app css
ценарий для воспроизведения:

mkdir -p ~/hexlet/test && cd $_
git clone https://github.com/hexlet-codebattle/codebattle.git
cd codebattle

# установить Docker
docker -v && docker-compose -v
Docker version 17.06.0-ce, build 02c1d87
docker-compose version 1.15.0, build e12f3b9

# удалить все контейнеры
docker stop $(docker ps -a -q) && docker rm $(docker ps -a -q)
# почистить тома
docker volume prune
docker volume rm codebattle_postgres-data

make compose-setup
make compose

Локально тесты не прошли. и ошибка compose.

Репозиторий клонированный, без изменений

mix test

18:01:55.538 [error] GenServer #PID<0.209.0> terminating
** (KeyError) key :hostname not found in: [types: Postgrex.DefaultTypes, backoff_type: :stop, pool: DBConnection.Connection, database: "
template1", otp_app: :codebattle, repo: Codebattle.Repo, adapter: Ecto.Adapters.Postgres]
    (elixir) lib/keyword.ex:371: Keyword.fetch!/2
    (postgrex) lib/postgrex/protocol.ex:54: Postgrex.Protocol.connect/1
    (db_connection) lib/db_connection/connection.ex:134: DBConnection.Connection.connect/2
    (connection) lib/connection.ex:622: Connection.enter_connect/5
    (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3
Last message: nil

** (Mix) The database for Codebattle.Repo couldn't be created: an exception was raised:
    ** (KeyError) key :hostname not found in: [types: Postgrex.DefaultTypes, backoff_type: :stop, pool: DBConnection.Connection, databas
e: "template1", otp_app: :codebattle, repo: Codebattle.Repo, adapter: Ecto.Adapters.Postgres]
        (elixir) lib/keyword.ex:371: Keyword.fetch!/2
        (postgrex) lib/postgrex/protocol.ex:54: Postgrex.Protocol.connect/1
        (db_connection) lib/db_connection/connection.ex:134: DBConnection.Connection.connect/2
        (connection) lib/connection.ex:622: Connection.enter_connect/5
        (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3
Makefile:48: recipe for target 'test' failed
make: *** [test] Error 1

и ошибка compose-setup

docker-compose build web
Building web
ERROR: Couldn't connect to Docker daemon at http+docker://localunixsocket - is it running?

If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable.
Makefile:12: recipe for target 'compose-build' failed
make: *** [compose-build] Error 1

Добавить i18n

Все строки должны быть интернационализированы

Подключить i18n для javascript

Нужно подключить i18n, чтобы слова в js коде при загрузке страницы (например, joined channel) менялись в соотвествии с языком пользователя.

Создание схемы базы и моделей

Предлагаю коллективно продумать основные модели и их связи. Если кто-то знает бесплатный инструмент для совместного проектирования, будет круто. А так можно просто в обсуждении.

Как вариант:
модели: User, Game, Battle, Language

связи:
у battle два user-a и один game.
many_to_many user и battle
battle has_one game
many_to_many game languages

Makefile:25: recipe for target 'compose-db-create' failed

git clone https://github.com/hexlet-codebattle/codebattle.git 
cd codebattle 
make development-build-local 
make compose-setup 

...log ok...

All dependencies up to date
docker-compose run web mix compile
Starting db ... done
docker-compose run web mix ecto.create
Starting db ... done
** (Mix) The database for Codebattle.Repo couldn't be created: FATAL 28P01 (invalid_password): password authentication failed for user "postgres"

08:39:28.277 [error] GenServer #PID<0.210.0> terminating
** (Postgrex.Error) FATAL 28P01 (invalid_password): password authentication failed for user "postgres"
    (db_connection) lib/db_connection/connection.ex:148: DBConnection.Connection.connect/2
    (connection) lib/connection.ex:622: Connection.enter_connect/5
    (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3
Last message: nil
State: Postgrex.Protocol
Makefile:25: recipe for target 'compose-db-create' failed
make: *** [compose-db-create] Error 1

Предполагаю это локальная проблема, в любом случае будут полезны предположения по решению.

Реализовать чат для каждой игры

Данная задача выполяется уже после завершения задачи #63
Теперь чат создаётся при каждом создании нового игрового процесса. Чат привязан к Pid игрового процесса, и история чата хранится в памяти игрового процесса(до завершения игры). Игрок(и) и спектаторы, которые зашли в игровой процесс, могут переписываться в нём. Дублирую материалы с прошлого таска: №1, №2, №3

Подключение сервиса coveralls.io

Для подключение сервиса coveralls.io надо сделать следующие:

  1. Настроить проект https://coveralls.io/github/hexlet-codebattle/codebattle и получить COVERALLS_REPO_TOKEN
  2. Указать правильное значение COVERALLS_REPO_TOKEN в .travis.yml и использовать для запуска тестов команду test mix coveralls.travis:
@@ -1,5 +1,9 @@
 language: elixir
 
+env:
+  global:
+    - COVERALLS_REPO_TOKEN: %TODO_KEY_VALUE%
+
 elixir:
   - 1.5.0
 
@@ -16,4 +20,4 @@
 script:
   - mix credo
   - MIX_ENV=test mix ecto.migrate
-  - mix test
+  - MIX_ENV=test mix coveralls.travis
  1. произвести другие настройки интеграции, в зависимости от рабочего процесса, например иконка о проценте покрытия, ограничение на PR при снижении тестового покрытия и пр.

Пофиксить стили

Нужно убрать все кастомные стили и заменить их бутстраповскими в самих шаблонах.

Дополнить тесты игрового процесса

Нужно добавить тесты для подключения спектатора, его отключения от игры.
Тесты на игру с самим собой и подключения к самому себе.
Тест на проверку игры ("check") вторым игроком после победы первого игрока.

Реализовать общий чат

Для реализации чата в игровом процессе, первостепенно нам следует сделать его прототип на странице предъигрового процесса (страница, на которую перебрасывает после авторизации, и где кнопка start game). В данном чате могут переписываться все авторизованные пользователи, история пока не стирается и хранится в памяти процесса. Возможно, для данной задачи понадобится №1, №2, №3

Добавить инфу по применению технологий, которые планируется использовать в проекте.

На странице wiki хотелось бы видеть что для чего планируется использовать. Это снимет много вопросов тех кто ещё совсем "зеленый". Просто в скобочках справа от каждого пункта.

Надеюсь я в правильное место записал этот вопрос :) .

Исправление логики игры

  • 404 ошибка при вызове не сушествующей игры
  • если игрок окончил игру и зашёл в неё вновь как спектатор, то кнопка check остаётся для него и вызывает ошибки. Нужно её убрать.
  • после создания игры игроком, убрать подключения к ней повторно. (игра с самим собой)
  • запрет спектатору проверять (и заканчивать) игру.

Очистить код от deprecated

После перехода на elixir 1.5 появилось много deprecated по типу

warning: String.strip/1 is deprecated, use String.trim/1
  lib/mime.ex:28

Нужно это исправить. Полный список предупреждений об устаревшем коде можно увидеть, если исполнить команду make compose-setup

Дополнить процесс создания игры

Пользовать авторизовался и попал на предыигровую страницу #64, где есть кнопка Start game.
При нажатии на неё, до записи id игры в бд и создания игрового процесса, должен создаваться уникальный Pid игры(соответствующий id игры), который записывается в память отдельного специального процесса(актора, который нужен именно для хранения данных), в виде части коллекции (id игры => pid). Возможно, при реализации данной задачи потребуется данная библиотека

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.