簡體   English   中英

如何在控制台中在坐標XY上移動點對象-C ++ OOP

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

我正在做面向對象的編程任務,在該任務中,我被要求為孩子們創建一個捉數字游戲,以便他們在享受游戲的同時也學習計數數字。

在這里,我應該創建一個Point類和一個xy坐標。 在這里,我必須創建一個將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,因為這會使它們不顯示/導致異常,具體取決於您構造代碼和播放區域的方式。

希望這有助於解決您的運動問題,但如果您需要更多信息,請告訴我:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM