Как сделать игру на c rpg

от admin

Русские Блоги

C # консольная RPG игра, объектно-ориентированная практика

Введение

Это консольное приложение на C #, написанное Ся Лай Ву Ши, в этой RPG-игре есть множество атрибутов персонажей на выбор: навыки, магазины, богатые боевые системы и функции обновления. Друзья, которые изучают C #, могут взглянуть, это очень полезно для объектно-ориентированного. Инкапсуляция наследования и полиморфизм используются.

Снимок экрана примера проекта

Исходный код некоторых проектов

Исходный код проекта и адрес загрузки исполняемой программы

C # проект обмена

Если вы хотите получить исходный код проекта бесплатно, если у вас возникли проблемы с обучением, вы можете добавить группу пингвинов: 787981076. Я объясню тебе

Интеллектуальная рекомендация

Реализация JavaScript Hashtable

причина Недавно я смотрю на «Структуру данных и алгоритм — JavaScript», затем перейдите в NPMJS.ORG для поиска, я хочу найти подходящую ссылку на библиотеку и записывать его, я могу исполь.

MySQL общие операции

jdbc Транзакция: транзакция, truncate SQL заявление Transaction 100 000 хранимая процедура mysql msyql> -определить новый терминатор,Пробелов нет mysql>delimiter // mysql> -создание хранимой .

Используйте Ansible для установки и развертывания TiDB

жизненный опыт TiDB — это распределенная база данных. Настраивать и устанавливать службы на нескольких узлах по отдельности довольно сложно. Чтобы упростить работу и облегчить управление, рекомендуетс.

Последняя версия в 2019 году: использование nvm под Windows для переключения между несколькими версиями Node.js.

С использованием различных интерфейсных сред вы можете переключаться между разными версиями в любое время для разработки. Например, развитие 2018 года основано наNode.js 7x версия разработана. Тебе эт.

Шаблон проектирования — Создать тип — Заводской шаблон

Заводская модель фабрикиPattern Решать проблему: Решен вопрос, какой интерфейс использовать принципСоздайте интерфейс объекта, класс фабрики которого реализуется его подклассом, чтобы процесс создания.

Name already in use

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A fairly big lab we (ansjob@kth.se and marcular@kth.se) made for the course cprog12 to create a C++ role playing game using classic text-commands. The engine is there and very extensible.

Some key features are:

  • Fully customizable map (read from the file univ.xml)
  • Fight system with accuracy and ranges for each weapon (making fights interesting)
  • Possibility to alias commands
  • Consumable items like shield boosters

The setting of the game is space. You have a small space ship and travel between solar systems in the galaxy. When you encounter other characters you can talk to them, fight them, and engage in trade with some. The main plot is that you should try to find and kill the evil boss; «Charlie Mancrunch» because he has kidnapped the mayor of your home town.

This was developed on Ubuntu Linux, but most resonably patched unix-like systems should run it just fine. We use lots of C++11 features, so an up-to-date compiler is a must.

Third party libraries

We make use of boost’s property tree and regular expressions, so a recent version of boost is also necessary.

When these requirements are met, compiling is simply done by using cmake:

About

A small lab we made for the course cprog12 to create a C++ role playing game using classic text-commands. The engine is there and very extensible.

C++ text-based RPG

I have made this small text-based RPG in C++ which is based around one quest. I did this to practice what I have learnt so far. How could I improve it? Be as picky as you’d like.

Jamal's user avatar

3 Answers 3

Don’t do using namespace std in global scope, instead use it inside the functions or even better only on the things you are using:

In your main, you have exit(0) , instead you should do a return statement.

You don’t have a default case in your switch statements, so if a user enters the wrong number nothing happens and the program ends without notice. It is better to have some kind of error handling. You should also do a function that shows a number of options and lets the user enter a value that is returned if correct, that way you save some typing.

Your program has the structure of a C program, you should use classes to encapsulate functionality. Identify the objects in the story and create appropriate classes.

e.g. Aragorn, Thief, Player have some common traits

Calling external programs like that is not a good thing, it opens up a security hole in your application instead use std::getline or similar.

You forgot to initialize some variables e.g.

Always make it a habit to initialize variables when you declare them.

Don’t call main() . It makes the program flow difficult to follow, instead have a loop in main() if you want to allow restart of the game.

AndersK's user avatar

If you have C++11, use nullptr instead of NULL .

In general though, you want to avoid using rand() and instead take advantage of the improved random facilities from <random> . A much better generator is std::mt19937 . And instead of rand() % N + M , which gives non-uniform results, you can use std::uniform_int_distribution<> dist(N, M); . For a seed, instead of time(nullptr) , you can use std::random_device .

