Hackerboard Wiki HaboBlog
Hackerboard bei Facebook Hackerboard bei Google+ Hackerboard bei Twitter

[HaBo]

 
Programmieraufgaben Hier wird regelmäßig eine neue Programmieraufgabe gestellt, die dann gelöst werden soll und in Zusammenarbeit mit den Moderatoren auch besprochen werden kann.

Binäruhr

Diskussion: Binäruhr im Forum Programmieraufgaben, in der Kategorie Code Kitchen; Anzeige Eingereicht von Ook! Zitat: Eine Idee für eine Programmieraufgabe, Schwierigkeit 1,5 Wie wäre es mit einer Binären Uhr? Stunden, ...

Antwort
Alt 11.05.08, 16:32   #1 (permalink)
CDW
Moderator
 
Benutzerbild von CDW
 
Registriert seit: 20.07.05
CDW Leistung: OpteronCDW Leistung: OpteronCDW Leistung: OpteronCDW Leistung: OpteronCDW Leistung: OpteronCDW Leistung: Opteron
Likes: 202
Standard Binäruhr

Anzeige

Eingereicht von Ook!

Zitat:
Eine Idee für eine Programmieraufgabe, Schwierigkeit 1,5

Wie wäre es mit einer Binären Uhr? Stunden, Minuten & Sekunden sollten angezeigt werden, binär sowohl als auch dezimal...
Wenn möglich natürlich mit Oberfläche, Konsolenbasiert geht auch... wie Ihr wollt.
Für eine Anregung, wie das ganze ausschauen könnte, bietet sich wikipedia an:
http://de.wikipedia.org/wiki/Bin%C3%A4re_Uhr
Schwierigkeit 2 wegen GUI-Fummelei ;)
__________________
Noch mal, für alle Pseudo-Geeks: 1+1=0. -> 10 wäre Überlauf!
Selig, wer nichts zu sagen hat und trotzdem schweigt.
CDW ist offline   Mit Zitat antworten
Alt 11.05.08, 21:24   #2 (permalink)
 
Registriert seit: 22.03.08
MontyPerl Leistung: Facit NTK
Likes: 0
Standard

