generated from admin/template
Compare commits
7
Commits
efb41a5d8a
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea31b89c74 | ||
|
|
d1a7f7f8e2 | ||
|
|
0eb2f34ad5 | ||
|
|
ebd04219c5 | ||
|
|
9caa8499de | ||
|
|
8bdc908e0a | ||
|
|
b46725ffbb |
@@ -17,3 +17,6 @@
|
||||
* [Лабораторная работа №2](./works/Kotlin/lab-02)
|
||||
* [Лабораторная работа №3](./works/Kotlin/lab-03)
|
||||
* [Лабораторная работа №4](./works/Kotlin/lab-04)
|
||||
* [Лабораторная работа №5](./works/Kotlin/lab-05)
|
||||
* [Лабораторная работа №6](./works/Kotlin/lab-06)
|
||||
* [Лабораторная работа №7](./works/Kotlin/lab-07)
|
||||
@@ -0,0 +1,9 @@
|
||||
# Secrets
|
||||
.env*
|
||||
|
||||
# Dependencies
|
||||
node_modules
|
||||
|
||||
# OS files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -0,0 +1,16 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PokedexApi", "PokedexApi\PokedexApi.csproj", "{342D404B-EE24-4EF6-95DF-A79BD34A11E6}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{342D404B-EE24-4EF6-95DF-A79BD34A11E6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{342D404B-EE24-4EF6-95DF-A79BD34A11E6}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{342D404B-EE24-4EF6-95DF-A79BD34A11E6}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{342D404B-EE24-4EF6-95DF-A79BD34A11E6}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.11"/>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,6 @@
|
||||
@PokedexApi_HostAddress = http://localhost:5037
|
||||
|
||||
GET {{PokedexApi_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
@@ -0,0 +1,93 @@
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.Services.AddOpenApi();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
var pokemons = new List<Pokemon>
|
||||
{
|
||||
new(1, "Pikachu", "Electric", 12),
|
||||
new(2, "Charmander", "Fire", 8),
|
||||
new(3, "Squirtle", "Water", 10)
|
||||
};
|
||||
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.MapOpenApi();
|
||||
}
|
||||
app.MapGet("/hello", () => "Привет, мир API!");
|
||||
app.MapGet("/pokemons", () => Results.Ok(pokemons));
|
||||
app.MapGet("/pokemons/{id:int}", (int id) =>
|
||||
{
|
||||
var pokemon = pokemons.FirstOrDefault(p => p.Id == id);
|
||||
|
||||
if (pokemon == null)
|
||||
{
|
||||
return Results.NotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
return Results.Ok(pokemon);
|
||||
}
|
||||
});
|
||||
app.MapPost("/pokemons", (PokemonInput input) =>
|
||||
{
|
||||
var errors = Validate(input);
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
return Results.BadRequest(new { errors });
|
||||
}
|
||||
|
||||
var newId = pokemons.Max(p => p.Id) + 1;
|
||||
var pokemon = new Pokemon(newId, input.Name, input.Type, input.Level);
|
||||
pokemons.Add(pokemon);
|
||||
{
|
||||
return Results.Created($"/pokemons/{newId}", pokemon);
|
||||
}
|
||||
});
|
||||
|
||||
app.MapPut("/pokemons/{id}", (int id, PokemonInput input) =>
|
||||
{
|
||||
var existing = pokemons.FirstOrDefault(p => p.Id == id);
|
||||
{
|
||||
return Results.NotFound();
|
||||
|
||||
}
|
||||
var errors = Validate(input);
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
return Results.BadRequest(new { errors });
|
||||
}
|
||||
|
||||
var updated = new Pokemon(id, input.Name, input.Type, input.Level);
|
||||
pokemons[pokemons.IndexOf(existing)] = updated;
|
||||
{
|
||||
return Results.Ok(updated);
|
||||
}
|
||||
});
|
||||
// DELETE /pokemons/{id} — удалить покемона по id
|
||||
app.MapDelete("/pokemons/{id}", (int id) =>
|
||||
{
|
||||
var existing = pokemons.FirstOrDefault(p => p.Id == id);
|
||||
|
||||
{
|
||||
return Results.NotFound();
|
||||
}
|
||||
pokemons.Remove(existing);
|
||||
{
|
||||
return Results.NoContent();
|
||||
}
|
||||
});
|
||||
app.Run();
|
||||
|
||||
public record Pokemon(
|
||||
int Id,
|
||||
string Name,
|
||||
string Type,
|
||||
int Level);
|
||||
public record PokemonInput(
|
||||
string Name,
|
||||
string Type,
|
||||
int Level);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "http://localhost:5037",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "https://localhost:7299;http://localhost:5037",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
opencollection: 1.0.0
|
||||
|
||||
info:
|
||||
name: Lab1 - PokeAPI
|
||||
config:
|
||||
proxy:
|
||||
inherit: true
|
||||
config:
|
||||
protocol: http
|
||||
hostname: ""
|
||||
port: ""
|
||||
auth:
|
||||
username: ""
|
||||
password: ""
|
||||
bypassProxy: ""
|
||||
bundled: false
|
||||
extensions:
|
||||
bruno:
|
||||
ignore:
|
||||
- node_modules
|
||||
- .git
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 5.4 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 10 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
+159
@@ -0,0 +1,159 @@
|
||||
=**Тема:** Оптимизация. Устранение ветвлений (branchless programming), замена деления на битовые сдвиги, анализ генерируемого кода. (В контексте архитектуры Texas Instruments TMS34010)
|
||||
|
||||
**Цель работы:** Научиться писать код, учитывающий особенности конвейера (pipeline) процессора.
|
||||
|
||||
---
|
||||
|
||||
## Часть 1. Устранение ветвлений (Branchless Programming)
|
||||
|
||||
### Теория: Стоимость условного перехода
|
||||
Процессоры выполняют инструкции конвейерным методом. При встрече с условным переходом (`if`, `while`, тернарный оператор) процессор использует механизм предсказания переходов (Branch Prediction), чтобы начать выполнять инструкции заранее.
|
||||
|
||||
Если предсказание оказывается неверным (например, в файтинге игрок неожиданно нажал блок, и логика пошла по ветке, которую процессор не предсказал), конвейер сбрасывается (pipeline stall). Это стоит десятки тактов процессора. В играх со строгим требованием в 60 кадров в секунду такие микро-фризы недопустимы.
|
||||
|
||||
### Практика: Детекция коллизий (Hitboxes)
|
||||
Классический подход к проверке
|
||||
пересечения прямоугольников (AABB) использует множественные условия `if`.
|
||||
|
||||
```c
|
||||
#include <stdint.h>
|
||||
|
||||
typedef struct { int32_t x, y, w, h; } Hitbox;
|
||||
|
||||
// ПЛОХО: Множественные условные переходы. Высокий риск ошибки предсказания.
|
||||
int collide_if(Hitbox a, Hitbox b) {
|
||||
if (a.x + a.w <= b.x) return 0;
|
||||
if (a.x >= b.x + b.w) return 0;
|
||||
if (a.y + a.h <= b.y) return 0;
|
||||
if (a.y >= b.y + b.h) return 0;
|
||||
return 1;
|
||||
}
|
||||
```
|
||||
|
||||
### Оптимальное решение: Битовая логика и принудительное вычисление
|
||||
Попытка вручную реализовать проверку через арифметический сдвиг (`>> 31`) для получения маски знака часто приводит к логическим ошибкам на границах (например, при равенстве координат разность равна 0, что не является отрицательным числом, и маска не срабатывает так, как ожидается для условия `<=`).
|
||||
|
||||
Современный и надежный способ заставить компилятор сгенерировать branchless-код — использовать побитовый оператор `&` вместо логического `&&`. Оператор `&&` подразумевает ленивое вычисление (short-circuit evaluation), что вынуждает компилятор генерировать переходы. Оператор `&` гарантирует вычисление всех операндов, что позволяет компилятору заменить условия на инструкции установки флага (`setcc`) или условного перемещения (`cmov`).
|
||||
|
||||
```c
|
||||
// ОТЛИЧНО: Компилятор гарантированно сгенерирует branchless-код
|
||||
int collide_branchless(Hitbox a, Hitbox b) {
|
||||
return (a.x + a.w > b.x) &
|
||||
(a.x < b.x + b.w) &
|
||||
(a.y + a.h > b.y) &
|
||||
(a.y < b.y + b.h);
|
||||
}
|
||||
```
|
||||
|
||||
**Задание в Godbolt:**
|
||||
1. Вставьте обе функции. Выберите компилятор `x86-64 gcc` или `clang`, флаг оптимизации `-O2` или `-O3`.
|
||||
2. Проанализируйте вывод. В `collide_if` вы увидите инструкции сравнения (`cmp`) и условных переходов (`jle`, `jge`). В `collide_branchless` вы увидите последовательность инструкций `cmp`, за которыми следуют `setg` / `setl` (установка байта по флагу) и побитовое `and`, либо использование `cmov`. Условных переходов (`jmp`) в теле функции не будет.
|
||||
|
||||
---
|
||||
|
||||
## Часть 2. Замена деления на битовые сдвиги
|
||||
|
||||
### Теория: Аппаратная стоимость деления
|
||||
|
||||
|
||||
На архитектуре TMS34010 (и большинстве процессоров того времени) операция целочисленного деления (`div` / `idiv`) выполнялась аппаратно долго, занимая от 10 до 40 тактов. Битовый сдвиг выполнялся за 1 такт.
|
||||
|
||||
В Mortal Kombat 3 была введена механика бега. Для создания эффекта параллакса фон должен был двигаться медленнее персонажа, например, в 4 раза.
|
||||
|
||||
### Практика: Сдвиг вместо деления
|
||||
Сдвиг двоичного числа вправо на $N$ позиций эквивалентен целочисленному делению на $2^N$.
|
||||
|
||||
```c
|
||||
#include <stdint.h>
|
||||
|
||||
// ПЛОХО: Медленное аппаратное деление
|
||||
int32_t bg_scroll_slow(int32_t player_x) {
|
||||
return player_x / 4;
|
||||
}
|
||||
|
||||
// ОТЛИЧНО: Мгновенный битовый сдвиг (1 такт)
|
||||
int32_t bg_scroll_fast(int32_t player_x) {
|
||||
return player_x >> 2;
|
||||
}
|
||||
```
|
||||
|
||||
### Ловушка: Знаковые числа и округление
|
||||
В языке C целочисленное деление всегда округляет результат в сторону нуля. Арифметический сдвиг вправо (`sar`) всегда округляет в сторону минус бесконечности.
|
||||
|
||||
Проверим на значении `-5`:
|
||||
* `-5 / 4` в C должно дать `-1`.
|
||||
* `-5` в дополнительном коде: `...11111011`.
|
||||
* Сдвигаем вправо на 2 (`>> 2`): `...11111110`, что равно `-2`. Возникает ошибка.
|
||||
|
||||
**Решение компилятора:**
|
||||
Чтобы эмулировать поведение C при делении отрицательных чисел с помощью сдвигов, компилятор добавляет поправку (bias), равную $(2^N - 1)$, но только если число отрицательное.
|
||||
|
||||
**Анализ ассемблерного кода (GCC `-O2`):**
|
||||
```asm
|
||||
div_signed:
|
||||
mov eax, edi ; eax = x (копируем аргумент)
|
||||
sar eax, 31 ; Арифметический сдвиг: получаем 0xFFFFFFFF, если x < 0, иначе 0
|
||||
shr eax, 30 ; Логический сдвиг: превращает 0xFFFFFFFF в 3 (0x00000003), а 0 в 0
|
||||
add eax, edi ; Добавляем поправку к исходному числу: x + 3 (только если x < 0)
|
||||
sar eax, 2 ; Финальный арифметический сдвиг: (x + 3) >> 2
|
||||
ret
|
||||
```
|
||||
*Историческая справка:* Процессор TMS34010 был уникален тем, что поддерживал битовую адресацию (bit-addressable). Это означало, что указатель мог ссылаться на конкретный бит в памяти, а не только на байт, что делало подобные битовые манипуляции для программистов Midway естественными и высокоэффективными.
|
||||
|
||||
---
|
||||
|
||||
## Часть 3. Экономия памяти: Упаковка данных (Bit Packing)
|
||||
|
||||
### Теория: Ограничения видеопамяти
|
||||
Оцифрованные спрайты MK3 занимали значительный объем. Для экономии места в ПЗУ (ROM) палитра отдельного спрайта часто ограничивалась 16 цветами.
|
||||
16 цветов = $2^4$, то есть **4 бита на пиксель**.
|
||||
Следовательно, в один байт (8 бит) можно упаковать два пикселя.
|
||||
|
||||
### Практика: Извлечение и упаковка
|
||||
Для работы с упакованными данными нельзя использовать арифметическое деление или взятие остатка (`%`). Используются битовые маски (`&`) и сдвиги.
|
||||
|
||||
```c
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
|
||||
// Упаковка двух 4-битных значений (0-15) в один байт
|
||||
uint8_t pack_pixels(uint8_t pixel_left, uint8_t pixel_right) {
|
||||
return (pixel_left << 4) | (pixel_right & 0x0F);
|
||||
}
|
||||
|
||||
// Распаковка байта обратно в два пикселя
|
||||
void unpack_pixels(uint8_t packed, uint8_t* out_left, uint8_t* out_right) {
|
||||
*out_right = packed & 0x0F; // Маска 0x0F оставляет младшие 4 бита
|
||||
*out_left = (packed >> 4) & 0x0F; // Сдвиг старших 4 бит вниз и маскирование
|
||||
}
|
||||
```
|
||||
*Примечание:* На TMS34010 существовала специализированная инструкция `PIXBLT` (Pixel Block Transfer), которая выполняла распаковку, применение маски прозрачности и запись в видеопамять на аппаратном уровне, не отвлекая основной вычислительный конвейер.
|
||||
|
||||
---
|
||||
|
||||
## Задания для самостоятельной работы
|
||||
|
||||
Выполните следующие задания. Для каждого пункта предоставьте ссылку на Compiler Explorer (godbolt.org) с флагом `-O2` или `-O3` и краткий комментарий, указывающий на конкретную инструкцию ассемблера, доказывающую оптимальность вашего решения.
|
||||
|
||||
### Задание 1. Плавное движение: Fixed-Point арифметика
|
||||
В MK3 персонажи двигаются не строго по 1 пикселю за кадр, а, например, по 1.5 пикселя, чтобы анимация бега была плавной. Использование типов с плавающей точкой (`float`) было слишком медленным. Вместо этого применялась арифметика с фиксированной запятой (Fixed-Point): дробная часть хранилась в младших битах целого числа.
|
||||
**Задача:** Напишите функцию `int32_t get_screen_pos(int32_t fixed_point_pos)`, которая принимает координату, где младшие 16 бит отведены под дробную часть, а старшие 16 бит — под целую. Функция должна вернуть целую координату для отрисовки на экране.
|
||||
**Требование:** Использовать одну операцию. В Godbolt должна быть видна только одна инструкция сдвига (`shr` или `sar`).
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
### Задание 2. Branchless-затемнение палитры при Фаталити
|
||||
В MK3 при начале Фаталити фон мгновенно темнел, чтобы сфокусировать внимание на персонажах, при этом цвета самих бойцов не менялись. Представим, что цвет хранится в 16-битном формате RGB565 (5 бит красный, 6 бит зеленый, 5 бит синий).
|
||||
Наивное затемнение (`color >> 1`) приведет к "перетеканию" битов (bit bleeding): младший бит зеленого канала провалится в красный, исказив цвет.
|
||||
**Задача:** Напишите функцию `uint16_t darken_color(uint16_t color)`, которая уменьшает яркость каждого цветового канала ровно в 2 раза (сдвиг вправо на 1), не используя `if`, циклы, умножение или деление.
|
||||
**Подсказка:** Используйте битовые маски (`&`), чтобы изолировать каждый канал, сдвиньте каждый канал вправо на 1, и объедините их обратно через побитовое ИЛИ (`|`).
|
||||
**Требование:** В Godbolt вы должны увидеть только инструкции `and`, `shr` и `or`. Никаких `jmp` или `imul`.
|
||||
|
||||

