[代码题]Simple_Virtual_World

本文介绍了一种使用C++构建虚拟世界的方法,重点在于创建人物与群体,并通过实例展示了如何建立和管理社交关系。文章还探讨了编程实践中的一些细节问题及解决方案。

题目描述:
This is a virtual world, none of us can tell whether it is real or not. But I need you now~
Now, you are require to build this world, first you should make ‘person’ and ‘group’.
In the world, we can make group to invite persons or remove someone, make friends with others or break up with someone.
The rules of the world is inside the ‘main.cpp’, and the structure of ‘world.h’ is at the bottom of ‘main.cpp’
Some notes:
for ‘person’, when build a person, an ID would be arrange to him;
the ID is from 0 - 9900, the first should be 0 and the next will be 1…;
for ‘group’, when build a group, an integer (0 or 1) is needed for initialization;
‘0’ means persons inside the group is strange to each other defaultly;
‘1’ means persons inside the group is already known to each other by default;
for ‘displayGroup()’, format is as the following:
Person_ID: ID sequence of the person’s friends (early-make friend should be print first!)
example => Person_0: 0, 2

测试文件:

#include <iostream>
#include "world.h"
using namespace std;

void test_1() {
    person mike, jack, lily, carson, sucie;
    group school(0), family_1(1), family_2(1);
    // make group (act as a society)
    school.addMember(mike);
    school.addMember(jack);
    school.addMember(lily);
    family_1.addMember(mike);
    family_1.addMember(carson);
    family_2.addMember(jack);
    family_2.addMember(lily);
    family_2.addMember(sucie);
    // construct relationship in the society
    school.makeFriend(mike, jack);
    school.makeFriend(mike, lily);
    // display the society
    cout << "\n------ SCHOOL -----\n";
    school.displayGroup();
    cout << "\n------ FAMILY_1 -----\n";
    family_1.displayGroup();
    cout << "\n------ FAMILY_2 -----\n";
    family_2.displayGroup();
}

void test_2() {
    person Baidu, Alibaba, Tencent, NTES, Kingsoft_Antivirus, _360safe;
    group BAT(1), ECommerce(1), Security(1);
    // make group (act as a society)
    BAT.addMember(Baidu);
    BAT.addMember(Alibaba);
    BAT.addMember(Tencent);
    ECommerce.addMember(Baidu);
    ECommerce.addMember(Alibaba);
    ECommerce.addMember(Tencent);
    ECommerce.addMember(NTES);
    Security.addMember(Kingsoft_Antivirus);
    Security.addMember(_360safe);
    // display the society
    cout << "\n------ BAT -----\n";
    BAT.displayGroup();
    cout << "\n------ ECommerce -----\n";
    ECommerce.displayGroup();
    cout << "\n------ Security -----\n";
    Security.displayGroup();
}

void test_3() {
    person p0, p1, p2, p3, p4;
    group g0(0), g1(0), g2(1);
    // make group (act as a society)
    g0.addMember(p0);
    g0.addMember(p1);
    g0.addMember(p2);
    g1.addMember(p0);
    g1.addMember(p3);
    g2.addMember(p3);
    g2.addMember(p4);
    // construct relationship in the society
    g1.makeFriend(p0, p3);
    g2.breakRelation(p3, p4);
    g0.deleteMember(p2);
    // display the society
    cout << "\n------ G0 -----\n";
    g0.displayGroup();
    cout << "\n------ G1 -----\n";
    g1.displayGroup();
    cout << "\n------ G2 -----\n";
    g2.displayGroup();
}