=(   
Code:
#!/usr/bin/env perl
use warnings;
use strict;
use Tk;

my $mw = MainWindow->new(
    -title      => "binary-clock 10111",
    -background => "black",
);

$mw->geometry('150x120');
$mw->resizable(0, 0);

my $secFrame = $mw->Frame(
    -width       => 50,
    -height      => 100,
    -borderwidth => 10,
    -background  => "black"
);
my $minFrame = $mw->Frame(
    -width       => 50,
    -height      => 100,
    -borderwidth => 10,
    -background  => "black"
);
my $hourFrame = $mw->Frame(
    -width       => 50,
    -height      => 100,
    -borderwidth => 10,
    -background  => "black"
);

my %LED = setupLEDS($secFrame, $minFrame, $hourFrame);
my $decTime;
$mw->repeat(1000, [\&myMainLoop, \$decTime, \%LED]);
myMainLoop(\$decTime, \%LED);

$mw->Label(
    -textvariable => \$decTime,
    -background   => "black",
    -foreground   => "grey"
)->grid();
Tk::grid($hourFrame, $minFrame, $secFrame);

MainLoop();

sub myMainLoop {
    my ($timeVarRef, $LED) = @_;
    updateTime($timeVarRef);
    my ($hours, $min, $sec) = $$timeVarRef =~ /^(\d{2}):(\d{2}):(\d{2})$/;
    updateLEDS($hours, $min, $sec, $LED);
    return;
}

sub updateTime {
    my ($timeVarRef) = @_;
    my ($sec, $min, $hours) = localtime;
    $$timeVarRef = sprintf "%02d:%02d:%02d", ($hours, $min, $sec);
    return;
}

sub separateTenOne {
    my ($decimal) = @_;
    my ($ten, $one) = (0, 0);
    $ten = int $decimal / 10;
    $one = $decimal - $ten * 10;
    return ($ten, $one);
}

sub updateLEDS {
    my ($hour, $min, $sec, $LED) = @_;
    my ($secTen,  $secOne)  = separateTenOne($sec);
    my ($minTen,  $minOne)  = separateTenOne($min);
    my ($hourTen, $hourOne) = separateTenOne($hour);

    # seconds:
    for my $i (1, 2, 4) {
        my $color = ($i & $secTen) ? "blue" : "black";
        $$LED{"sec10_$i"}->configure(-background => $color);
    }
    for my $i (1, 2, 4, 8) {
        my $color = ($i & $secOne) ? "blue" : "black";
        $$LED{"sec1_$i"}->configure(-background => $color);
    }

    # minutes:
    for my $i (1, 2, 4) {
        my $color = ($i & $minTen) ? "green" : "black";
        $$LED{"min10_$i"}->configure(-background => $color);
    }
    for my $i (1, 2, 4, 8) {
        my $color = ($i & $minOne) ? "green" : "black";
        $$LED{"min1_$i"}->configure(-background => $color);
    }

    # and finally hours:
    for my $i (1, 2) {
        my $color = ($i & $hourTen) ? "red" : "black";
        $$LED{"hour10_$i"}->configure(-background => $color);
    }
    for my $i (1, 2, 4, 8) {
        my $color = ($i & $hourOne) ? "red" : "black";
        $$LED{"hour1_$i"}->configure(-background => $color);
    }

}

sub setupLEDS {
    # now i'll put the "LED"s (label widgets) into a hash and grid them.
    my ($secFrame, $minFrame, $hourFrame) = @_;
    my %LED;

    # seconds first:
    for my $i (1, 2, 4, 8) {
        $LED{"sec1_$i"} = $secFrame->Label(
            -text       => ' ',
            -background => "blue",
            -relief     => "groove"
        );
    }
    for my $i (1, 2, 4) {
        $LED{"sec10_$i"} = $secFrame->Label(
            -text       => ' ',
            -background => "blue",
            -relief     => "groove"
        );
    }
    Tk::grid("x",             $LED{"sec1_8"});
    Tk::grid($LED{"sec10_4"}, $LED{"sec1_4"});
    Tk::grid($LED{"sec10_2"}, $LED{"sec1_2"});
    Tk::grid($LED{"sec10_1"}, $LED{"sec1_1"});

    # now minutes:
    for my $i (1, 2, 4, 8) {
        $LED{"min1_$i"} = $minFrame->Label(
            -text       => ' ',
            -background => "green",
            -relief     => "groove"
        );
    }
    for my $i (1, 2, 4) {
        $LED{"min10_$i"} = $minFrame->Label(
            -text       => ' ',
            -background => "green",
            -relief     => "groove"
        );
    }
    Tk::grid("x",             $LED{"min1_8"});
    Tk::grid($LED{"min10_4"}, $LED{"min1_4"});
    Tk::grid($LED{"min10_2"}, $LED{"min1_2"});
    Tk::grid($LED{"min10_1"}, $LED{"min1_1"});

    # and hours:
    for my $i (1, 2, 4, 8) {
        $LED{"hour1_$i"} = $hourFrame->Label(
            -text       => ' ',
            -background => "red",
            -relief     => "groove"
        );
    }
    for my $i (1, 2) {
        $LED{"hour10_$i"} = $hourFrame->Label(
            -text       => ' ',
            -background => "red",
            -relief     => "groove"
        );
    }
    Tk::grid("x",              $LED{"hour1_8"});
    Tk::grid("x",              $LED{"hour1_4"});
    Tk::grid($LED{"hour10_2"}, $LED{"hour1_2"});
    Tk::grid($LED{"hour10_1"}, $LED{"hour1_1"});

    return %LED;
}

Sind zwar ziemlich viele Zeilen code, aber vieles wurde durch stumpfes copy'n'paste erstellt. (Speziell in den subs updateLEDS und setupLEDS, da sind die Blöcke für Sekunden, Minuten und Stunden jeweils fast exakt gleich.)
Auch wird jede Zelle neu "configured", nicht nur die, für die sich der Status geändert hat. Aber bei einem frame-per-second darf man sich sowas wohl mal erlauben ):

ps: ich hatte das eigentlich grade schon gepostet, aber das Forum hats wohl irgendwie "verschluckt".
MontyPerl ist offline   Mit Zitat antworten
   
HaBOT
 
- Anzeige -

Werbung ist gerade online    
Alt 12.05.08, 13:05   #3 (permalink)
 
Registriert seit: 11.09.05
Diabeles Leistung: Facit NTK
Likes: 0
Standard

Python   
Code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pygame
import sys
import time

SIZE = 10

def dec2bin(n):
    return ((n >> i) % 2 for i in range(6)[::-1])

def hms_time():
    return map(int, map(time.strftime, ("%H", "%M", "%S")))
    
if __name__ == "__main__":
    pygame.display.init()
    screen = pygame.display.set_mode((6 * SIZE, 3 * SIZE))
    pygame.display.set_caption("Binaeruhr")
    clock = pygame.time.Clock()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
        hms = hms_time()
        for y, value in enumerate(hms):
            for x, b in enumerate(dec2bin(value)):
                color = 0, 0, 255 * b
                pygame.draw.rect(screen, color, (SIZE * x, SIZE * y, SIZE, SIZE))
                pygame.draw.rect(screen, (0, 0, 0), (SIZE * x, SIZE * y, SIZE, SIZE), 2)
        pygame.display.update()
        clock.tick(1)
Diabeles ist offline   Mit Zitat antworten
Alt 12.05.08, 19:41   #4 (permalink)
 
Registriert seit: 16.10.07
Spyx Leistung: Facit NTK
Spyx eine Nachricht über ICQ schicken
Likes: 0
Standard

Hier meine grafische Lösung in FreeBASIC:
60 Zeilen Code   
Code:
'Binäruhr von Spyx


'Variablen definieren
DIM AS INTEGER kreisbreite, kreishoehe
DIM AS UBYTE stunden, minuten, sekunden, i, farbe
DIM uhrzeit AS STRING * 8
DIM key AS STRING * 2

'Grafikmodus initialisieren
SCREENRES 92, 175
Color 15,0

'Beim drücken der Escapetaste oder des Kreuzes oben rechts Schleife beenden
WHILE (key<>CHR(27)) and key<>(Chr(255, 107))
    'Bildschirm leeren
    CLS
    
    'Zeit als String abrufen
    uhrzeit = TIME
    'Stunden, Minuten, Sekunden als unsigned Byte speichern
    stunden = 10*CAST(BYTE,CHR(uhrzeit[0])) + CAST(BYTE,CHR(uhrzeit[1]))
    minuten = 10*CAST(BYTE,CHR(uhrzeit[3])) + CAST(BYTE,CHR(uhrzeit[4]))
    sekunden = 10*CAST(BYTE,CHR(uhrzeit[6])) + CAST(BYTE,CHR(uhrzeit[7]))
    
    'Anzeige
    FOR i = 0 to 5
        
        'Stunden anzeigen
        IF BIT(stunden, i) THEN
            farbe = 15
        ELSE
            farbe = 8
        ENDIF
        CIRCLE (14,31+i*25), 10,farbe,,,1.2,F
        DRAW STRING (8,5),STR(stunden)
        
        'Minuten anzeigen
        IF BIT(minuten, i) THEN
            farbe = 15
        ELSE
            farbe = 8
        ENDIF
        CIRCLE (45,31+i*25), 10,farbe,,,1.2,F
        DRAW STRING (39,5),STR(minuten)
        
        'Sekunden anzeigen
        IF BIT(sekunden, i) THEN
            farbe = 15
        ELSE
            farbe = 8
        ENDIF
        CIRCLE (76,31+i*25), 10,farbe,,,1.2,F
        DRAW STRING (70,5),STR(sekunden)
    NEXT

    'Tastaturabfrage
    key = INKEY

    'Flimmern reduzieren
    SCREENSYNC
WEND
END

Wie man die Uhr lesen muss, sollte sich eigentlich selbst erklären. Falls es jmd. kompilieren möchte, so gibt es hier den Compiler:
http://freebasic.net/index.php/download
Spyx ist offline   Mit Zitat antworten
Alt 12.05.08, 20:41   #5 (permalink)
 
Registriert seit: 12.05.08
deadbird Leistung: Facit NTK
Likes: 0
Standard

Konsolenlösung in c++...
Sind glaube ich ein bischen viele Zeilen Code geworden...

...   
Code:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <windows.h>

using namespace std;
void bin(time_t secs);

int main(){
	time_t seconds;
	time_t old;
	old=time(NULL);
	while(1){
		seconds=time(NULL);
		seconds+=(2*3600);
		if(seconds>old){
			system("cls");
			cout<<"Dezimal : "<<(seconds/3600)%24<<":"<<(seconds/60)%60<<":"<<seconds%60<<endl;
			cout<<"Binaer : "<<endl;
			cout<<"hour mins secs"<<endl;
			bin(seconds);
			old=seconds;
		}		
	}
	return 0;
}
void bin(time_t in){
	char feld[3][6];
	for(int i=0; i<3; i++){
		for(int j=0; j<6; j++){
			feld[i][j]='0';
		}
	}
	double hour=(double) ((in/3600)%24);
	for(double i=32.0; i>=1.0; i=i/2){
		if(hour/i>=1.0){
			switch((int) i){
				case 32:
					feld[0][0]='1';
					hour-=32.0;
					break;
				
				case 16:
					feld[0][1]='1';
					hour-=16.0;
					break;

				case 8:
					feld[0][2]='1';
					hour-=8.0;
					break;

				case 4:
					feld[0][3]='1';
					hour-=4.0;
					break;

				case 2:
					feld[0][4]='1';
					hour-=2.0;
					break;

				case 1:
					feld[0][5]='1';
					break;

				default:
					break;

			}
		}
	}
	
	double mins=(double) ((in/60)%60);
	for(double i=32.0; i>=1.0; i=i/2){
		if(mins/i>=1.0){
			switch((int) i){
				case 32:
					feld[1][0]='1';
					mins-=32.0;
					break;
				
				case 16:
					feld[1][1]='1';
					mins-=16.0;
					break;

				case 8:
					feld[1][2]='1';
					mins-=8.0;
					break;

				case 4:
					feld[1][3]='1';
					mins-=4.0;
					break;

				case 2:
					feld[1][4]='1';
					mins-=2.0;
					break;

				case 1:
					feld[1][5]='1';
					break;

				default:
					break;

			}
		}
	}
	double secs=(double) ((in)%60);
	for(double i=32.0; i>=1.0; i=i/2){
		if(secs/i>=1.0){
			switch((int) i){
				case 32:
					feld[2][0]='1';
					secs-=32.0;
					break;
				
				case 16:
					feld[2][1]='1';
					secs-=16.0;
					break;

				case 8:
					feld[2][2]='1';
					secs-=8.0;
					break;

				case 4:
					feld[2][3]='1';
					secs-=4.0;
					break;

				case 2:
					feld[2][4]='1';
					secs-=2.0;
					break;

				case 1:
					feld[2][5]='1';
					break;

				default:
					break;

			}
		}
	}
	for(int y=0; y<6; y++){
		for(int x=0; x<3; x++){
			cout<<"  "<<feld[x][y]<<"  ";
		}
		cout<<endl;
	}
}
deadbird ist offline   Mit Zitat antworten
Alt 13.05.08, 20:43   #6 (permalink)
LX
Moderator
 
Registriert seit: 14.02.06
LX Leistung: Z3
LX eine Nachricht über ICQ schicken LX eine Nachricht über AIM schicken LX eine Nachricht über Yahoo! schicken
Likes: 21
Arrow

CDW:
Nanu, hast ja deine ASM-Binäruhr noch gar net mit gepostet

Naja, ich hab das vor ein paar Jahren mal in JavaScript und HTML umgesetzt. Das Script selber ist dabei recht kurz:

JavaScript   
Code:
function display(number, column)
{
  led3 = Math.floor(number / 8);
  led2 = Math.floor((number % 8) / 4);
  led1 = Math.floor((number % 4) / 2);
  led0 = Math.floor(number % 2);

  if (column == 0)
    end = 2;
  else if (column % 2 != 0)
    end = 4;
  else
    end = 3;

    for (i = 0; i < end; i++)
    {
      if (eval ("led"+i))
        document.getElementById("led" + column + i).checked = true;
      else
        document.getElementById("led" + column + i).checked = false;
    }
}

function clock()
{
  var time = new Date();
  
  var hrs = time.getHours();
  display(Math.floor(hrs/10),0);
  display(hrs%10,1);
  
  var min = time.getMinutes();
  display(Math.floor(min/10),2);
  display(min%10,3);

  var sec = time.getSeconds();
  display(Math.floor(sec/10),4);
  display(sec%10,5);

  setTimeout("clock()",1000);
}

clock();


'n bissel HTML ist aber noch nötig für die Ausgabe. Das gesamte Teil kann auf meiner Homepage bestaunt werden.
__________________
"Ever tried. Ever failed. No matter.
Try again. Fail again. Fail better."
- Samuel Beckett

JS BB LX UP
LX ist offline   Mit Zitat antworten
Alt 13.05.08, 23:34   #7 (permalink)
CDW
Moderator
Themenstarter
 
Benutzerbild von CDW
 
Registriert seit: 20.07.05
CDW Leistung: OpteronCDW Leistung: OpteronCDW Leistung: OpteronCDW Leistung: OpteronCDW Leistung: OpteronCDW Leistung: Opteron
Likes: 202
Standard

Zitat:
Original von LX
CDW:
Nanu, hast ja deine ASM-Binäruhr noch gar net mit gepostet

Naja, ich hab das vor ein paar Jahren mal in JavaScript und HTML umgesetzt.
Also, wenn du mich schon verrätst - ich wurde damals von DEINEM Script inspiriert. Das heißt: das was du uns hier als fast neuwertig unterschieben möchtest (nur "paar Jahre" alt) hat in Wirklichkeit schon 5 Jährchen auf dem Buckel
__________________
Noch mal, für alle Pseudo-Geeks: 1+1=0. -> 10 wäre Überlauf!
Selig, wer nichts zu sagen hat und trotzdem schweigt.
CDW ist offline   Mit Zitat antworten
Alt 14.05.08, 11:14   #8 (permalink)
 
Registriert seit: 05.06.07
0mega Leistung: Facit NTK
Likes: 0
Standard

entweder hab ich was falsch verstanden, oder es war wirklich einfach o,o
der sourcecode is in powerbasic 3.2o geschrieben, mfg.

mir fällt grad auf, das is ja mein erster post unter programmieraufgaben

Code:
color 2,0
cls
while not instat

    h$=bin$(val(left$(time$,2)))
    m$=bin$(val(mid$(time$,4,2)))
    s$=bin$(val(right$(time$,2)))

    locate 13,10
    print h$+":"+m$+":"+s$
    locate 1,65
    print time$

wend
__________________
Jabber: admin@c-r-t.ath.cx
0mega ist offline   Mit Zitat antworten
Alt 21.05.08, 03:53   #9 (permalink)
 
Registriert seit: 21.04.08
Ook! Leistung: Facit NTK
Likes: 0
Standard

Hallo!

Meine eigene Variante in Java

Controller:
Code:
public void run() {
	while(true) {
		date.setTime(System.currentTimeMillis());
			
		decimalPanel.setTimeOnLabel(sdf.format(date));
		binaryPanel.setTimeOnLEDs(sdf.format(date));
			
		try { Thread.sleep(1000); } 
		catch (InterruptedException e) { e.printStackTrace(); }
	}
}
Binäranzeige:
Code:
public void setTimeOnLEDs(String value) {
		value = value.replaceAll(" : ", "");

		setAllLedsToOff();
		for(int i=0; i<value.length(); i++) {
			String binary = getBinaryString(Integer.parseInt(String.valueOf(value.charAt(i))));
			
			for(int z=0; z<binary.length(); z++)
				leds.get(i)[z].setOn(Integer.parseInt(String.valueOf(binary.charAt(z))));
		}
		repaint();
	}

private String getBinaryString(int value) {
		String binary = "";

		while(value > 0) { 
			if((value % 2) == 1) { 
				value = (value - 1) / 2; 
				binary += "1";
			}
			else {
				value = value / 2;
				binary += "0";
			}
		}
		return binary;
	}
Ich habe nicht den kompletten Code gepostet, wäre etwas viel geworden... nur die Teile, die ich für den Kern der Anwendung halte.

Gruß
Felix
Angehängte Dateien
Dateityp: rar Binäre Uhr.rar (7,1 KB, 16x aufgerufen)
Ook! ist offline   Mit Zitat antworten
Alt 06.10.08, 14:55   #10 (permalink)
 
Registriert seit: 10.01.08
FdDi Leistung: Facit NTK
Likes: 0
Standard

ALso meine Lösung ist in java
als Applet geschrieben

Hier Meine Lösung - 62 Zeilen   

Code:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.util.BitSet;
import java.util.Date;

public class Binaryclock extends Applet{
	public Date heute = new Date(System.currentTimeMillis());
	
	public static BitSet convertDez2bin(int dez, int bits) {
		BitSet bit = new BitSet(bits);
		for (int i = 0; i < bits; i++) {
			bit.set(bits-i, (dez%2 == 1)?true:false);
			dez = dez/2;
		}
		return bit;	
	}
	public static Graphics rect(Graphics e, int x, int y){
		e.drawOval(x, y, 10, 10);
		return e ;
	}
	public static Graphics rectf(Graphics e, int x, int y){
		e.fillOval(x, y, 12, 12);
		return e ;
	}
	public static Graphics bin2rect(Graphics e, BitSet b,int bits, int offsety ,int offsetx){
		for (int i = 1; i <= bits; i++) {
			if(b.get(i)) rectf(e, 10+offsetx-1, 12*i+offsety);
			else rect(e, 10+offsetx, 12*i+offsety);
		}
		return e;
	}
	@SuppressWarnings("deprecation")
	public void paint(Graphics e) {
			e.setColor(Color.ORANGE);
			e.drawString("Hour", 30, 10);
			e.drawString("Minute", 70, 10);
			e.drawString("Second", 120, 10);
			e.drawString(heute.toString(), 5 ,130);
			e.drawString("1", 15, 105);
			e.drawString("2", 15, 93);
			e.drawString("4", 15, 81);
			e.drawString("8", 15, 69);
			e.drawString("16", 15, 57);
			e.drawString("32", 15, 45);
			bin2rect(e, convertDez2bin(heute.getHours(), 6), 6, 20, 30);
			bin2rect(e, convertDez2bin(heute.getMinutes(), 6), 6, 20, 70);
			bin2rect(e, convertDez2bin(heute.getSeconds(), 6), 6, 20, 120);
			heute.setTime(System.currentTimeMillis());
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			super.repaint();
	}
	public void init() {
		setBackground(Color.BLACK);
		setSize(200, 150);
		super.init();
	}
}
FdDi ist offline   Mit Zitat antworten
Alt 20.05.09, 13:17   #11 (permalink)
 
Registriert seit: 02.09.08
Speedy_92 Leistung: Facit NTK
Likes: 0
Standard

Hier mal meine Version in C# .NET. Ich weiß, man könnte die Anzahl der Zeilen noch drastisch optimieren, aber mir ging es erstmal nur darum, dass es läuft :

BinaryClock.cs   

Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace BinaryClock
{
	public partial class BinaryClock : Form
	{
		Image img0 = Image.FromFile(Path.GetDirectoryName(Application.ExecutablePath) + @"\gfx\0.jpg");
		Image img1 = Image.FromFile(Path.GetDirectoryName(Application.ExecutablePath) + @"\gfx\1.jpg");

		bool[] zHours = new bool[2];
		bool[] eHours = new bool[4];
		bool[] zMinutes = new bool[3];
		bool[] eMinutes = new bool[4];
		bool[] zSeconds = new bool[3];
		bool[] eSeconds = new bool[4];

		BackgroundWorker bgw = new BackgroundWorker();

		public BinaryClock()
		{
			InitializeComponent();
			bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
			bgw.WorkerSupportsCancellation = true;
			bgw.RunWorkerAsync();
		}

		void bgw_DoWork(object sender, DoWorkEventArgs e)
		{
			DateTime dt	= DateTime.Now.ToLocalTime();

			while (true)
			{
				if (dt == DateTime.Now.ToLocalTime())
					continue;

				dt	= DateTime.Now.ToLocalTime();

				#region zHours

				int zHour = dt.Hour;

				zHours[0] = false;
				zHours[1] = false;

				if (zHour >= 20)
				{
					zHours[0] = true;
					zHours[1] = false;
				}
				else if (zHour >= 10)
				{
					zHours[0] = false;
					zHours[1] = true;
				}

				#endregion

				#region eHours

				int eHour = dt.Hour % 10;

				eHours[0] = false;
				eHours[1] = false;
				eHours[2] = false;
				eHours[3] = false;

				if (eHour >= 8)
				{
					eHours[0] = true;
					eHour -= 8;
				}
				if (eHour >= 4)
				{
					eHours[1] = true;
					eHour -= 4;
				}
				if (eHour >= 2)
				{
					eHours[2] = true;
					eHour -= 2;
				}
				if (eHour >= 1)
				{
					eHours[3] = true;
				}
				
				#endregion

				#region zMinutes

				int zMinute = dt.Minute;

				zMinutes[0] = false;
				zMinutes[1] = false;
				zMinutes[2] = false;

				if (zMinute >= 40)
				{
					zMinutes[0] = true;
					zMinute -= 40;
				}
				if (zMinute >= 20)
				{
					zMinutes[1] = true;
					zMinute -= 20;
				}
				if (zMinute >= 10)
				{
					zMinutes[2] = true;
				}

				#endregion

				#region eMinutes

				int eMinute = dt.Minute % 10;

				eMinutes[0] = false;
				eMinutes[1] = false;
				eMinutes[2] = false;
				eMinutes[3] = false;

				if (eMinute >= 8)
				{
					eMinutes[0] = true;
					eMinute -= 8;
				}
				if (eMinute >= 4)
				{
					eMinutes[1] = true;
					eMinute -= 4;
				}
				if (eMinute >= 2)
				{
					eMinutes[2] = true;
					eMinute -= 2;
				}
				if (eMinute >= 1)
				{
					eMinutes[3] = true;
				}

				#endregion

				#region zSeconds

				int zSecond = dt.Second;

				zSeconds[0] = false;
				zSeconds[1] = false;
				zSeconds[2] = false;

				if (zSecond >= 40)
				{
					zSeconds[0] = true;
					zSecond -= 40;
				}
				if (zSecond >= 20)
				{
					zSeconds[1] = true;
					zSecond -= 20;
				}
				if (zSecond >= 10)
				{
					zSeconds[2] = true;
				}

				#endregion

				#region eSeconds

				int eSecond = dt.Second % 10;

				eSeconds[0] = false;
				eSeconds[1] = false;
				eSeconds[2] = false;
				eSeconds[3] = false;

				if (eSecond >= 8)
				{
					eSeconds[0] = true;
					eSecond -= 8;
				}
				if (eSecond >= 4)
				{
					eSeconds[1] = true;
					eSecond -= 4;
				}
				if (eSecond >= 2)
				{
					eSeconds[2] = true;
					eSecond -= 2;
				}
				if (eSecond >= 1)
				{
					eSeconds[3] = true;
				}

				#endregion

				doubleBufferedPanel.Invalidate();
			}
		}

		private void BinaryClock_FormClosing(object sender, FormClosingEventArgs e)
		{
			bgw.CancelAsync();
		}

		private void doubleBufferedPanel_Paint(object sender, PaintEventArgs e)
		{
			//198 Breit
			//132 Hoch

			for (int i = 0; i < 2; i++)
			{
				if (zHours[i] == true)
				{
					e.Graphics.DrawImage(img1, new Point(0, (i + 2) * 33));
				}
				else
				{
					e.Graphics.DrawImage(img0, new Point(0, (i + 2) * 33));
				}
			}

			for (int i = 0; i < 4; i++)
			{
				if (eHours[i] == true)
				{
					e.Graphics.DrawImage(img1, new Point(33, i * 33));
				}
				else
				{
					e.Graphics.DrawImage(img0, new Point(33, i * 33));
				}
			}

			for (int i = 0; i < 3; i++)
			{
				if (zMinutes[i] == true)
				{
					e.Graphics.DrawImage(img1, new Point(66, (i + 1) * 33));
				}
				else
				{
					e.Graphics.DrawImage(img0, new Point(66, (i + 1) * 33));
				}
			}

			for (int i = 0; i < 4; i++)
			{
				if (eMinutes[i] == true)
				{
					e.Graphics.DrawImage(img1, new Point(99, i * 33));
				}
				else
				{
					e.Graphics.DrawImage(img0, new Point(99, i * 33));
				}
			}

			for (int i = 0; i < 3; i++)
			{
				if (zSeconds[i] == true)
				{
					e.Graphics.DrawImage(img1, new Point(132, (i + 1) * 33));
				}
				else
				{
					e.Graphics.DrawImage(img0, new Point(132, (i + 1) * 33));
				}
			}

			for (int i = 0; i < 4; i++)
			{
				if (eSeconds[i] == true)
				{
					e.Graphics.DrawImage(img1, new Point(165, i * 33));
				}
				else
				{
					e.Graphics.DrawImage(img0, new Point(165, i * 33));
				}
			}
		}
	}
}