Читать:
Что такое проги для компа

Don’t use std::default_random_engine because that might use rand() . Always prefer std::mt19937 as a good default.

If you don’t have a C++11 capable compiler, use Konrad Rudolph’s suggestion:

Of course, that method is slow but it does produce a good distribution. A slightly smarter way of doing this is to find the largest multiple of N that is smaller than RAND_MAX and using that as the upper bound. After that, one can safely take the result % (N + 1) .

Required reading:

rand() Considered Harmful — Stephan T. Lavavej, Going Native 2013

If you’ve managed to ditch rand() , you can get rid of <stdlib.h> and <time.h> . Otherwise, prefer the headers added by the C++ standard, <cstdlib> and <ctime> , because <xxx.h> -style headers are deprecated. A long and comprehensive answer found in std::transform() and toupper(), no matching function by Lightness Races in Orbit explains the caveats you need to be aware of regarding these headers. Since it is unspecified whether or not C library functions like toupper appear in the global namespace when using <xxx> -style headers, you should always prefix those functions with std:: .

  • Your program is suspended until the command finishes.
  • It runs the command through a shell, which means you have to worry about making sure the string you pass is safe for the shell to evaluate.
  • If you try to run a backgrounded command with & , it ends up being a grandchild process and gets orphaned and taken in by the init process (pid 1), and you have no way of checking its status after that.
  • There’s no way to read the command’s output back into your program.

Aside from those reasons, it’s just bad user experience. Clearing the screen and requiring the user to press ENTER several times throughout the program is really annoying.

There is a lot to be improved here. Number one is that you have huge blocks of code in super methods that handle entire moves. You should split that up into smaller logical groups for ease of reading, debugging, maintenance, and additions. One example I noticed is that you have this a lot:

Maybe you should make a method to print the options:

Then, you can just call this:

This is cleaner than the other version, and is reusable, so it will shorten your code. You can also have as many arguments as you wish, so if you want three options sometime, no problem.

Another problem you have is you are using namespace std; . This is bad, because later you may define your own namespace or use a different one that has some methods named the same, which could cause problems.

Your switch statements should not look like this:

Instead, the case statements should be indented, like this:

Also, I believe you have an error here. In C++, and most other languages, once a matching case statement is reached, you continue executing all lower case statements. If case 1: is matched and searchBody(); is executed, that means riverstead(); is also executed. You should add a break; statement to the end of each case block:

I prefer if / else statements to switch statements, but switch statements are sometimes helpful.

Again, you have huge methods that should be split up into smaller blocks. I’m sure there are other things you can clean up, but this will be a good start

Консольный рогалик на С++

Я не стану показывать и рассказывать весь код (это не очень интересно) — только основные моменты.

1.Персонаж

Здесь перечисленны все параметры персонажа (здоровье, броня, опыт и т.д) интерес представляет отрисовка и направление движения (которого сейчас нет).

2.Управление

Как двигать персонажа итак ясно(x—\++, y—\++). А вот обработка клавиатуры более занимательна:

Осталось только задать «управляющие символы». Можно сделать с помощью switch’a, но я ненавижу его.

switch(. ) case .. : . ; break лучше вот так

Красота! Зацикливаем функции и бегаем по экрану! Но как-то резковато… И курсор мелькает, и буквы… Исправим!

Ух-х-х! Один процент готов!

3.Окружающий мир

Здесь делаем массивы для x, y кусочков мира и самих кусочков (char o[N]) , то же для монстров и бонусов.

Создаём функцию world(int objx[N] . objy[N] . obj[N], . objcolor[N]) по аналогии с hero() , но с параметрами и дополнительным циклом для вывода массива… для интереса рисуем только в поле зрения(vis) (if (ox[k] < vis && oy[k]. ))

Сейчас заливаем экран частичками мира посредством незамысловатого for и процедурно выдалбливаем комнаты и проходы, заодно вписываем врагов и предметы, для полной рандомности не забываем про srand(time(NULL));

4.Взаимодействие

Теперь нам нужно как-то не проходить сквозь стены и монстров, получать бонусы от предметов.

Наши любимые for и #define

5.Меню

Меню просто выводим на экран, нумеруя пункты, с помощью getkey() обрабатываем выбор игрока. Пишем статус-бар персонажа, реализуем меню прокачки, пишем предысторию, и получаем то, что я назвал «Subsoil»(«Недра»).

Заключение

Такое вот нечто. Вы можете поиграть в него, скачав, распаковав и запустив таким образом:

, или же, наконец воодушевившись, написать себе приключение по своему вкусу. Заранее предупреждаю: моя игра не из лёгких!

Похожие статьи