Jump to content

The under 100 line challenge!

fletch to 99

A simple little test progam I made for the Spherical Engine. Not quite a hundred lines. 

//A Simple game engine by [redacted]//Import scripts Herevar Red = CreateColor(255, 0, 0, 255)var Green = CreateColor(0, 255, 0, 255)var Blue = CreateColor(0, 0, 255, 255)var penAlign = []var penColor = Bluefont = GetSystemFont()var screenWidth = GetScreenWidth()var screenHeight = GetScreenHeight()function AlignPen (x, y) {	penAlign = [x, y]}function MovePen (x, y) {	Line (penAlign[0], penAlign[1], penAlign[0] + x, penAlign[1] + y, penColor)	AlignPen(penAlign[0] + x, penAlign [1] + y) }function DrawFrame (frameDistance) {//Draws a border w	Line(frameDistance, frameDistance, screenWidth - frameDistance, frameDistance, Red)	Line(frameDistance, frameDistance, screenWidth - frameDistance, frameDistance, Red)	Line(frameDistance, screenHeight - frameDistance, screenWidth - frameDistance, screenHeight - frameDistance, Red)	Line(frameDistance, frameDistance, frameDistance, screenHeight - frameDistance, Red)	Line(screenWidth - frameDistance, frameDistance, screenWidth - frameDistance, screenHeight - frameDistance, Red) }SetFrameRate(60)while (true) {	AlignPen(4, 4)	MovePen(100, 0)	MovePen(0, 100)	MovePen(-100, 0)	MovePen(0, -100)	font.drawText(4 + 5, 4 + 5, "Hello world!");	FlipScreen();}

My procrastination is the bane of my existence.

I make games and stuff in my spare time.

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

Here is one of the first programs I ever wrote. Probably a very tedious algorithm, but it worked fine and gave me an A the first week in CS at high school.

It's a very simple converter between binary and decimal-numbers (meaning the regular 10^x system). 