void test_4() {
    person p[50];
    group g0(0), g1(1);
    int p_count;
    cin >> p_count;
    // make group (act as a society)
    for (int i = 0; i < p_count/2; i++)
        g0.addMember(p[i]);
    for (int i = p_count/2; i < p_count; i++)
        g1.addMember(p[i]);
    // construct relationship in the society
    for (int i = 0; i < p_count/5; i += 2)
        g0.makeFriend(p[i], p[i+1]);
    for (int i = p_count/2; i < p_count*3/4-1; i += 2)
        g1.breakRelation(p[i], p[i+1]);
    for (int i = p_count/4; i < p_count/2; i++)
        g0.deleteMember(p[i]);
    for (int i = p_count*3/4; i < p_count; i++)
        g1.deleteMember(p[i]);
    // display the society
    cout << "\n------ G0 -----\n";
    g0.displayGroup();
    cout << "\n------ G1 -----\n";
    g1.displayGroup();
}

int main() {
    int test_id;
    cin >> test_id;
    switch (test_id) {
        case 1:
        test_1();
        break;
        case 2:
        test_2();
        break;
        case 3:
        test_3();
        break;
        case 4:
        test_4();
        break;
        default:
        cout << "wrong input\n";
    }
    return 0;
}

Virtual World1这道题貌似有三种方法,一种是句柄类,一种是用两个数组,一种是用STL里面的链表。
下面记录在写的过程中发现的一些知识点的漏洞:
发现如果函数参数仅仅这样写bool addMember(person &p)是会因为引用而不符合google style的,必须在person前面加一个const才能过,可是加了const又会导致更改不了变量p的内容,如果遇到需要更改的情况,该怎么处理?正确的姿势是在引用&符号左右两边都加上空格。

P.S.google style其实是一个不错的规范写代码风格的工具。

还有,如果定义person member[5],然后member[0] = p1,实际上只是复制了一个p1进了member,member[0]和p1的地址是不一样的,并不是同一个东西,所以才会出现以下的问题:
makeFriend函数和breakRelation函数,如果写成以下情况:

bool group::makeFriend(person &p1, person &p2) {
    int i;
    for (i = 0; i < p1.num_of_fri; ++i)
        if (p1.fri[i] == p2.ID) return false;
    for (i = 0; i < p2.num_of_fri; ++i)
        if (p2.fri[i] == p1.ID) return false;
    p1.fri[p1.num_of_fri++] = p2.ID;
    p2.fri[p2.num_of_fri++] = p1.ID;
    return true;
}

并不能实现member数组中的p1和p2makeFriends,只能实现传进来的p1、p2makefriend,虽然这里处理的是引用,但是这个引用的原型跟member里的并不是同一个东西,改成以下形式就可以了:

bool group::makeFriend(const person &p1, const person &p2) {
    int i, a = -1, b = -1;
    for (int i = 0; i < number; i++)
        if (member[i].ID == p1.ID) a = i;
        else if (member[i].ID == p2.ID) b = i;
    if (a == -1 || b == -1) return false;
    member[a].fri[member[a].num_of_fri++] = member[b].ID;
    member[b].fri[member[b].num_of_fri++] = member[a].ID;
    return true;
}

这样子直接在member中跟p1 p2一样的person上面操作,可以实现目的。

参考的解决问题的代码:

#ifndef world_h
#define world_h
#include "iostream"
using namespace std;
static int total = 0;
struct person {
    int ID;
    int fri[100];
    int num_of_fri;
    person() {
        num_of_fri = 0;
        ID = total++;
        for (int i = 0; i < 100; ++i)
            fri[i] = -1;
    }
};

