close

題目

結果.png

使用方向鍵或wasd改變1的位置

 

C++

 


#include <bits/stdc++.h>
#include <conio.h>
using namespace std;

int f=1,size,x=1,y=1,ch1=0,ch2=0;
string key="0";
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;//互斥鎖 

void *keyboard(void* arg)
{
    while (1)
    {
    	ch1=getch();//第一次取得按鍵 
        pthread_mutex_lock(&mut);//上鎖,一次只讓一個執行續執行 
    	if (ch1==224)//得到方向鍵 
        { 
        	ch2=getch();//因為是方向鍵要再取一次按鍵 
		if (ch2==72)//上 
        	{
        		x-=1;
        		x=(x+size)%size;
			f=1;
			key="↑";
		}
		else if(ch2==80)//下 
		{
			x+=1;
			x=(x+size)%size;
			f=1;
			key="↓";
		}
		else if(ch2==75)//左 
		{
			y-=1;
			y=(y+size)%size;
			f=1;
			key="←";
		}
		else if(ch2==77)//右 
		{
			y+=1;
			y=(y+size)%size;
			f=1;
			key="→";
		}
        }
	else //非方向鍵 
	{
		if(ch1==119)//上 
		{
			x-=1;
        		x=(x+size)%size;
			f=1;
			key="w";
		}
		else if(ch1==115)//下 
		{
			x+=1;
        		x=(x+size)%size;
			f=1;
			key="s";
		}
		else if(ch1==97)//左 
		{
			y-=1;
        		y=(y+size)%size;
			f=1;
			key="a";
		}
		else if(ch1==100)//右 
		{
			y+=1;
        		y=(y+size)%size;
			f=1;
			key="d";
		}
	}  
	pthread_mutex_unlock(&mut);//解鎖 
    }
}

void *display(void* arg)//顯示畫面 
{
	while(1)
	{
		if(f==1)//有人按按鍵 
		{
			f=0;//關閉旗標 
			system("cls");//清空畫面 
			
			string str[size];//建立字串 
			for(int i =0;i<size;i++)
			{//設定字串 
				str[i]="";
				for(int j=0;j<size;j++)
				{
					str[i]+="0";
				}
			}
			
			str[x][y]='1';//設定1的位置 
			
			for(int i =0;i<size;i++)//輸出 
			{
				cout<<str[i]<<endl;
			}
			cout<<"目前位置: "<<x*size+y<<endl<<"輸入按鍵: " <<key; 
		}
	}
}

int main() {
	
	cout<<"輸入大小"<<endl;
	cin>>size;//輸入大小 
	pthread_t t1,t2,t3;//宣告多執行緒變數 
	
	pthread_create(&t1, NULL,keyboard,NULL);//建立子執行緒 
	pthread_create(&t2, NULL,keyboard,NULL);
	pthread_create(&t3, NULL,display,NULL);
	
	pthread_join(t1, NULL);//等待結束 
	pthread_join(t2, NULL);
	pthread_join(t3, NULL);
	return 0;
}
arrow
arrow
    創作者介紹
    創作者 豪CO 的頭像
    豪CO

    程式道路,必為豐富

    豪CO 發表在 痞客邦 留言(0) 人氣()