|
||||
|
||||
### Задание 3. Сжатие данных комбо (Bit Packing)
|
||||
Необходимо сохранить историю последних 8 ударов игрока в минимально возможном объеме памяти. Сила каждого удара кодируется числом от 0 до 15 (4 бита).
|
||||
**Задача:** Напишите функцию `uint32_t pack_hits(const uint8_t hits[8])`, которая упаковывает массив из 8 чисел в одно 32-битное целое `uint32_t`.
|
||||
**Требование:** Напишите цикл `for`. В Godbolt с флагом `-O3` найдите доказательство того, что компилятор применил развертку цикла (Loop Unrolling). Вы должны увидеть прямую последовательность инструкций сдвига влево (`shl`) и побитового ИЛИ (`or`), без инструкций организации цикла (таких как обратный `jmp`, `cmp` счетчика или `dec`).
|
||||
@@ -3,16 +3,15 @@
|
||||
* **Студент:** [ФИО]
|
||||
* **Вариант / Карточка:** [Например: #025 Pikachu]
|
||||
|
||||
|
||||
```
|
||||
string pokemonName = "Чармандер";
|
||||
string elementType = "Огонь";
|
||||
int level = 1;
|
||||
int hp = 95;
|
||||
|
||||
Console.WriteLine($"=== БАЗА ДАННЫХ ПОКЕМОНОВ === \nПокемон: {pokemonName}\nСтихия: {elementType}\nУровень: {level} | HP:{hp}");
|
||||
```
|
||||
|
||||
//task 2
|
||||
//zad2
|
||||
string trainerName = Console.ReadLine();
|
||||
string pokemonName = Console.ReadLine();
|
||||
string elementType = Console.ReadLine();
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "lol", "lol\lol.csproj", "{8A527AAD-A846-404D-8FD5-3AD6BAFF66A9}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{8A527AAD-A846-404D-8FD5-3AD6BAFF66A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{8A527AAD-A846-404D-8FD5-3AD6BAFF66A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{8A527AAD-A846-404D-8FD5-3AD6BAFF66A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{8A527AAD-A846-404D-8FD5-3AD6BAFF66A9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,62 @@
|
||||
using System;
|
||||
namespace ConsoleApp1
|
||||
{
|
||||
public class Pokemon: Pokemons
|
||||
{
|
||||
protected static string name;
|
||||
protected static int level;
|
||||
protected int hp;
|
||||
|
||||
public string Name
|
||||
{
|
||||
get => name;
|
||||
set => name = string.IsNullOrWhiteSpace(value) ? "Я хуй знает что за покемон!" : value;
|
||||
}
|
||||
|
||||
public int Level
|
||||
{
|
||||
get => level;
|
||||
set => level = value < 1 ? 1 : value;
|
||||
}
|
||||
|
||||
public int Hp
|
||||
{
|
||||
get => Hp;
|
||||
set => hp = value < 1 ? 1 : value;
|
||||
}
|
||||
public Pokemon(string name, int level, int hp)
|
||||
{
|
||||
Name = name;
|
||||
Level = level;
|
||||
Hp = hp;
|
||||
}
|
||||
public virtual void Attaka()
|
||||
{
|
||||
Console.WriteLine($"{Name},(Ур. {Level}:)");
|
||||
}
|
||||
}
|
||||
|
||||
public class Pokemons
|
||||
{
|
||||
public virtual void Attack()
|
||||
{
|
||||
Console.WriteLine($"{Name} атакует как-то непонятно.");
|
||||
}
|
||||
}
|
||||
|
||||
public class Pikachu : Pokemons
|
||||
{
|
||||
public override void Attack()
|
||||
{
|
||||
Console.WriteLine($"{Name} бьёт током! Пика-пика!");
|
||||
}
|
||||
}
|
||||
|
||||
public class Squirtle : Pokemons
|
||||
{
|
||||
public override void Attack()
|
||||
{
|
||||
Console.WriteLine($"{Name} стреляет водой! Сквирт-сквирт!");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,41 +1,23 @@
|
||||
int pokemonHP = 20;
|
||||
Console.WriteLine("=== ПОКЕЦЕНТР: ЛЕЧЕНИЕ ===");
|
||||
Console.WriteLine($"Здоровье до лечения: {pokemonHP} HP.");
|
||||
HealPokemon(ref pokemonHP);
|
||||
using System;
|
||||
|
||||
Console.WriteLine($"Здоровье после лечения: {pokemonHP} HP.");
|
||||
static void HealPokemon(ref int hp)
|
||||
namespace ConsoleApp1
|
||||
{
|
||||
hp += 80;
|
||||
Console.WriteLine("[Покецентр] Покемон полностью здоров! Восстановлено 80 HP.");
|
||||
}
|
||||
|
||||
Console.WriteLine("=== ИССЛЕДОВАНИЕ ЛОКАЦИИ ===");
|
||||
Console.WriteLine("Вы зашли в высокую траву...");
|
||||
SearchBushes(out string foundPokemon, out int pokemonLevel);
|
||||
Console.WriteLine($"Шорох! Из кустов появляется дикий {foundPokemon} (Уровень: {pokemonLevel})!");
|
||||
static void SearchBushes(out string foundPokemon, out int pokemonLevel)
|
||||
{
|
||||
Random random = new Random();
|
||||
foundPokemon = "Пикачу";
|
||||
pokemonLevel = random.Next(1, 16);
|
||||
}
|
||||
|
||||
Console.WriteLine("=== РЕГИСТРАЦИЯ НА ТУРНИР ===");
|
||||
|
||||
RegisterTournament(1.5, "Бульбазавр", "Чармандер");
|
||||
RegisterTournament(1.5, "Сквиртл", "Пикачу", "Псайдак", "Мяут");
|
||||
static void RegisterTournament(in double difficulty, params string[] participants)
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
|
||||
|
||||
Console.WriteLine("-----------------------------");
|
||||
Console.WriteLine($"Коэффициент стадиона: {difficulty} ");
|
||||
Console.WriteLine("Список участников: ");
|
||||
|
||||
foreach (string pokemon in participants)
|
||||
}
|
||||
class Pokemon
|
||||
{
|
||||
Console.WriteLine($"* {pokemon} ");
|
||||
protected string Name;
|
||||
protected int Level;
|
||||
protected int hp;
|
||||
}
|
||||
public string Name
|
||||
{
|
||||
|
||||
}
|
||||
Console.WriteLine("=============================");
|
||||
public int Level
|
||||
|
||||
public int hp;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "lab-06", "lab-06\lab-06.csproj", "{E72FE545-8B00-4EB4-A6B4-9C5B1940EB7F}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{E72FE545-8B00-4EB4-A6B4-9C5B1940EB7F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{E72FE545-8B00-4EB4-A6B4-9C5B1940EB7F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{E72FE545-8B00-4EB4-A6B4-9C5B1940EB7F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{E72FE545-8B00-4EB4-A6B4-9C5B1940EB7F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,61 @@
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
// Выводим главный заголовок
|
||||
Console.WriteLine("=== ПОКЕДЕКС ===");
|
||||
|
||||
// Создаем двух покемонов через new
|
||||
Pokemon pokemon1 = new Pokemon("Пикачу", 5, 100);
|
||||
pokemon1.ShowInfo(1);
|
||||
|
||||
Pokemon pokemon2 = new Pokemon("Сквиртл", 7, 90);
|
||||
pokemon2.ShowInfo(2);
|
||||
}
|
||||
}
|
||||
class Pokemon
|
||||
{
|
||||
private string name;
|
||||
private int level;
|
||||
private int hp;
|
||||
|
||||
public string Name
|
||||
{
|
||||
get { return name; }
|
||||
set { name = value; }
|
||||
}
|
||||
|
||||
public int Level
|
||||
{
|
||||
get { return level; }
|
||||
set
|
||||
{
|
||||
if (value < 1) level = 1;
|
||||
else if (value > 100) level = 100;
|
||||
else level = value;
|
||||
}
|
||||
}
|
||||
|
||||
public int HP
|
||||
{
|
||||
get { return hp; }
|
||||
set
|
||||
{
|
||||
if (value < 0) hp = 0;
|
||||
else if (value > 100) hp = 100;
|
||||
else hp = value;
|
||||
}
|
||||
}
|
||||
|
||||
public Pokemon(string name, int level, int hp)
|
||||
{
|
||||
Name = name;
|
||||
Level = level;
|
||||
HP = hp; // Добавили инициализацию HP
|
||||
}
|
||||
|
||||
public void ShowInfo(int id)
|
||||
{
|
||||
Console.WriteLine($"{id}. Имя: {Name}, Уровень: {Level}, HP: {HP}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RootNamespace>lab_06</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,16 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PokedexApp", "PokedexApp\PokedexApp.csproj", "{3A45169D-4715-4CAB-BF8D-6201F208BF24}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{3A45169D-4715-4CAB-BF8D-6201F208BF24}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{3A45169D-4715-4CAB-BF8D-6201F208BF24}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{3A45169D-4715-4CAB-BF8D-6201F208BF24}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{3A45169D-4715-4CAB-BF8D-6201F208BF24}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace PokedexApp.Models;
|
||||
|
||||
[Table("ability")]
|
||||
[Index("AbilityName", Name = "ability_ability_name_key", IsUnique = true)]
|
||||
public partial class Ability
|
||||
{
|
||||
[Key]
|
||||
[Column("ability_id")]
|
||||
public int AbilityId { get; set; }
|
||||
|
||||
[Column("ability_name")]
|
||||
[StringLength(60)]
|
||||
public string AbilityName { get; set; } = null!;
|
||||
|
||||
[Column("ability_description")]
|
||||
public string? AbilityDescription { get; set; }
|
||||
|
||||
[Column("ability_is_hidden")]
|
||||
public bool AbilityIsHidden { get; set; }
|
||||
|
||||
[InverseProperty("Ability")]
|
||||
public virtual ICollection<PokemonAbility> PokemonAbilities { get; set; } = new List<PokemonAbility>();
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace PokedexApp.Models;
|
||||
|
||||
[Table("caught_pokemon")]
|
||||
public partial class CaughtPokemon
|
||||
{
|
||||
[Key]
|
||||
[Column("caught_pokemon_id")]
|
||||
public int CaughtPokemonId { get; set; }
|
||||
|
||||
[Column("trainer_id")]
|
||||
public int TrainerId { get; set; }
|
||||
|
||||
[Column("pokemon_id")]
|
||||
public int PokemonId { get; set; }
|
||||
|
||||
[Column("caught_pokemon_nickname")]
|
||||
[StringLength(50)]
|
||||
public string? CaughtPokemonNickname { get; set; }
|
||||
|
||||
[Column("caught_pokemon_level")]
|
||||
public short CaughtPokemonLevel { get; set; }
|
||||
|
||||
[Column("caught_pokemon_gender")]
|
||||
[MaxLength(1)]
|
||||
public char? CaughtPokemonGender { get; set; }
|
||||
|
||||
[Column("caught_pokemon_is_shiny")]
|
||||
public bool CaughtPokemonIsShiny { get; set; }
|
||||
|
||||
[Column("caught_pokemon_catch_date")]
|
||||
public DateOnly CaughtPokemonCatchDate { get; set; }
|
||||
|
||||
[Column("catch_region_id")]
|
||||
public int? CatchRegionId { get; set; }
|
||||
|
||||
[ForeignKey("CatchRegionId")]
|
||||
[InverseProperty("CaughtPokemons")]
|
||||
public virtual Region? CatchRegion { get; set; }
|
||||
|
||||
[ForeignKey("PokemonId")]
|
||||
[InverseProperty("CaughtPokemons")]
|
||||
public virtual Pokemon Pokemon { get; set; } = null!;
|
||||
|
||||
[ForeignKey("TrainerId")]
|
||||
[InverseProperty("CaughtPokemons")]
|
||||
public virtual Trainer Trainer { get; set; } = null!;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace PokedexApp.Models;
|
||||
|
||||
[Table("evolution")]
|
||||
[Index("FromPokemonId", "ToPokemonId", Name = "uq_evolution_pair", IsUnique = true)]
|
||||
public partial class Evolution
|
||||
{
|
||||
[Key]
|
||||
[Column("evolution_id")]
|
||||
public int EvolutionId { get; set; }
|
||||
|
||||
[Column("from_pokemon_id")]
|
||||
public int FromPokemonId { get; set; }
|
||||
|
||||
[Column("to_pokemon_id")]
|
||||
public int ToPokemonId { get; set; }
|
||||
|
||||
[Column("evolution_trigger")]
|
||||
[StringLength(30)]
|
||||
public string EvolutionTrigger { get; set; } = null!;
|
||||
|
||||
[Column("evolution_min_level")]
|
||||
public short? EvolutionMinLevel { get; set; }
|
||||
|
||||
[Column("evolution_item_name")]
|
||||
[StringLength(50)]
|
||||
public string? EvolutionItemName { get; set; }
|
||||
|
||||
[ForeignKey("FromPokemonId")]
|
||||
[InverseProperty("EvolutionFromPokemons")]
|
||||
public virtual Pokemon FromPokemon { get; set; } = null!;
|
||||
|
||||
[ForeignKey("ToPokemonId")]
|
||||
[InverseProperty("EvolutionToPokemons")]
|
||||
public virtual Pokemon ToPokemon { get; set; } = null!;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace PokedexApp.Models;
|
||||
|
||||
[Table("move")]
|
||||
[Index("MoveName", Name = "move_move_name_key", IsUnique = true)]
|
||||
public partial class Move
|
||||
{
|
||||
[Key]
|
||||
[Column("move_id")]
|
||||
public int MoveId { get; set; }
|
||||
|
||||
[Column("move_name")]
|
||||
[StringLength(80)]
|
||||
public string MoveName { get; set; } = null!;
|
||||
|
||||
[Column("type_id")]
|
||||
public int TypeId { get; set; }
|
||||
|
||||
[Column("move_category")]
|
||||
[StringLength(10)]
|
||||
public string MoveCategory { get; set; } = null!;
|
||||
|
||||
[Column("move_power")]
|
||||
public short? MovePower { get; set; }
|
||||
|
||||
[Column("move_accuracy")]
|
||||
public short? MoveAccuracy { get; set; }
|
||||
|
||||
[Column("move_pp")]
|
||||
public short MovePp { get; set; }
|
||||
|
||||
[Column("move_description")]
|
||||
public string? MoveDescription { get; set; }
|
||||
|
||||
[InverseProperty("Move")]
|
||||
public virtual ICollection<PokemonMove> PokemonMoves { get; set; } = new List<PokemonMove>();
|
||||
|
||||
[ForeignKey("TypeId")]
|
||||
[InverseProperty("Moves")]
|
||||
public virtual Type Type { get; set; } = null!;
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace PokedexApp.Models;
|
||||
|
||||
public partial class PokedexDbContext : DbContext
|
||||
{
|
||||
public PokedexDbContext()
|
||||
{
|
||||
}
|
||||
|
||||
public PokedexDbContext(DbContextOptions<PokedexDbContext> options)
|
||||
: base(options)
|
||||
{
|
||||
}
|
||||
|
||||
public virtual DbSet<Ability> Abilities { get; set; }
|
||||
|
||||
public virtual DbSet<CaughtPokemon> CaughtPokemons { get; set; }
|
||||
|
||||
public virtual DbSet<Evolution> Evolutions { get; set; }
|
||||
|
||||
public virtual DbSet<Move> Moves { get; set; }
|
||||
|
||||
public virtual DbSet<Pokemon> Pokemons { get; set; }
|
||||
|
||||
public virtual DbSet<PokemonAbility> PokemonAbilities { get; set; }
|
||||
|
||||
public virtual DbSet<PokemonMove> PokemonMoves { get; set; }
|
||||
|
||||
public virtual DbSet<PokemonType> PokemonTypes { get; set; }
|
||||
|
||||
public virtual DbSet<Region> Regions { get; set; }
|
||||
|
||||
public virtual DbSet<Trainer> Trainers { get; set; }
|
||||
|
||||
public virtual DbSet<Type> Types { get; set; }
|
||||
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see https://go.microsoft.com/fwlink/?LinkId=723263.
|
||||
=> optionsBuilder.UseNpgsql("Host=localhost;Port=5432;Database=postgres;Username=postgres;Password=pokedex_pass;");
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<Ability>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.AbilityId).HasName("ability_pkey");
|
||||
|
||||
entity.Property(e => e.AbilityId).UseIdentityAlwaysColumn();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<CaughtPokemon>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.CaughtPokemonId).HasName("caught_pokemon_pkey");
|
||||
|
||||
entity.Property(e => e.CaughtPokemonId).UseIdentityAlwaysColumn();
|
||||
entity.Property(e => e.CaughtPokemonCatchDate).HasDefaultValueSql("CURRENT_DATE");
|
||||
|
||||
entity.HasOne(d => d.CatchRegion).WithMany(p => p.CaughtPokemons)
|
||||
.OnDelete(DeleteBehavior.SetNull)
|
||||
.HasConstraintName("caught_pokemon_catch_region_id_fkey");
|
||||
|
||||
entity.HasOne(d => d.Pokemon).WithMany(p => p.CaughtPokemons)
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.HasConstraintName("caught_pokemon_pokemon_id_fkey");
|
||||
|
||||
entity.HasOne(d => d.Trainer).WithMany(p => p.CaughtPokemons).HasConstraintName("caught_pokemon_trainer_id_fkey");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<Evolution>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.EvolutionId).HasName("evolution_pkey");
|
||||
|
||||
entity.Property(e => e.EvolutionId).UseIdentityAlwaysColumn();
|
||||
|
||||
entity.HasOne(d => d.FromPokemon).WithMany(p => p.EvolutionFromPokemons).HasConstraintName("evolution_from_pokemon_id_fkey");
|
||||
|
||||
entity.HasOne(d => d.ToPokemon).WithMany(p => p.EvolutionToPokemons).HasConstraintName("evolution_to_pokemon_id_fkey");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<Move>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.MoveId).HasName("move_pkey");
|
||||
|
||||
entity.Property(e => e.MoveId).UseIdentityAlwaysColumn();
|
||||
|
||||
entity.HasOne(d => d.Type).WithMany(p => p.Moves)
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.HasConstraintName("move_type_id_fkey");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<Pokemon>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.PokemonId).HasName("pokemon_pkey");
|
||||
|
||||
entity.Property(e => e.PokemonId).UseIdentityAlwaysColumn();
|
||||
entity.Property(e => e.PokemonCreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP");
|
||||
|
||||
entity.HasOne(d => d.Region).WithMany(p => p.Pokemons)
|
||||
.OnDelete(DeleteBehavior.SetNull)
|
||||
.HasConstraintName("pokemon_region_id_fkey");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<PokemonAbility>(entity =>
|
||||
{
|
||||
entity.HasKey(e => new { e.PokemonId, e.AbilityId }).HasName("pokemon_ability_pkey");
|
||||
|
||||
entity.HasOne(d => d.Ability).WithMany(p => p.PokemonAbilities)
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.HasConstraintName("pokemon_ability_ability_id_fkey");
|
||||
|
||||
entity.HasOne(d => d.Pokemon).WithMany(p => p.PokemonAbilities).HasConstraintName("pokemon_ability_pokemon_id_fkey");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<PokemonMove>(entity =>
|
||||
{
|
||||
entity.HasKey(e => new { e.PokemonId, e.MoveId, e.PokemonMoveLearnMethod }).HasName("pokemon_move_pkey");
|
||||
|
||||
entity.HasOne(d => d.Move).WithMany(p => p.PokemonMoves).HasConstraintName("pokemon_move_move_id_fkey");
|
||||
|
||||
entity.HasOne(d => d.Pokemon).WithMany(p => p.PokemonMoves).HasConstraintName("pokemon_move_pokemon_id_fkey");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<PokemonType>(entity =>
|
||||
{
|
||||
entity.HasKey(e => new { e.PokemonId, e.TypeId }).HasName("pokemon_type_pkey");
|
||||
|
||||
entity.HasOne(d => d.Pokemon).WithMany(p => p.PokemonTypes).HasConstraintName("pokemon_type_pokemon_id_fkey");
|
||||
|
||||
entity.HasOne(d => d.Type).WithMany(p => p.PokemonTypes)
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.HasConstraintName("pokemon_type_type_id_fkey");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<Region>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.RegionId).HasName("region_pkey");
|
||||
|
||||
entity.Property(e => e.RegionId).UseIdentityAlwaysColumn();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<Trainer>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.TrainerId).HasName("trainer_pkey");
|
||||
|
||||
entity.Property(e => e.TrainerId).UseIdentityAlwaysColumn();
|
||||
entity.Property(e => e.TrainerRegisteredAt).HasDefaultValueSql("CURRENT_TIMESTAMP");
|
||||
|
||||
entity.HasOne(d => d.HomeRegion).WithMany(p => p.Trainers)
|
||||
.OnDelete(DeleteBehavior.SetNull)
|
||||
.HasConstraintName("trainer_home_region_id_fkey");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<Type>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.TypeId).HasName("type_pkey");
|
||||
|
||||
entity.Property(e => e.TypeId).UseIdentityAlwaysColumn();
|
||||
entity.Property(e => e.TypeColorHex).IsFixedLength();
|
||||
});
|
||||
|
||||
OnModelCreatingPartial(modelBuilder);
|
||||
}
|
||||
|
||||
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace PokedexApp.Models;
|
||||
|
||||
[Table("pokemon")]
|
||||
[Index("PokemonName", Name = "pokemon_pokemon_name_key", IsUnique = true)]
|
||||
[Index("PokemonNationalDexNumber", Name = "pokemon_pokemon_national_dex_number_key", IsUnique = true)]
|
||||
public partial class Pokemon
|
||||
{
|
||||
[Key]
|
||||
[Column("pokemon_id")]
|
||||
public int PokemonId { get; set; }
|
||||
|
||||
[Column("pokemon_national_dex_number")]
|
||||
public int PokemonNationalDexNumber { get; set; }
|
||||
|
||||
[Column("pokemon_name")]
|
||||
[StringLength(50)]
|
||||
public string PokemonName { get; set; } = null!;
|
||||
|
||||
[Column("pokemon_species")]
|
||||
[StringLength(50)]
|
||||
public string? PokemonSpecies { get; set; }
|
||||
|
||||
[Column("pokemon_height")]
|
||||
[Precision(4, 2)]
|
||||
public decimal? PokemonHeight { get; set; }
|
||||
|
||||
[Column("pokemon_weight")]
|
||||
[Precision(5, 2)]
|
||||
public decimal? PokemonWeight { get; set; }
|
||||
|
||||
[Column("pokemon_base_hp")]
|
||||
public short PokemonBaseHp { get; set; }
|
||||
|
||||
[Column("pokemon_base_attack")]
|
||||
public short PokemonBaseAttack { get; set; }
|
||||
|
||||
[Column("pokemon_base_defense")]
|
||||
public short PokemonBaseDefense { get; set; }
|
||||
|
||||
[Column("pokemon_base_sp_attack")]
|
||||
public short PokemonBaseSpAttack { get; set; }
|
||||
|
||||
[Column("pokemon_base_sp_defense")]
|
||||
public short PokemonBaseSpDefense { get; set; }
|
||||
|
||||
[Column("pokemon_base_speed")]
|
||||
public short PokemonBaseSpeed { get; set; }
|
||||
|
||||
[Column("pokemon_is_legendary")]
|
||||
public bool PokemonIsLegendary { get; set; }
|
||||
|
||||
[Column("pokemon_is_mythical")]
|
||||
public bool PokemonIsMythical { get; set; }
|
||||
|
||||
[Column("region_id")]
|
||||
public int? RegionId { get; set; }
|
||||
|
||||
[Column("pokemon_description")]
|
||||
public string? PokemonDescription { get; set; }
|
||||
|
||||
[Column("pokemon_created_at")]
|
||||
public DateTime PokemonCreatedAt { get; set; }
|
||||
|
||||
[InverseProperty("Pokemon")]
|
||||
public virtual ICollection<CaughtPokemon> CaughtPokemons { get; set; } = new List<CaughtPokemon>();
|
||||
|
||||
[InverseProperty("FromPokemon")]
|
||||
public virtual ICollection<Evolution> EvolutionFromPokemons { get; set; } = new List<Evolution>();
|
||||
|
||||
[InverseProperty("ToPokemon")]
|
||||
public virtual ICollection<Evolution> EvolutionToPokemons { get; set; } = new List<Evolution>();
|
||||
|
||||
[InverseProperty("Pokemon")]
|
||||
public virtual ICollection<PokemonAbility> PokemonAbilities { get; set; } = new List<PokemonAbility>();
|
||||
|
||||
[InverseProperty("Pokemon")]
|
||||
public virtual ICollection<PokemonMove> PokemonMoves { get; set; } = new List<PokemonMove>();
|
||||
|
||||
[InverseProperty("Pokemon")]
|
||||
public virtual ICollection<PokemonType> PokemonTypes { get; set; } = new List<PokemonType>();
|
||||
|
||||
[ForeignKey("RegionId")]
|
||||
[InverseProperty("Pokemons")]
|
||||
public virtual Region? Region { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace PokedexApp.Models;
|
||||
|
||||
[PrimaryKey("PokemonId", "AbilityId")]
|
||||
[Table("pokemon_ability")]
|
||||
public partial class PokemonAbility
|
||||
{
|
||||
[Key]
|
||||
[Column("pokemon_id")]
|
||||
public int PokemonId { get; set; }
|
||||
|
||||
[Key]
|
||||
[Column("ability_id")]
|
||||
public int AbilityId { get; set; }
|
||||
|
||||
[Column("pokemon_ability_is_hidden")]
|
||||
public bool PokemonAbilityIsHidden { get; set; }
|
||||
|
||||
[Column("pokemon_ability_slot")]
|
||||
public short PokemonAbilitySlot { get; set; }
|
||||
|
||||
[ForeignKey("AbilityId")]
|
||||
[InverseProperty("PokemonAbilities")]
|
||||
public virtual Ability Ability { get; set; } = null!;
|
||||
|
||||
[ForeignKey("PokemonId")]
|
||||
[InverseProperty("PokemonAbilities")]
|
||||
public virtual Pokemon Pokemon { get; set; } = null!;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace PokedexApp.Models;
|
||||
|
||||
[PrimaryKey("PokemonId", "MoveId", "PokemonMoveLearnMethod")]
|
||||
[Table("pokemon_move")]
|
||||
public partial class PokemonMove
|
||||
{
|
||||
[Key]
|
||||
[Column("pokemon_id")]
|
||||
public int PokemonId { get; set; }
|
||||
|
||||
[Key]
|
||||
[Column("move_id")]
|
||||
public int MoveId { get; set; }
|
||||
|
||||
[Key]
|
||||
[Column("pokemon_move_learn_method")]
|
||||
[StringLength(20)]
|
||||
public string PokemonMoveLearnMethod { get; set; } = null!;
|
||||
|
||||
[Column("pokemon_move_level_learned")]
|
||||
public short? PokemonMoveLevelLearned { get; set; }
|
||||
|
||||
[ForeignKey("MoveId")]
|
||||
[InverseProperty("PokemonMoves")]
|
||||
public virtual Move Move { get; set; } = null!;
|
||||
|
||||
[ForeignKey("PokemonId")]
|
||||
[InverseProperty("PokemonMoves")]
|
||||
public virtual Pokemon Pokemon { get; set; } = null!;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace PokedexApp.Models;
|
||||
|
||||
[PrimaryKey("PokemonId", "TypeId")]
|
||||
[Table("pokemon_type")]
|
||||
[Index("PokemonId", "PokemonTypeSlot", Name = "uq_pokemon_slot", IsUnique = true)]
|
||||
public partial class PokemonType
|
||||
{
|
||||
[Key]
|
||||
[Column("pokemon_id")]
|
||||
public int PokemonId { get; set; }
|
||||
|
||||
[Key]
|
||||
[Column("type_id")]
|
||||
public int TypeId { get; set; }
|
||||
|
||||
[Column("pokemon_type_slot")]
|
||||
public short PokemonTypeSlot { get; set; }
|
||||
|
||||
[ForeignKey("PokemonId")]
|
||||
[InverseProperty("PokemonTypes")]
|
||||
public virtual Pokemon Pokemon { get; set; } = null!;
|
||||
|
||||
[ForeignKey("TypeId")]
|
||||
[InverseProperty("PokemonTypes")]
|
||||
public virtual Type Type { get; set; } = null!;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace PokedexApp.Models;
|
||||
|
||||
[Table("region")]
|
||||
[Index("RegionName", Name = "region_region_name_key", IsUnique = true)]
|
||||
public partial class Region
|
||||
{
|
||||
[Key]
|
||||
[Column("region_id")]
|
||||
public int RegionId { get; set; }
|
||||
|
||||
[Column("region_name")]
|
||||
[StringLength(50)]
|
||||
public string RegionName { get; set; } = null!;
|
||||
|
||||
[Column("region_generation")]
|
||||
public short RegionGeneration { get; set; }
|
||||
|
||||
[Column("region_description")]
|
||||
public string? RegionDescription { get; set; }
|
||||
|
||||
[InverseProperty("CatchRegion")]
|
||||
public virtual ICollection<CaughtPokemon> CaughtPokemons { get; set; } = new List<CaughtPokemon>();
|
||||
|
||||
[InverseProperty("Region")]
|
||||
public virtual ICollection<Pokemon> Pokemons { get; set; } = new List<Pokemon>();
|
||||
|
||||
[InverseProperty("HomeRegion")]
|
||||
public virtual ICollection<Trainer> Trainers { get; set; } = new List<Trainer>();
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace PokedexApp.Models;
|
||||
|
||||
[Table("trainer")]
|
||||
[Index("TrainerEmail", Name = "trainer_trainer_email_key", IsUnique = true)]
|
||||
public partial class Trainer
|
||||
{
|
||||
[Key]
|
||||
[Column("trainer_id")]
|
||||
public int TrainerId { get; set; }
|
||||
|
||||
[Column("trainer_name")]
|
||||
[StringLength(50)]
|
||||
public string TrainerName { get; set; } = null!;
|
||||
|
||||
[Column("trainer_email")]
|
||||
[StringLength(120)]
|
||||
public string? TrainerEmail { get; set; }
|
||||
|
||||
[Column("home_region_id")]
|
||||
public int? HomeRegionId { get; set; }
|
||||
|
||||
[Column("trainer_registered_at")]
|
||||
public DateTime TrainerRegisteredAt { get; set; }
|
||||
|
||||
[InverseProperty("Trainer")]
|
||||
public virtual ICollection<CaughtPokemon> CaughtPokemons { get; set; } = new List<CaughtPokemon>();
|
||||
|
||||
[ForeignKey("HomeRegionId")]
|
||||
[InverseProperty("Trainers")]
|
||||
public virtual Region? HomeRegion { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace PokedexApp.Models;
|
||||
|
||||
[Table("type")]
|
||||
[Index("TypeName", Name = "type_type_name_key", IsUnique = true)]
|
||||
public partial class Type
|
||||
{
|
||||
[Key]
|
||||
[Column("type_id")]
|
||||
public int TypeId { get; set; }
|
||||
|
||||
[Column("type_name")]
|
||||
[StringLength(30)]
|
||||
public string TypeName { get; set; } = null!;
|
||||
|
||||
[Column("type_color_hex")]
|
||||
[StringLength(7)]
|
||||
public string? TypeColorHex { get; set; }
|
||||
|
||||
[InverseProperty("Type")]
|
||||
public virtual ICollection<Move> Moves { get; set; } = new List<Move>();
|
||||
|
||||
[InverseProperty("Type")]
|
||||
public virtual ICollection<PokemonType> PokemonTypes { get; set; } = new List<PokemonType>();
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.13">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1 @@
|
||||
Console.WriteLine("Hello, World!");
|
||||
Reference in New Issue
Block a user