class group {
 public:
    explicit group(bool b);
    ~group();
    void displayGroup();
    bool addMember(const person &p);
    bool deleteMember(const person &p);
    bool makeFriend(const person &p1, const person &p2);
    bool breakRelation(const person &p1, const person &p2);
 private:
    bool relation;
    int number;
    person member[100];
};
#endif /* world_h */
group::group(bool b) {
    relation = b;
    number = 0;
    for (int i = 0; i < 100; i++)
        member[i];
}
group::~group() {}
bool group::addMember(const person &p) {
    if (number > 100)
        return false;
    member[number] = p;
    if (relation == 1) {
        for (int i = 0; i < number; ++i)
            member[number].fri[i + member[number].num_of_fri] = member[i].ID;
        member[number].num_of_fri += number;
        for (int j = 0; j < number; ++j)
            member[j].fri[member[j].num_of_fri++] = member[number].ID;
    }
    number++;
    return true;
}
bool group::deleteMember(const person &p) {
    if (number < 1) return false;
    for (int i = 0; i < number; i++) {
        if (member[i].ID == p.ID) {
            for (int j = i; j < number - 1; ++j)
                member[j] = member[j + 1];
            number--;
            return true;
        }
    }
    return false;
}
bool group::makeFriend(const person &p1, const person &p2) {
    int i, a = -1, b = -1;
    for (int i = 0; i < number; i++)
        if (member[i].ID == p1.ID) a = i;
        else if (member[i].ID == p2.ID) b = i;
    if (a == -1 || b == -1) return false;
    member[a].fri[member[a].num_of_fri++] = member[b].ID;
    member[b].fri[member[b].num_of_fri++] = member[a].ID;
    return true;
}
bool group::breakRelation(const person &p1, const person &p2) {
    int i, j, a, b;
    for (i = 0; i < number; i++)
        if (member[i].ID == p1.ID) a = i;
        else if (member[i].ID == p2.ID) b = i;
    for (i = 0; i < member[a].num_of_fri; ++i)
        if (member[a].fri[i] == member[b].ID) {
            for (j = i; j < member[a].num_of_fri - 1; ++j)
                member[a].fri[j] = member[a].fri[j + 1];
            member[a].num_of_fri--;
        }
    for (i = 0; i < member[b].num_of_fri; ++i)
        if (member[b].fri[i] == member[a].ID) {
            for (j = i; j < member[b].num_of_fri - 1; ++j)
                member[b].fri[j] = member[b].fri[j + 1];
            member[b].num_of_fri--;
        }
    return true;
}
void group::displayGroup() {
    for (int i = 0; i < number; ++i) {
        cout << "Person_" << member[i].ID << ": ";
        for (int j = 0; j < member[i].num_of_fri - 1; ++j)
            cout << member[i].fri[j] << ", ";
        if (member[i].num_of_fri != 0)
            cout << member[i].fri[member[i].num_of_fri - 1] << endl;
        else
            cout << "null\n";
    }
}
我这个代码如何实现分页加载#include "aem_world_clock.h" #include "aem_log.h" #include "aem_zoom_list.h" #define WORLD_CLOCK_TIMER 1000 typedef struct { lv_obj_t *bg; lv_obj_t *page; lv_obj_t *item[20]; lv_timer_t *task; uint8_t number; } aem_world_t_clock_t; static aem_world_t_clock_t *s_world_clock = NULL; const uint8_t no_ala_world_title_pos = 40; const uint8_t no_label_world_y = 255; const uint8_t no_ala_world_str = 19; const uint8_t no_world_y = 100; void world_clock_refresh_ui(lv_timer_t *t) { for (int i = 0; i < s_world_clock->number; i++) { if (s_world_clock->item[i]) { lv_aem_world_clock_updata_time(s_world_clock->item[i], i); } } } static void no_data_world_clock_create(void) { if (s_world_clock == NULL) return; if (s_world_clock->task) { lv_timer_del(s_world_clock->task); s_world_clock->task = NULL; } lv_obj_t *icon = simple_img_create(s_world_clock->bg); if (icon) { simple_img_set_src(icon, &IMG_SCENE_WORLD_CLOCK_PIC_WORLD_CLOCK_BG); lv_obj_align(icon, LV_ALIGN_TOP_MID, 0, AEM_SIZE_VER_FACTOR_466(no_world_y)); } lv_obj_t *label = text_canvas_create(s_world_clock->bg); if (label) { lv_obj_set_width(label, AEM_SIZE_VER_FACTOR_466(400)); lv_obj_set_style_text_font(label, aem_font_sub(), LV_PART_MAIN); lv_obj_set_style_text_align(label, LV_TEXT_ALIGN_CENTER, LV_PART_MAIN); lv_obj_set_style_text_color(label, lv_palette_main(LV_PALETTE_GREY), LV_PART_MAIN); lv_obj_set_style_text_opa(label, LV_OPA_100, LV_PART_MAIN); text_canvas_set_text(label, res_manager_get_string_from_id(ID_KEY_WORLD_CLOCK_REMIND)); lv_obj_align(label, LV_ALIGN_TOP_MID, 0, AEM_SIZE_VER_FACTOR_466(no_label_world_y)); } } static void yes_data_world_clock_create(void) { if (s_world_clock == NULL || s_world_clock->bg == NULL) return; if (s_world_clock->page == NULL) { s_world_clock->page = aem_zoom_list_create(s_world_clock->bg); lv_obj_set_style_pad_row(s_world_clock->page, 10, LV_PART_MAIN); lv_obj_set_style_pad_bottom(s_world_clock->page, AEM_PUB_WIDGET_ITEM_MIN_H, LV_PART_MAIN); aem_title_create(s_world_clock->page, false, res_manager_get_string_from_id(ID_KEY_APP_WORLD_CLOCK)); } const char *am_pm[2] = {res_manager_get_string_from_id(ID_KEY_ALARM_AM), res_manager_get_string_from_id(ID_KEY_ALARM_PM)}; s_world_clock->number = aem_get_world_clock_cnt(); aem_world_time_t *world_data = share_get_world_time(); if (world_data == NULL) { return; } if (world_data) { for (int i = 0; i < s_world_clock->number; i++) { s_world_clock->item[i] = lv_aem_world_clock_item_create(s_world_clock->page, NULL, "H", am_pm); lv_aem_world_clock_set_city(s_world_clock->item[i], world_data, i); } } if (s_world_clock->task) { lv_timer_resume(s_world_clock->task); } else { s_world_clock->task = lv_timer_create(world_clock_refresh_ui, WORLD_CLOCK_TIMER, NULL); } } static void create_ui(void) { if (s_world_clock == NULL) return; if (NULL != s_world_clock->bg) { lv_obj_clean(s_world_clock->bg); s_world_clock->page = NULL; if (aem_get_world_clock_cnt()) { yes_data_world_clock_create(); } else { no_data_world_clock_create(); } } } static void aem_world_bg_create(void) { if (!s_world_clock) { s_world_clock = (aem_world_t_clock_t *)lv_mem_alloc(sizeof(aem_world_t_clock_t)); } if (!s_world_clock) return; lv_memset(s_world_clock, 0x00, sizeof(aem_world_t_clock_t)); if (s_world_clock && s_world_clock->bg == NULL) { s_world_clock->bg = aem_bg_create(lv_scr_act(), DEF_UI_WIDTH, DEF_UI_HEIGHT, lv_color_black()); lv_obj_center(s_world_clock->bg); } } static void on_create(void) { #ifdef CONFIG_SIMULATOR share_init_world_time(); #endif aem_world_bg_create(); } static void on_resume(void) { create_ui(); } static void on_suspend(void) { if (s_world_clock && s_world_clock->task) { lv_timer_pause(s_world_clock->task); } } static void on_close(void) { if (s_world_clock) { if (s_world_clock->task) { lv_timer_del(s_world_clock->task); s_world_clock->task = NULL; } if (s_world_clock->bg) { lv_obj_del(s_world_clock->bg); s_world_clock->bg = NULL; } lv_mem_free(s_world_clock); s_world_clock = NULL; } } static void on_ui_refresh(aem_msg_t *msg) { if (msg == NULL || s_world_clock == NULL) { return; } AEM_LOG_I("WORLD_MSG=%d\n", msg->sub_type); if (msg->sub_type == UI_WORLD_CLOCK_REFRESH || msg->sub_type == UI_RESUME_REFRESH) { create_ui(); } } static int32_t keypad_evt_handler(aem_key_evt_info_t *evt_info) { if (NULL != s_world_clock && NULL != s_world_clock->page) { aem_zoom_list_keypad_handler(s_world_clock->page, evt_info); } return 0; } static int32_t ui_evt_handler(aem_msg_t *msg) { if (msg == NULL) return 0; if (msg->sub_type == UI_SET_LANGUAGE_EVT) { create_ui(); } return 0; } static const aem_sys_evt_ops_t ops = { .key_evt_func = keypad_evt_handler, .ui_evt_func = ui_evt_handler, }; void aem_world_clock_app_create() { aem_app_launch(AEM_APP_ID_WORLD_CLOCK, AEM_APP_WORLD_CLOCK, on_create, on_resume, on_suspend, on_close, on_ui_refresh, &ops); } AEM_APP_DEFINE(AEM_APP_ID_WORLD_CLOCK, AEM_DEFAULT_APP, ID_KEY_APP_WORLD_CLOCK, IMG_SCENE_APPLIST_RES_WORLD_CLOCK_PIC_ICON, aem_world_clock_app_create);
08-06
import gym_super_mario_bros from nes_py.wrappers import JoypadSpace from gym_super_mario_bros.actions import SIMPLE_MOVEMENT # 使用 make 函数创建环境 env = gym_super_mario_bros.make( 'SuperMarioBros-1-1-v0', # 环境 ID render_mode='human', # 显示游戏窗口 apply_api_compatibility=True # 避免新旧 API 不兼容警告 ) # 包装动作空间(只保留常用动作) env = JoypadSpace(env, SIMPLE_MOVEMENT) # 运行一个简单循环 done = False state = env.reset() while not done: action = env.action_space.sample() # 随机选择动作 next_state, reward, terminated, truncated, info = env.step(action) done = terminated or truncated env.close() 代码为什么报错? OverflowError Traceback (most recent call last) Cell In[6], line 6 3 from gym_super_mario_bros.actions import SIMPLE_MOVEMENT 5 # 使用 make 函数创建环境 ----> 6 env = gym_super_mario_bros.make( 7 'SuperMarioBros-1-1-v0', # 环境 ID 8 render_mode='human', # 显示游戏窗口 9 apply_api_compatibility=True # 避免新旧 API 不兼容警告 10 ) 12 # 包装动作空间(只保留常用动作) 13 env = JoypadSpace(env, SIMPLE_MOVEMENT) File D:\10_The_Programs\4_The_Codes\00_virtual_environment\V25_11_13_RL_gymnasium_pytorch\Lib\site-packages\gym\envs\registration.py:640, in make(id, max_episode_steps, autoreset, apply_api_compatibility, disable_env_checker, **kwargs) 637 render_mode = None 639 try: --> 640 env = env_creator(**_kwargs) 641 except TypeError as e: 642 if ( 643 str(e).find("got an unexpected keyword argument 'render_mode'") >= 0 644 and apply_human_rendering 645 ): File D:\10_The_Programs\4_The_Codes\00_virtual_environment\V25_11_13_RL_gymnasium_pytorch\Lib\site-packages\gym_super_mario_bros\smb_env.py:52, in SuperMarioBrosEnv.__init__(self, rom_mode, lost_levels, target) 50 rom = rom_path(lost_levels, rom_mode) 51 # initialize the super object with the ROM path ---> 52 super(SuperMarioBrosEnv, self).__init__(rom) 53 # set the target world, stage, and area variables 54 target = decode_target(target, lost_levels) File D:\10_The_Programs\4_The_Codes\00_virtual_environment\V25_11_13_RL_gymnasium_pytorch\Lib\site-packages\nes_py\nes_env.py:126, in NESEnv.__init__(self, rom_path) 124 raise ValueError('ROM has trainer. trainer is not supported.') 125 # try to read the PRG ROM and raise a value error if it fails --> 126 _ = rom.prg_rom 127 # try to read the CHR ROM and raise a value error if it fails 128 _ = rom.chr_rom File D:\10_The_Programs\4_The_Codes\00_virtual_environment\V25_11_13_RL_gymnasium_pytorch\Lib\site-packages\nes_py\_rom.py:204, in ROM.prg_rom(self) 202 """Return the PRG ROM of the ROM file.""" 203 try: --> 204 return self.raw_data[self.prg_rom_start:self.prg_rom_stop] 205 except IndexError: 206 raise ValueError('failed to read PRG-ROM on ROM.') File D:\10_The_Programs\4_The_Codes\00_virtual_environment\V25_11_13_RL_gymnasium_pytorch\Lib\site-packages\nes_py\_rom.py:198, in ROM.prg_rom_stop(self) 195 @property 196 def prg_rom_stop(self): 197 """The exclusive stopping index of the PRG ROM.""" --> 198 return self.prg_rom_start + self.prg_rom_size * 2**10 OverflowError: Python integer 1024 out of bounds for uint8
最新发布
11-15
env=gym_super_mario_bros.make('SuperMarioBros-v0') env=JoypadSpace(env,SIMPLE_MOVEMENT) 以上代码,为什么报错? --------------------------------------------------------------------------- OverflowError Traceback (most recent call last) Cell In[6], line 1 ----> 1 env=gym_super_mario_bros.make('SuperMarioBros-v1') 2 env=JoypadSpace(env,SIMPLE_MOVEMENT) File D:\10_The_Programs\4_The_Codes\00_virtual_environment\V25_11_13_RL_gymnasium_pytorch\Lib\site-packages\gym\envs\registration.py:640, in make(id, max_episode_steps, autoreset, apply_api_compatibility, disable_env_checker, **kwargs) 637 render_mode = None 639 try: --> 640 env = env_creator(**_kwargs) 641 except TypeError as e: 642 if ( 643 str(e).find("got an unexpected keyword argument 'render_mode'") >= 0 644 and apply_human_rendering 645 ): File D:\10_The_Programs\4_The_Codes\00_virtual_environment\V25_11_13_RL_gymnasium_pytorch\Lib\site-packages\gym_super_mario_bros\smb_env.py:52, in SuperMarioBrosEnv.__init__(self, rom_mode, lost_levels, target) 50 rom = rom_path(lost_levels, rom_mode) 51 # initialize the super object with the ROM path ---> 52 super(SuperMarioBrosEnv, self).__init__(rom) 53 # set the target world, stage, and area variables 54 target = decode_target(target, lost_levels) File D:\10_The_Programs\4_The_Codes\00_virtual_environment\V25_11_13_RL_gymnasium_pytorch\Lib\site-packages\nes_py\nes_env.py:126, in NESEnv.__init__(self, rom_path) 124 raise ValueError('ROM has trainer. trainer is not supported.') 125 # try to read the PRG ROM and raise a value error if it fails --> 126 _ = rom.prg_rom 127 # try to read the CHR ROM and raise a value error if it fails 128 _ = rom.chr_rom File D:\10_The_Programs\4_The_Codes\00_virtual_environment\V25_11_13_RL_gymnasium_pytorch\Lib\site-packages\nes_py\_rom.py:204, in ROM.prg_rom(self) 202 """Return the PRG ROM of the ROM file.""" 203 try: --> 204 return self.raw_data[self.prg_rom_start:self.prg_rom_stop] 205 except IndexError: 206 raise ValueError('failed to read PRG-ROM on ROM.') File D:\10_The_Programs\4_The_Codes\00_virtual_environment\V25_11_13_RL_gymnasium_pytorch\Lib\site-packages\nes_py\_rom.py:198, in ROM.prg_rom_stop(self) 195 @property 196 def prg_rom_stop(self): 197 """The exclusive stopping index of the PRG ROM.""" --> 198 return self.prg_rom_start + self.prg_rom_size * 2**10 OverflowError: Python integer 1024 out of bounds for uint8
11-14
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值