import java.util.Scanner;public class BinaryConverter {		public static void main(String args[]) {				new BinaryConverter();	}		public BinaryConverter() {				Scanner keyboard = new Scanner(System.in);		boolean stop = true;		int input;				System.out.println("BINARY CONVERTER");		System.out.println("___________________");				while (stop = true)		{			System.out.println("");			System.out.println("Type\n 1 to convert decimal to binary\n 2 to convert binary to decimal\n 3 to quit");			input = keyboard.nextInt();						if (input == 1)				decimalToBinary();			else if (input == 2)				binaryToDecimal();			else if (input == 3)				stop = false;		}	}		public static void decimalToBinary() {				Scanner keyboard = new Scanner(System.in);				int [] array = {128,64,32,16,8,4,2,1};		int num, last = 0;				System.out.println("Type in the decimal number to convert: ");		num = keyboard.nextInt();				//calculate		for (int i = 0; i<array.length; i++)		{			if (num-last >= array[i])			{				num = num-last;				last = array[i];				array[i] = 1;			}			else			{				array[i] = 0;			}		}				System.out.println("The binary number is: ");				//display		for (int j = 0; j<array.length; j++)		{			System.out.print(array[j]);		}				System.out.println("");	}		public static void binaryToDecimal() {				Scanner keyboard = new Scanner(System.in);				String num = null;		int num1 = 0;		int current = 128;				System.out.println("Type in the 8bit binary number to convert: ");		num = keyboard.next();				//calculate		for (int i = 0; i<num.length(); i++)		{			if (num.charAt(i) == '1')			{				num1 = num1 + current;				current = current / 2;			}			else 			{				current = current / 2;			}		}				//display		System.out.println("The decimal number is: " + num1);		}}

99 lines. 

Running Arch with i3-gaps on a Thinkpad X1 Extreme
Data Science Postgrad

 

Link to comment
Share on other sites

Link to post
Share on other sites


<?php

$meme = "dank";

if $meme == "dank" {

echo "Ayyy";

}

else {

echo "stale meme :(";

}

?>

Link to comment
Share on other sites

Link to post
Share on other sites

I made a snake game program in like a day, so yeah. Also it is a little over 100 lines, but I didn't feel like "in-lining" procedures. So its under 100 lines if it was formatted differently.

 

https://github.com/mkmxwl/snake I'm also going to improve the game loop, right now it will just put the thread to sleep

 

Download Turing from here http://compsci.ca/holtsoft/ if you want to run it and play. I made the snake out of dots and the apple so it takes some skillful timing

% right = 0, left = 1, up = 2, down = 3const maxSnake := maxx * maxyvar control : array char of booleanvar x : array 0 .. maxSnake of nat1var y : array 0 .. maxSnake of nat1var long : nat2var dir, add : nat1var applex, appley : intproc apple    loop        randint (applex, 0, maxx)        randint (appley, 0, maxy)        var flag : boolean := true        for j : 0 .. maxy            for i : 0 .. maxx                if x (i) = applex and y (i) = appley then                    flag := false;                end if            end for        end for        exit when (flag)    end loopend appleproc setup    x (0) := 128    y (0) := 128    long := 30    add := 0    dir := 0    for i : 1 .. long        x (i) := x (i - 1) - 1        y (i) := y (0)    end for    appleend setupproc input    Input.KeyDown (control)    if control (KEY_RIGHT_ARROW) and dir not= 1 then        dir := 0    elsif control (KEY_LEFT_ARROW) and dir not= 0 then        dir := 1    elsif control (KEY_UP_ARROW) and dir not= 3 then        dir := 2    elsif control (KEY_DOWN_ARROW) and dir not= 2 then        dir := 3    end ifend inputproc logic    if x (0) = applex and y (0) = appley then        apple        add := 10    end if    if add > 0 then        add -= 1        x (long + 1) := x (long)        y (long + 1) := y (long)        long += 1    end if    for i : 1 .. long        if x (0) = x (i) and y (0) = y (i) then            setup        end if    end for    for decreasing i : long .. 1        x (i) := x (i - 1)        y (i) := y (i - 1)    end for    if dir = 0 and x (0) < maxx then        x (0) += 1    elsif dir = 1 and x (0) > 0 then        x (0) -= 1    elsif dir = 2 and y (0) < maxy then        y (0) += 1    elsif dir = 3 and y (0) > 0 then        y (0) -= 1    else        setup    end ifend logicproc draw    cls    colorback (black)    Draw.Dot (applex, appley, 39)    for i : 0 .. long        Draw.Dot (x (i), y (i), 46)    end for    Font.Draw ("Score: ", 10, maxy - 18, Font.New ("mono:9"), white)    Font.Draw (intstr (long - 30), 55, maxy - 18, Font.New ("mono:9"), white)    View.Updateend drawView.Set ("graphics:256;256, offscreenonly, nobuttonbar, title:Snake")setuploop    input    logic    draw    Time.Delay (16)end loop
Link to comment
Share on other sites

Link to post
Share on other sites

I have something in the works that I might be able to mash into under 50-lines with a hammer but I have to first learn these new API functions I just discovered, until now I thought I could only save data using the .sav files spherical likes so much. considering i'm writing in javascript; directory selection is finicky.

 

I think it's totalling somewhere around 130-150 lines, taking into account commentation of the code.

My procrastination is the bane of my existence.

I make games and stuff in my spare time.

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

 

I made a snake game program in like a day, so yeah. Also it is a little over 100 lines, but I didn't feel like "in-lining" procedures. So its under 100 lines if it was formatted differently.

 

https://github.com/mkmxwl/snake I'm also going to improve the game loop, right now it will just put the thread to sleep

 

Download Turing from here http://compsci.ca/holtsoft/ if you want to run it and play. I made the snake out of dots and the apple so it takes some skillful timing

% right = 0, left = 1, up = 2, down = 3const maxSnake := maxx * maxyvar control : array char of booleanvar x : array 0 .. maxSnake of nat1var y : array 0 .. maxSnake of nat1var long : nat2var dir, add : nat1var applex, appley : intproc apple    loop        randint (applex, 0, maxx)        randint (appley, 0, maxy)        var flag : boolean := true        for j : 0 .. maxy            for i : 0 .. maxx                if x (i) = applex and y (i) = appley then                    flag := false;                end if            end for        end for        exit when (flag)    end loopend appleproc setup    x (0) := 128    y (0) := 128    long := 30    add := 0    dir := 0    for i : 1 .. long        x (i) := x (i - 1) - 1        y (i) := y (0)    end for    appleend setupproc input    Input.KeyDown (control)    if control (KEY_RIGHT_ARROW) and dir not= 1 then        dir := 0    elsif control (KEY_LEFT_ARROW) and dir not= 0 then        dir := 1    elsif control (KEY_UP_ARROW) and dir not= 3 then        dir := 2    elsif control (KEY_DOWN_ARROW) and dir not= 2 then        dir := 3    end ifend inputproc logic    if x (0) = applex and y (0) = appley then        apple        add := 10    end if    if add > 0 then        add -= 1        x (long + 1) := x (long)        y (long + 1) := y (long)        long += 1    end if    for i : 1 .. long        if x (0) = x (i) and y (0) = y (i) then            setup        end if    end for    for decreasing i : long .. 1        x (i) := x (i - 1)        y (i) := y (i - 1)    end for    if dir = 0 and x (0) < maxx then        x (0) += 1    elsif dir = 1 and x (0) > 0 then        x (0) -= 1    elsif dir = 2 and y (0) < maxy then        y (0) += 1    elsif dir = 3 and y (0) > 0 then        y (0) -= 1    else        setup    end ifend logicproc draw    cls    colorback (black)    Draw.Dot (applex, appley, 39)    for i : 0 .. long        Draw.Dot (x (i), y (i), 46)    end for    Font.Draw ("Score: ", 10, maxy - 18, Font.New ("mono:9"), white)    Font.Draw (intstr (long - 30), 55, maxy - 18, Font.New ("mono:9"), white)    View.Updateend drawView.Set ("graphics:256;256, offscreenonly, nobuttonbar, title:Snake")setuploop    input    logic    draw    Time.Delay (16)end loop

 

Haha I remember using turing in HS. Also nice program :)

There are 10 types of people in this world, those who can read binary and those who can't.

There are 10 types of people in this world, those who can read hexadecimal and F the rest.

~Fletch

Link to comment
Share on other sites

Link to post
Share on other sites

Haha I remember using turing in HS. Also nice program :)

Yah man, Turing was the shit back in highschool. Even though back then I had no idea what was going on :unsure:

Now I can show my comp sci teacher in highschool my mad skillz and swag.

The gameloop is bad though

Link to comment
Share on other sites

Link to post
Share on other sites

Yah man, Turing was the shit back in highschool. Even though back then I had no idea what was going on :unsure:

Now I can show my comp sci teacher in highschool my mad skillz and swag.

The gameloop is bad though

 

Haha yeah. Also I noticed you're from Ottawa too! Do you uOttawa? :P

There are 10 types of people in this world, those who can read binary and those who can't.

There are 10 types of people in this world, those who can read hexadecimal and F the rest.

~Fletch

Link to comment
Share on other sites

Link to post
Share on other sites

Haha yeah. Also I noticed you're from Ottawa too! Do you uOttawa? :P

Nope, I Carleton!!

Link to comment
Share on other sites

Link to post
Share on other sites

Here is a neat little MATLAB project I worked on not to long ago:

 

It started out with this little function (90 lines of code) that calculates beam deflection based on load, cross sectional area of an beam, support type, etc.

function beamdeflection(L,E,I,P,a)% calculating beam deflection% L= length of the beam% E=modulus of elasticity% I=cross-section% P=value of the load% a=location% initialize bb=L-a;% ask for type of beambeam=input('cantilever or simply supported?');switch beam    case 0        disp('the beam is a cantilever')    case 1        disp('the beam is simply supported')end%initialize equationsv1=@(x)-(P*x^2)/(6*E*I)*(3*a-x);dv1=@(x)-(P*x)/(2*E*I)*(2*a-x);v2=@(x)-(P*a^2)/(6*E*I)*(3*x-a);dv2=@(x)-(P*a^2)/(2*E*I);v3=@(x)-(P*b*x)/(6*L*E*I)*(L^2-b^2-x^2);dv3=@(x)-(P*b)/(6*L*E*I)*(L^2-b^2-3*x^2);v4=@(x)-(P*b*x)/(6*L*E*I)*(L^2-b^2-x^2)-((P*(x-a)^3)/(6*E*I));dv4=@(x)-(P*b)/(6*L*E*I)*(L^2-b^2-3*x^2)-((P*(x-a)^2)/(2*E*I));% set up xx=linspace(0,L,100);% set up equations as a piecewise function depending on the type of beamfor ii=1:length(x)if beam == 0    if x(ii)<=a        v(ii)=v1(x(ii));        dv(ii)=dv1(x(ii));    elseif a<=x(ii) && x(ii)<=L        v(ii)=v2(x(ii));        dv(ii)=dv2(x(ii));    end    vmax=-(P*a^2)/(6*E*I)*(3*L-a); %the negative of the equation given    thetamax=(P*a^2)/(2*E*I);            elseif beam==1    if x(ii)<=a    v(ii)=v3(x(ii));    dv(ii)=dv3(x(ii));    elseif a<=x(ii) && L>=x(ii)        v(ii)=v4(x(ii));        dv(ii)=dv4(x(ii));    end    thetaA=((P*a*b)*(L+b))/(6*E*I);    thetaB=((P*a*b)*(L+a))/(6*E*I);    if a>=b        vc=(P*b*(3*L^2-4*b^2))/(48*E*I);        x1=sqrt((L^2-b^2)/3);    elseif a<=b        vc=(P*a*(3*L^2-4*a^2))/(48*E*I);    end    vmax=-(P*b*(L^2-b^2)^(3/2))/(9*sqrt(3)*L*E*I); %negative of the equation givenendend% plot v and dv with respect to xsubplot (2,1,1)plot(x,v,'b')hold on %find where x is the most negative (maximum)index=find(min(v)==v); %this will yield at most 2 results we want the most negative of these resultsxmin=x(index);xminprime=(min(xmin)); %use min to find the most negative answerplot(xminprime,(vmax),'o')xlabel('Distance');ylabel('Deflection');%description for the 2nd line of the title contains the maximum deflection%at specific x value.str=sprintf('the maximum deflection is %.2e at x=%.2e',vmax,xminprime);title({'Deflection vs. Distance',str});grid onsubplot(2,1,2)plot(x,dv)xlabel('Distance');ylabel('Slope of Deflection');title({'Slope of Deflection vs. Distance'});grid onend
Which results in the following plot:

Lraacfj.png

There is an part two this code! It's over an hundred lines of code though, but it's basically taking my rudimentary function and cleaning it up, and adding an nicer looking GUI, where users can enter their inputs, etc. If someone is interested, ill post back with what that looks like.

▶ Learn from yesterday, live for today, hope for tomorrow. The important thing is not to stop questioning. - Einstein◀

