如何在控制台上移动x-y坐标上的点对象- c++ OOP

How to move a point object on co-ordinates x-y in console - C++ OOP

本文关键字:对象 OOP c++ x-y 控制台 移动 坐标      更新时间:2023-10-16

我正在做我的面向对象编程作业,我被要求为孩子们创造一个捕捉数字的游戏,这样他们在享受的过程中也可以学习计数。

在这里,我应该创建一个Point类和一个x-y坐标。在这里,我必须创建一个移位函数,它以P(点对象作为参数)为参数。当用户按下方向键时,此功能将移动第一个点。

问题是我对c++中箭头键(如向上,向下,向左,向右移动)的实际关键字感到困惑,就像我们在正常游戏中使用的移动物体或人一样!???

下面是我的代码!类Point.h

#ifndef POINT_H
#define POINT_H
class Point
{
public:
    Point();                                    // Default Constructor
    Point(double, double, int);                // Three argument constructor
    void initialize(double, double, int);    
    void shift(Point p);                      // Shift the first point when user press keys
    void setValue(int value);
    int getValue() const;
    void setX();
    double getX() const;
    void setY();
    double gety() const;
    void AddPointValue(Point p2);             /*This function add the TWO points value  
    void displayPoint();                     //This will use to display value of point  
    bool checkCoordinates();
    bool checkTime();                        // Check time remaining
private:
    double x;
    double y;
    int value;
};
#endif

实现文件

#include <iostream>
#include <windows.h>
#include "point.h"

using namespace std;
Point::Point()    // Default Constructor
{
x = 0;
y = 0;
value = 0;
}
Point::Point(double x1, double y1, int value1){   // Three argument constructor
x = x1;
y = y1;
value = value1;
}
void Point::initialize(double init_x, double init_y, int init_value)
{
x = init_x;
y = init_y;
value = init_value;
}
void Point::shift(Point p){
if(p == VK_LEFT)
{
}else if(p == VK_RIGHT)
{
}else if(p == VK_UP)
{
}else if(p == VK_DOWN)
{
}
}

它现在给我一个错误,没有匹配的操作符==(操作数类型'point'和'int')

point和int的问题是因为您试图将2d坐标与ASCII值(VK_*)进行比较,将该部分更改为以下内容,它应该更容易维护:

Point Point::shift(Point p, int keyPress)
{
    Point maxSize = new Point();
    Point minSize = new Point();
    maxSize.x=80;
    maxSize.y=40; 
 //  Assuming a coordinate system of 0,0 (x,y) at top left of the display
    switch (keyPress)
    {
      case (VK_LEFT):    // increment the x coord by 1 to go left
        p.x += 1;
        if (p.x < minSize.x) p.x = minSize.x;
        break;
      case (VK_RIGHT):    // decrement the x coord by 1 to go right
        p.x -= 1;
        if (p.x > maxize.x) p.x = maxSize.x;
        break;
      case (VK_UP):    // decrement the y coord by 1 to go up
        p.y -= 1;
        if (p.y < minSize.y) p.y = minSize.y;
        break;
      case (VK_DOWN):    // increment the y coord by 1 to go down
        p.y += 1;
        if (p.y > maxize.y) p.y = maxSize.y;
        break;
    }
    return p;
}

你还必须检查x和y永远不会小于0,因为这会使它们离开显示/导致异常,这取决于你如何构建代码和播放区域。

希望这有助于你的运动问题,但让我知道,如果你需要更多的信息:)