BinaryClock.Designer.cs   

Code:
namespace BinaryClock
{
	partial class BinaryClock
	{
		/// <summary>
		/// Erforderliche Designervariable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Verwendete Ressourcen bereinigen.
		/// </summary>
		/// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Vom Windows Form-Designer generierter Code

		/// <summary>
		/// Erforderliche Methode für die Designerunterstützung.
		/// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
		/// </summary>
		private void InitializeComponent()
		{
			this.doubleBufferedPanel = new DoubleBufferedPanel();
			this.SuspendLayout();
			// 
			// doubleBufferedPanel
			// 
			this.doubleBufferedPanel.BackColor = System.Drawing.Color.Black;
			this.doubleBufferedPanel.ForeColor = System.Drawing.SystemColors.Control;
			this.doubleBufferedPanel.Location = new System.Drawing.Point(0, 0);
			this.doubleBufferedPanel.Name = "doubleBufferedPanel";
			this.doubleBufferedPanel.Size = new System.Drawing.Size(198, 132);
			this.doubleBufferedPanel.TabIndex = 0;
			this.doubleBufferedPanel.Paint += new System.Windows.Forms.PaintEventHandler(this.doubleBufferedPanel_Paint);
			// 
			// BinaryClock
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(198, 132);
			this.Controls.Add(this.doubleBufferedPanel);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
			this.MaximizeBox = false;
			this.Name = "BinaryClock";
			this.Text = "BinaryClock";
			this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.BinaryClock_FormClosing);
			this.ResumeLayout(false);

		}

		#endregion

		private DoubleBufferedPanel doubleBufferedPanel;
	}
}


DoubleBufferedPanel.cs   

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BinaryClock
{
	public class DoubleBufferedPanel : Panel
	{
		public DoubleBufferedPanel()
		{
			this.DoubleBuffered = true;
		}
	}
}


Program.cs   

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace BinaryClock
{
	static class Program
	{
		/// <summary>
		/// Der Haupteinstiegspunkt für die Anwendung.
		/// </summary>
		[STAThread]
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new BinaryClock());
		}
	}
}