Please remember to mark a thread as solved if your issue has been fixed, it helps other who may stumble across the thread at a later point in time.

Link to comment
Share on other sites

Link to post
Share on other sites

 

 

Well, here's my snake game :

#include <iostream>#include <cstdlib>#include <string>#include <sstream>#include <time.h>#include <vector>#include "common.h"#include "snake.h"#include "obstacles.h"#include "food.h"#include <SFML/Graphics.hpp>using namespace std;sf::Time delta_i = sf::seconds(0.3f);sf::Time delta = delta_i;bool game_over = false;int SIZE = 800;sf::RenderWindow window(sf::VideoMode(SIZE, SIZE), "Snake");direction dir;Snake snake;obstacles o;food f;Texts text;void input(direction &d){    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))    {        d.x = 1;        d.y = 0;    }    else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))    {        d.x = -1;        d.y = 0;    }    else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))    {        d.x = 0;        d.y = -1;    }    else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))    {        d.x = 0;        d.y = 1;    }}void reset(){    game_over = false;    snake.reset();    f.generatePos();}int main(){    sf::Clock clock;    while (window.isOpen())    {        sf::Event event;        while (window.pollEvent(event))        {            if (event.type == sf::Event::Closed)                window.close();        }        window.clear(sf::Color(244, 67, 54));        if(game_over)        {            ostringstream s;            s << "Your score was : " << snake.length();            text.scoreText.setStr(s.str());            if (sf::Keyboard::isKeyPressed(sf::Keyboard::R)) reset();            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) break;            text.draw();        }        else        {            input(dir);            sf::Time elapsed = clock.getElapsedTime();            if(elapsed >= delta)            {                if(snake.head()->position() ==  f.position())                {                    snake.add();                    f.generatePos();                    delta = sf::seconds(delta_i.asSeconds() - (float)snake.length()/100);                }                snake.move(dir);                clock.restart();            }            o.draw();            f.draw();            snake.draw();        }        window.display();    }    return 0;}

That is under 100 lines , but there's still a lot of other classes and headers D: , so I wouldn't say that it really fits into this thread. Also , it's C++...not exactly line friendly.

 

It's object oriented. No hard coded matrix :P .

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

from os import system as s

nextNum = None
operations = []

def getNextNumber():	
	nextNum = input(">> ")	
	operations.append(float(nextNum))
	while True:	
		print "Console Calculator by Anthony Baynham"	
		getNextNumber()	
		for i in operations:		
			print i		
			s("pause")		
			del operations[:]		
			s("cls")

Calculator in Python, doesn't like decimals unless you type .0 after every whole number but I wanted to see how little lines I could do it in.

Link to comment
Share on other sites

Link to post
Share on other sites

I'm in my first year studying informatics, so I made a bunch of small programs in the last few months. Some for school, some for my own pleasure.

Here you can find two of the latter in Python(3): a solution to the Tower of Hanoi and the 8 Queens Problem respectively.

 

#!/usr/bin/env python3class Disk:    def __init__(self,size=0): self.size = size    def __gt__(self,other):        if self.size > other.size: return True        else: return False        class Tower:    def __init__(self,maxsize=8):        self.disks = []        self.maxsize = maxsize    def push(self,disk):        if self.getLength() != 0:            if self[-1] > disk: self.disks.append(disk)            else: raise Exception("Oepsie!",self.disks[-1].size,disk.size)        else: self.disks.append(disk)            def getLength(self): return len(self.disks)    def pop(self): return self.disks.pop()    def __getitem__(self,index): return self.disks[index]    def __str__(self):        result = " " * (self.maxsize-1) + "|" + " " *(self.maxsize-1) + "\n"        for i in reversed(range(self.maxsize)):            if self.getLength() <= i: result += " " * (self.maxsize-1) + "|" + " " *(self.maxsize-1) + "\n"            else: result += " " * (self.maxsize-self.disks[i].size) + "="*(2*self.disks[i].size-1) +  " " * (self.maxsize-self.disks[i].size) + "\n"        return result                class Hanoi:    def __init__(self,n=8):        self.tower1 = Tower(n)        self.tower2 = Tower(n)        self.tower3 = Tower(n)        self.steps = 0        for i in reversed(range(self.tower1.maxsize)): self.tower1.push(Disk(i+1))                def _solve(self,source, helper, target,n):        if n > 0:            self._solve(source, target, helper,n-1)            if source:                target.push(source.pop())                self.steps += 1                print("Step: {}".format(self.steps)+"\n")                print(self)            self._solve(helper, source, target,n-1)            def solve(self):        print(self)        self._solve(self.tower1,self.tower2,self.tower3,self.tower1.maxsize)            def __str__(self):        result = ""        result1 = str(self.tower1).split("\n")        result2 = str(self.tower2).split("\n")        result3 = str(self.tower3).split("\n")        for i in range(len(result1)): result += result1[i] + "   " + result2[i] + "   " + result3[i] + "\n"        return resulthanoi = Hanoi(8)hanoi.solve()
class EightQueensProblem:    def __init__(self,n=8):        self.size = n        self.axis = []        for i in range(n):            self.axis.append([])            for p in range(n):                self.axis[i].append(0)    def __str__(self):        result = "  "+'\033[4m'+" "        for number in range(len(self.axis[0])):            result += "{} ".format(number)        result += '\033[0m' + "\n"        for row in range(len(self.axis)):            result += "{}| ".format(row)             for column in self.axis[row]:                result += "{} ".format(column)            result += "\n"        return result    def _getRow(self,row):        return self.axis[row]    def _getColumn(self,column):        result = []        for row in self.axis:            result.append(row[column])        return result    def _getDiagonalLeft(self,row,column):        result = []        while row != 0 and column !=0:            row -=1            column -=1        for i in range(self.size - column - row):            result.append(self.axis[row][column])            row += 1            column +=1        return result    def _getDiagonalRight(self,row,column):        result = []        while row != self.size-1 and column !=0:            row +=1            column -=1        for i in range(self.size - column):            result.append(self.axis[row][column])            row -= 1            column +=1        return result    def _isPosible(self,row,column):        if sum(self._getRow(row)) != 0 or sum(self._getColumn(column)) != 0 or sum(self._getDiagonalLeft(row, column)) != 0 or sum(self._getDiagonalRight(row, column)) != 0:            return False        else: return True    def solve(self,column = 0,verbose=False):        if column < self.size:            for row in range(len(self._getColumn(column))):                if self._isPosible(row, column):                    self.axis[row][column] = 1                    result = self.solve(column+1)                    if not result:                        self.axis[row][column] = 0                        continue                else: continue            if sum(self._getColumn(column)) != 1: return False            elif column != 0: return True            elif verbose == True: print(self)        else: return True            problem = EightQueensProblem()problem.solve(0,True)
Link to comment
Share on other sites

Link to post
Share on other sites

Risk attack simulator, works fairly well, not sure if I could have dropped an elif statement or not.

# this script will determine how many troops will need to be sacrificed# to take over a territory in risk givin countries the attacker owns, attackers troops available and# defenders troops available, will always use the maximum troops possible.from random import randrange# dieRoll(3) -> [5, 3, 1] :: returns list sorteddef die_roll(x):    i = 0    result_list = []    while i < x:        result_list.append(randrange(1, 7))        i += 1    result_list.sort()    result_list.reverse()    return(result_list)attackingCountries = input("How many of your countries can attack the defenders country?")attackTroops = input("How many troops do you have available to attack with?")defenceTroops = input("How many troops does the defender have available?")initAttackTroops = attackTroopswhile defenceTroops > 0 and attackTroops >attackingCountries + 1:    if attackTroops >= 3 and defenceTroops >= 2:        # Roll the dice        attackersRoll = die_roll(3)  # Attack with maximum amount of troop(s)        defendersRoll = die_roll(2)  # Defence with maximum amount of troop(s)        # First Highest Die Comparison        if max(attackersRoll) > max(defendersRoll):            defenceTroops -= 1        elif max(attackersRoll) == max(defendersRoll):            attackTroops -= 1            defenceTroops -= 1        else:  # If max(attackersRoll) < max(defendersRoll)            attackTroops -= 1        # Second Highest Die Comparison        if attackersRoll[1] > attackersRoll[1]:            defenceTroops -= 1        elif attackersRoll[1] == attackersRoll[1]:            attackTroops -= 1            defenceTroops -= 1        else:  # if attackersRoll[1] < defendersRoll[1]            attackTroops -= 1    elif attackTroops >= 3 and defenceTroops <= 2:        # Roll the dice        attackersRoll = die_roll(3)  # Attack with maximum amount of troop(s)        defendersRoll = die_roll(defenceTroops)  # Defence with maximum(1) amount of troop(s)        # First Highest Die Comparison        if max(attackersRoll) > max(defendersRoll):            defenceTroops -= 1        elif max(attackersRoll) == max(defendersRoll):            attackTroops -= 1            defenceTroops -= 1        else:  # if max(attackersRoll) < max(defendersRoll)            attackTroops -= 1        # Second Highest Die Comparison        if defenceTroops == 2:            if attackersRoll[1] > attackersRoll[1]:                defenceTroops -= 1            elif attackersRoll[1] == attackersRoll[1]:                attackTroops -= 1                defenceTroops -= 1            else:  # if attackersRoll[1] < defendersRoll[1]                attackTroops -= 1    elif attackTroops < 3 and defenceTroops == 1:        # Roll the dice        attackersRoll = die_roll(attackTroops)  # Attack with maximum amount of troop(s)        defendersRoll = die_roll(defenceTroops)  # Defence with maximum(1) amount of troop(s)        # First Highest Die Comparison        if max(attackersRoll) > max(defendersRoll):            defenceTroops -= 1        elif max(attackersRoll) == max(defendersRoll):            attackTroops -= 1            defenceTroops -= 1        else:  # if max(attackersRoll) < max(defendersRoll)            attackTroops -= 1    elif attackTroops < 3 and defenceTroops >= 2:        # Roll the dice        attackersRoll = die_roll(attackTroops) # Attack with maximum amount of troop(s)        defendersRoll = die_roll(2) # Defence with maximum(1) amount of troop(s)        # First Highest Die Comparison        if max(attackersRoll) > max(defendersRoll):            defenceTroops -= 1        elif max(attackersRoll) == max(defendersRoll):            attackTroops -= 1            defenceTroops -= 1        else:  # if max(attackersRoll) < max(defendersRoll)            attackTroops -= 1        # Second Highest Die Comparison        if attackersRoll[1] > attackersRoll[1]:            defenceTroops -= 1        elif attackersRoll[1] == attackersRoll[1]:            attackTroops -= 1            defenceTroops -= 1        else:  # if attackersRoll[1] < defendersRoll[1]            attackTroops -= 1    else:  #Never to be used...        continue    print("{0} Attacking Troops Remain... {1} Defending Troops Remain.").format(attackTroops, defenceTroops)if defenceTroops == 0:    print("You have taken over the enemies territory! {0} troops have been lost, {1} remain.").format(initAttackTroops - attackTroops, attackTroops)

Looking for a Programming Project take a look here!

http://linustechtips.com/main/topic/407332-looking-for-a-project-idea-start-here/

Link to comment
Share on other sites

Link to post
Share on other sites

A magic 8 ball simulator

#include <iostream>#include <random>#include <ctime>#include <string>using namespace std; const int ARRAY_LENGTH = 20;string question;string eightBallAns[ARRAY_LENGTH] = { "Signs point to yes", "Yes", "Reply hazy, try again", "Without a doubt", "My sources say no", "As I see it, yes", "You may rely on it", "Concentrate and ask again", "Outlook not so good", "It is decidedly so", "Better not tell you now", "Very doubtful", "Yes - definitely", "It is certain", "Cannot predict now", "Most likely", "Ask again later", "My reply is no", "Outlook good", "Don't count on it" };bool prgExit = false;int main(){	srand(time(NULL));		cout << "********************************MAGIC 8 BALL************************************\n\n";	cout << "Developed by David Kim\n";	while (true)	{		cout << "\nAsk a yes or no question : ";		getline(cin, question);				if (question.compare("exit") == 0)		{			prgExit = true;		}		if (question.compare("") != 0 && question.compare("exit") != 0)		{			cout << endl << eightBallAns[rand() % ARRAY_LENGTH] << endl;		}	}	system("PAUSE");	return 0;} 

Wrote a similar program months ago in C# , but it was way over 100 lines. Optimized in C++

Did my post help you? Then make sure to rate it!

Check out my post on symbolic links! || PSU ranking and tiers || Pokemon Thread

 

Link to comment
Share on other sites

Link to post
Share on other sites

Cat program in Batch (CMD language):

@[member=Echo] offREM This code has 14 lines.:xclstitle Cat programecho Type anything except spacesset %input%==Insert a cat song here:goto n:nclsecho %input%pause>nulgoto x

Ryzen 7 3700X / 16GB RAM / Optane SSD / GTX 1650 / Solus Linux

Link to comment
Share on other sites

Link to post
Share on other sites

thread about different programs turns in to a thread about one program. not that I'm complaining 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...
  • 2 weeks later...
On 12/26/2015 at 11:50 AM, NunoLava1998 said:

 

Cat program in Batch (CMD language):


@[member=Echo] offREM This code has 14 lines.:xclstitle Cat programecho Type anything except spacesset /p input=Insert a cat song here: clsecho %input%pause>nulgoto x

 

Welcome to batch programming newbie, anyway I fixed your code up there to make it work. 

 

I made a simple batch program here that Factorizes any number. Remember their is a limit of 32 bit integers (31 with the first bit being the sign + or -).

It also stores the factors into a text file called Factorizer.txt, make sure you have permissions in the location where you save the batch file.

@[member=Echo] offtitle Facotrizersetlocal enableDelayedExpansion:begclsset "fac=0"set /p numb=Number that will be factored:if !numb! EQU 1 echo 1if not defined numb goto :begecho Factors of !numb! >>Factorizer.txt:primefactorset "tem=%numb%"if "%tem%" EQU "1" goto :factoredcall :check 2call :check 3set "k=1":primesset /a "rr=(6*%k%)-1"set /a "tr=(6*%k%)+1"set /a "pr=%rr%*%rr%"if %pr% GTR %tem% call :addfactor %tem% & goto :factoredcall :check !rr!call :check !tr!set /a "k+=1"goto :primes:factoredfor /l %%i in (1,1,%fac%) do set "use%%i=0":nextfactorset "multi=1"for /l %%i in (1,1,%fac%) do call :multi !fac%%i! %%iecho %multi% >>Factorizer.txtecho %multi%set /a "use1+=1"for /l %%i in (1,1,%fac%) do call :fixuse %%igoto :nextfactor:multi call :expon %~1 !use%~2! mset /a "multi*=%ansm%" goto :eof:fixuseif !use%~1! LEQ !facval%~1! goto :eofset /a "use%~1=0"set /a "nxt=%~1+1"if !nxt! GTR %fac% goto :endset /a "use%nxt%+=1"goto :eof:endecho Done!pause >nulgoto :reset:exponset "a=%~1"set "b=%~2"set "in=%~3"set "eq=%a%"if "%b%" EQU "0" set "ans%in%=1" & goto :eofif "%a%" EQU "0" set "ans%in%=0" & goto :eofif "%b%" EQU "1" set "ans%in%=%a%" & goto :eoffor /l %%i in (2,1,%b%) do (	set "eq=!eq!*%a%")set /a "ans%in%=%eq%"goto :eof:addfactorfor /l %%i in (1,1,%fac%) do (	if "!fac%%i!" EQU "%~1" set /a "facval%%i+=1" & goto :eof)set /a "fac+=1"set "fac%fac%=%~1"set "facval%fac%=1"goto :eof:checkset /a "rem=%tem%%%%~1"if "%rem%" EQU "0" call :addfactor %~1 & set /a "tem/=%~1" & goto :checkif "%tem%" EQU "1" goto :factoredgoto :eof:resetfor /l %%r in (1,1,%fac%) do (	set "fac%%r="	set "facval%%r=")goto :beg

If you want to know how to install it its fairly simple, just paste the above code into a .txt file and save it with the file extension .bat

A riddle wrapped in an enigma , shot to the moon and made in China

Link to comment
Share on other sites

Link to post
Share on other sites

It´s nothing special and doesn´t serve a greater purpose other than writing a square, a triangle and a christmas tree in the console but its something and under 100 lines :D

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Christbaum{    class Program    {        static void Main(string[] args)        {            #region Dreieck                //Dreieck!            Console.ReadLine(); //wartet auf Eingabe                string x = "x"; //Definiert die Variable x als x                for (int i = 0; i < 10; i++) //Gibt die variable x aus und fügt dann noch ein x zur variable dazu.                {                    Console.WriteLine(x); //schreibt variable x                    x = x + "x"; //vergrößert variable x                }                Console.ReadLine(); //wartet auf eingabe                        #endregion            #region Viereck                //Viereck                string y = "x"; //definiert variable y als string und fügt x hinzu.            Console.Write("Zahl:"); //Schreibt: Zahl:            int zahl = Convert.ToInt32(Console.ReadLine()); //definiert die variable Zahl als Integer und fügt die Eingabe vom User der Variable hinzu             for (int v = 1; v < zahl; v++) //Looped Zahl mal            {                 y = y + ("x"); // fügt zur variable y ein x hinzu            }            for (int z = 0; z < zahl; z++) //looped Zahl mal            {                Console.WriteLine(y); //Schreibt die Variable y            }            Console.ReadLine(); //wartet auf Eingabe            #endregion            #region Christbaum            #region Äste            int p = 0;                                  //definiert die variable p als int und fügt den wert 0 hinzu            string ka = "";                             //definiert die variable ka als leerzeichen " "            for (int k = 0; k < 3; k++)                 // erschafft die 3 Dreiecke vom Christbaum            {                string m = "x" + ka;                    //setzt m immer auf x zurück und fügt dann ka dazu, sodass die dreiecke immer größer beginnen.                int Leertasten = 10 - p;                //Zieht p von Leertasten ab sodass pro Dreieck die x nach links rücken                 int zahlleertst = 10 - p;               //Um Die Leertasten wieder auf eine gewisse Anzahl zu setzen.                for (int d = 0; d < 7; d++)             //Jedes Dreieck besteht aus 7 Lagen                {                    for (; Leertasten > 0; Leertasten--)//Solange Leertasten > 0 wird " " geschrieben. Das rückt das x hinter den leertasten vom Rand weg.                    {                        Console.Write(" ");             // Schreibt Leertasten.                    }                    Console.WriteLine(m);               // Schreibt die x                    zahlleertst--;                      // 1 Leertaste weniger damit das x weiter nach rechts rückt                    Leertasten = zahlleertst;           //speichert zahllertasten in Leertasten, sodass weniger " " vor die x kommen.                    m = m + "xx";                       // vergrößert m = x zu m = xxx usw.                }                p = p + 1;                              //vergrößert p mit jedem durchlauf                ka = ka + "xx";                         //vergrößert ka mit xx bei jedem durchlauf            }            #endregion            #region Stamm            string t = "x";                             //definiert t als string und fügt "x" zu t inzu            string j = "         ";                     //9 Leertasten setzen den Stamm in die Mitte            for (int v = 1; v < 3; v++)                 //Macht den Stamm 3 x dick            {                t = t + ("x");            }            for (int z = 0; z < 3; z++)                 //macht den Stamm 3 x hoch            {                Console.WriteLine(j+t);                 //schreibt den x j leertasten vom rand enfernt            }            Console.ReadLine();                         //wartet auf eingabe            #endregion            #endregion        }    }}

it´s commented in german because I coded this 3 years ago in school ;)

System:
CPU: I7-3610QM @ 2.3 GHz | Motherboard: something with chips | RAM: 8 Gb of something | GPU: AMD HD 7600M | Case: Something made out of plastic | Storage: Toshiba MQ01ABD075 750GB | PSU: something external | Display(s): something glowing | Cooling: jet engine | Keyboard: hama something | Mouse: Logitech something | Sound: Traktor Kontrol S2 as soundcard, AKG K500 Headphones | Operating System: Windoof 10

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...

Below is a C# console program that scans for new files in a source directory(directory you place .exe in) and moves them to a specified destination directory.  It does validation checking to make sure that destination exists, as well as it can filter out certain extensions by changing line 65. I use this to transfer JDownloader files to my home NAS. The issue is that JDownloader cannot write to my network drive because of the type of permissions I am using. Instead, I place this .exe in the downloads directory on my local disk then I have it transfer all completed files to my NAS media drive. As you can see I am filtering .part files and .exe to prevent the program from moving files before they are done and to prevent it from throwing an exception from trying to move itself haha. PM me if you have any questions and I can explain it better. I also have a lot of fluff in it like countdowns etc, if you want the smallest program possible this could easy be cut in half. 

using System;
using System.IO;

namespace DownloadHelper
{
    class Program
    {
        static void Main(string[] args)
        {
            int count = 0;
            bool dirFound = false;
            string currentDirectory = Directory.GetCurrentDirectory();
            string copyDirectory = String.Empty;

            while(!dirFound)
            {
                Console.WriteLine("Current download directory set to: " + currentDirectory);

                Console.WriteLine("Please input path to desired download directory.");
                copyDirectory = Console.ReadLine();

                Console.WriteLine("Checking if valid directory...");
                if(Directory.Exists(copyDirectory))
                {
                    Console.WriteLine(copyDirectory + " is valid.");

                    Console.WriteLine("Starting to scan in 3...");
                    System.Threading.Thread.Sleep(1000);
                    Console.WriteLine("Starting to scan in 2...");
                    System.Threading.Thread.Sleep(1000);
                    Console.WriteLine("Starting to scan in 1...");
                    System.Threading.Thread.Sleep(1000);

                    dirFound = true;
                }
                else
                {
                    Console.WriteLine(copyDirectory + " is not valid!");
                }
            }

            while(true)
            {
                count++;

                switch(count)
                {
                    case 1:
                        Console.WriteLine("Scanning Folder.");
                        break;
                    case 2:
                        Console.WriteLine("Scanning Folder..");
                        break;
                    case 3:
                        Console.WriteLine("Scanning Folder...");
                        count = 0;
                        break;
                }
                //Get all the files in directory
                string[] filePaths = Directory.GetFiles(currentDirectory);
                //Loop through and move all the ones we want to new directory
                for(int i = 0; i < filePaths.Length; i++)
                {
                    string fileName = Path.GetFileName(filePaths[i]);
                    if(Path.GetExtension(fileName) != ".part" && Path.GetExtension(fileName) != ".exe")
                    {
                        Console.WriteLine("Attempting to move: " + filePaths[i] + " to: " + copyDirectory + "/" + fileName);
                        File.Move(filePaths[i], copyDirectory + "/" + fileName);
                    }
                }

                System.Threading.Thread.Sleep(1000);

                Console.Clear();
            }
        }
    }
}

dhja

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

A savings calculator I made in C for a game I'm playing.

#include	<stdio.h>
long int	days(long int,long int);
long int	amount(long int,int);
int	main()
{
	int i=1,select,iamount,tamount,paychecks;
	while(i>-1){
		printf("Please select one of the two options:\n1. Calculate amount after X paychecks\n2. Calculate paychecks to certain amount\n");
		scanf("%d",&select);
		printf("Enter initial amount:");
		scanf("%ld",&iamount);
		if(select==1){
			printf("Enter amount of paychecks:");
			scanf("%d",&paychecks);
			printf("Total amount after %d paychecks: %ld\n",paychecks,amount(iamount,paychecks));
		}
		else if(select==2){
			printf("Enter target amount:");
			scanf("%ld",&tamount);
			printf("Total paychecks until %ld is %d\n",tamount,days(iamount,tamount));
		}
		else
			printf("ERROR: Invalid input.\n");
	}
	return 0;
}
long int days(long int a, long int ta)
{
	int i,sum=0;
	while(a<=ta){
		a+=a*0.005;
		sum++;
	}
	return sum;
}
long int amount(long int a, int p)
{
	int i;
	for(i=1;i<=p;i++)
		a+=a*0.005;
	return a;
}

 

Toxic Ruski

CPU: R9 5900X

COOLER: Noctua NH-D15

MOBO: X570 Aorus Pro (rev 1.2)

RAM: Corsair Vengeance LPX 4x8GB

GPU: Gigabyte Aorus Xtreme Edition 1080Ti

STORAGE: Samsung 960 EVO 250GB, HyperX Savage SSD,WD 2TB Black, WD 3TB Green 5400RPM

PSU: Corsair RM750x

CASE: NZXT H440 Razer

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


×