Das wars dann auch schon

*EDIT: Hier noch die Grafik-Quellen, hatte ich vergessen^^: Klick

Speedy_92
Speedy_92 ist offline   Mit Zitat antworten
Alt 20.05.09, 14:26   #12 (permalink)
 
Registriert seit: 12.01.09
lone.wolf Leistung: Z3
lone.wolf eine Nachricht über AIM schicken
Likes: 1
Standard



Grafik-Quellen: http://haubergs.com/bc

Edit:
NonVCL(Delphi) Version für NONVCL FREAKS
Angehängte Dateien
Dateityp: rar binähhhrrr.rar (201,8 KB, 7x aufgerufen)
Dateityp: rar binääähhhrrr nonvcl.rar (98,2 KB, 5x aufgerufen)
lone.wolf ist offline   Mit Zitat antworten
Alt 20.05.09, 14:38   #13 (permalink)
 
Registriert seit: 02.09.08
Speedy_92 Leistung: Facit NTK
Likes: 0
Standard

@lone.wolf

Ich habe mal unsere beiden Uhren neben der Systemuhr laufen lassen und irgendwie scheint es mir, als wenn unsere Uhren der Systemuhr immer einen Tick voraus sind
Speedy_92 ist offline   Mit Zitat antworten
Alt 20.05.09, 15:23   #14 (permalink)
 
Registriert seit: 12.01.09
lone.wolf Leistung: Z3
lone.wolf eine Nachricht über AIM schicken
Likes: 1
Standard

Liegt wahrscheinlich an den Bildern.
Die haben etwas magisches an sich.
Letztendlich hat mich die Seite dazu verleitet, eine Binäähhr Uhr zu erschaffen

MfG
lone.wolf ist offline   Mit Zitat antworten
Alt 20.05.09, 15:30   #15 (permalink)
 
Benutzerbild von ChiefWiggum
 
Registriert seit: 09.10.07
ChiefWiggum Leistung: 8086
ChiefWiggum eine Nachricht über ICQ schicken
Likes: 11
Standard

Code:
#include <iostream>
#include <time.h>
#include <windows.h>
using namespace std;

time_t timestamp;
struct tm *timestruct = 0;
char *int2bin(int zahl);
void gotoxy(short x, short y);
int main()
{
    timestamp = time(0);
    while(1) {
        timestruct = localtime(&timestamp);
        gotoxy(1,1);
        printf("(%s\t%s\t%s)(%d:%d:%d)\n",int2bin(timestruct->tm_hour),int2bin(timestruct->tm_min),int2bin(timestruct->tm_sec),timestruct->tm_hour,timestruct->tm_min,timestruct->tm_sec);
        Sleep(1000);
        timestamp++;
    }
    return 0;
}

char *int2bin(int zahl){
    char *mem = new char[7];
    memset(mem, '0', 7);
    int pos = 5;
    if(zahl & 1) mem[pos] = '1'; else mem[pos] = '0'; pos--;
    if(zahl & 2) mem[pos] = '1'; else mem[pos] = '0'; pos--;
    if(zahl & 4) mem[pos] = '1'; else mem[pos] = '0'; pos--;
    if(zahl & 8) mem[pos] = '1'; else mem[pos] = '0'; pos--;
    if(zahl & 16) mem[pos] = '1'; else mem[pos] = '0'; pos--;
    if(zahl & 32) mem[pos] = '1'; else mem[pos] = '0'; pos--;
    mem[6] = 0;
    return mem;
}
void gotoxy(short x, short y)
{
    HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE);
    if(hCon == 0 ) {
        printf("%d\n",GetLastError());
        exit(0);
    }
    COORD pos;
    pos.X=x-1;
    pos.Y=y-1;
    SetConsoleCursorPosition(hCon, pos);
}
meine Lösung
__________________
Be the source always with you.
ChiefWiggum ist offline   Mit Zitat antworten
Antwort
   
- Anzeige -

Werbung ist gerade online    

[HaBo] » Software Home » Code Kitchen » Programmieraufgaben » Binäruhr
Themen-Optionen
Ansicht

Forumregeln
Es ist Ihnen nicht erlaubt, neue Themen zu verfassen.
Es ist Ihnen nicht erlaubt, auf Beiträge zu antworten.
Es ist Ihnen nicht erlaubt, Anhänge hochzuladen.
Es ist Ihnen nicht erlaubt, Ihre Beiträge zu bearbeiten.

BB-Code ist an.
Smileys sind an.
[IMG] Code ist an.
HTML-Code ist aus.
Trackbacks sind aus
Pingbacks sind aus
Refbacks sind aus



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61