r/badcode • • May 11 '22

python It works but.... NSFW

Post image
475 Upvotes

57 comments sorted by

119

u/nekokattt May 11 '22

just make a list of tuples of the coordinates you want to check and iterate over it.

coords = [
    (0, 1, 2),
    (0, 4, 8),
    (1, 4, 7),
    ...
]

win = any(
    grid[a] == grid[b] and grid[b] == grid[c]
    for a, b, c in coords
)

Then look into f-strings instead of string concatenation.

48

u/Espiring May 11 '22

This was copilots answer to a tictoctoe game

33

u/nekokattt May 11 '22

this is why i dont use copilot lol

25

u/[deleted] May 11 '22

I find copilot mostly useless, but it surprises me with something nice maybe once every few weeks

9

u/Leamir May 12 '22

I use it instead of stack overflow, when it’s something simple

8

u/Cerus_Freedom May 12 '22

For some languages, it can produce really phenomenal results. Python, it usually has a pretty good answer for well defined problems. The problem with this scenario is that it was trained by an absolute ton of people learning to program by making the same thing.

It's about 50/50 whether it saves me a second of typing on any given suggestion. The deeper into the guts of something I am, the less likely it is to be useful. With Dart, it tends to mangle syntax and leave me doing more work than if I'd just finished typing.

3

u/MKBSRC May 12 '22

Copilot can lead you in the right direction but ita not enough to rely on. I hate when people try to promote it as know all and the job killer lol

2

u/[deleted] May 12 '22

I find that I spend more time fighting against it trying to autocomplete imports with nonsense than being helped by it

2

u/MKBSRC May 12 '22

Exactly, if you have no idea what you’re doing it will leave you with stinky code

3

u/RCoder01 May 12 '22

For me, copilot has been mostly a very smart auto-complete. Sometimes as I'm writing a method header, it'll just complete the entire function exactly as I need it, often taking context in from the rest of the file or even occasionally from surrounding files. It's been totally fine just running in the background and helping occasionally with semi-repetitive tasks.

4

u/kristallnachte May 12 '22

It's at least as good as having the average coder help you.

6

u/analogic-microwave @SpringDoSomeBlackMagicStuffPls May 12 '22

Copilot is still a junior dev.

45

u/Rene_Z May 11 '22
grid[a] == grid[b] == grid[c]

as OP did it totally works in Python

3

u/havens1515 May 12 '22

What if those 3 locations are empty? Would that also be a situation where they are equal?

9

u/Rene_Z May 12 '22

Well yes, it's exactly equivalent to grid[a] == grid[b] and grid[b] == grid[c], so if all values are 0, the condition is True.

3

u/havens1515 May 12 '22

Seems like a problem...

2

u/[deleted] May 20 '22

Why is it a problem? They are equal, so result is True.

3

u/havens1515 May 20 '22

If that's not a good enough explanation, the way this code will work is:

Game starts

Player 1 makes a move

Player changes to 2

Game displays "Player 2 wins!"

3

u/[deleted] May 20 '22 edited May 20 '22

So, grid[a] != 0 and grid[b] != 0 and grid[c] != 0

ETA: ↑ This code checks that none of the variables are equal to zero

5

u/havens1515 May 20 '22

But also, that's not the only problem with this code. It changes active player before displaying the winner, which means it will display the wrong winner. And I'm sure there's more that I'm missing / forgot.

3

u/havens1515 May 20 '22

No, you'd need

If(grid[a] == grid[b] && grid[b] == grid[c] && grid[a] != 0)

3

u/[deleted] May 20 '22

By the way, I think there's a simpler way to do this

→ More replies

2

u/havens1515 May 20 '22

Exactly. So if no move has been made, win = true. That's a problem

3

u/kristallnachte May 12 '22

Or implement a simple pathfinding algo.

46

u/MurdoMaclachlan public boolean isInt(int i) { return true; } May 11 '22

Image Transcription: Code


while true:
    try:
        choice = int(input("Enter a number: "))
        if choice in board:
            board[choice] = player
            break
        else:
            print("Invalid choice")
    except ValueError
        print("Invalid choice")
if player == 1:
    player = 2
else:
    player = 1
if board[0] == board[1] == board[2]:
    win = True
elif board[3] == board[4] == board[5]:
    win = True
elif board[6] == board[7] == board[8]:
    win = True
elif board[0] == board[3] == board[6]:
    win = True
elif board[1] == board[4] == board[7]:
    win = True
elif board[2] == board[5] == board[8]:
    win = True
elif board[0] == board[4] == board[8]:
    win = True
elif board[2] == board[4] == board[6]:
    win = True
elif 0 not in board:
    win = True
if win:
    print("\n")
    print("   |   |")
    print(" " + str(board[0]) + " | " + str(board[1]) + " | " + str(board[2]))
    print("   |   |")
    print("-----------")
    print("   |   |")
    print(" " + str(board[3]) + " | " + str(board[4]) + " | " + str(board[5]))
    print("   |   |")
    print("-----------")
    print("   |   |")
    print(" " + str(board[6]) + " | " + str(board[7]) + " | " + str(board[8]))
    print("   |   |")
    print("\n")
    if player == 1:
        print("Player 1 wins!")
    else:
        print("Player 2 wins!")

I'm a human volunteer content transcriber and you could be too! If you'd like more information on what we do and why we do it, click here!

30

u/SpanVagyTeso May 11 '22

Good human.

25

u/frugalerthingsinlife May 12 '22

Honestly. this is exactly how I make silly little terminal games in python. very few functions. mixing mvc. write as much as you can in one go and fix the problems as you find them. TDD be damned.

19

u/waterbyseth May 12 '22

To be fair, there are only 8 win conditions and each one only takes up one line here.

I recently had to write tic tac toe in IEC structured text for school which has no tuples, iterators, or anything to make it more consice and this was pretty much the only way.

18

u/randomsmiteplayer May 11 '22

I’m looking at it and there’s an ID statement for player == 1. Then immediately afterwards, assign 1 to player. Redundant isn’t it? Am I missing something?

28

u/jomanning May 11 '22

Yes you’re missing something. it’s toggling between player 1 and 2.

If player 1 -> become player 2 Else -> become player 1

7

u/randomsmiteplayer May 12 '22

Yup I see it now. I'm the badcode now!

3

u/EvilStevilTheKenevil May 12 '22

A neat way of avoiding this if statement would be to have player_1 == 1 and player_2 == -1. At the end of each turn, multiply the number by -1.

I'd imagine it doesn't make much of a difference here (I mean if you really cared about performance you wouldn't be using Python), but "if" statements can screw up pipelining, which, for not-so-trivial programs, can dramatically slow down execution.

2

u/MrJankles May 30 '22

Easier than the solution I was thinking of

player = (player+1) % 2

1

u/EvilStevilTheKenevil May 30 '22

This also works, but the modulus operator involves division. If the compiler doesn't recognize %2 as logically equivalent to a bitwise operation on the least significant bit then this might slow things down.

 

Multiplication is as simple as several adders chained together with some bit-shifting for their inputs, and you could somewhat easily implement this algorithm entirely in hardware such that any two 64 bit ints could be multiplied together in a single cycle (floats would be slightly more complicated, but more or less the same).

Meanwhile, division is very complicated (relative to the other 3 fundamental arithmetic operations you learn in grade school, anyway), and there are many different algorithms out there which can get the job done. The naive approaches converge linearly, and some of the more interesting ones do it quadratically, but in any case division is likely to be a multi-cycle operation. In other words, slow.

1

u/LuckyNumber-Bot May 30 '22

All the numbers in your comment added up to 69. Congrats!

  2
+ 64
+ 3
= 69

Click here to have me scan all your future comments.
Summon me on specific comments with u/LuckyNumber-Bot.

1

u/RoLoLoLoLo May 12 '22

It works but....

Does it though? Exercise to the reader: what happens in case of a tie? What happens when two players enter the same number?

2

u/Espiring May 12 '22

It rolls a number between 0 and 1. The player who gets closest to it has their C directory deleted

3

u/Abstal_223 May 12 '22

OP got that yandere dev type code

4

u/trutheality May 12 '22

According to this in the event of a tie the last player to go wins?

1

u/maxbirkoff May 12 '22

yeah; I think the elif 0 not in board should not be a"win" case.

1

u/RFC793 May 12 '22

Err, yeah. That last if shouldn’t set win=True but rather set a tie condition.

2

u/[deleted] May 12 '22

Why is this nsfw

7

u/AstronautInTheLotion May 12 '22

my guy fucked up the code

1

u/kristallnachte May 12 '22

But what did it cost?

1

u/SlyWigga May 12 '22

You could cut the corners here and there and make the code prettier, but on the other hand its not like tic tac toe is going to change its rules anytime soon, and its readable enough

1

u/havens1515 May 12 '22

Does it work, though?

It looks like value for each position on the board defaults to 0, than changes to 1 or 2 depending on which player put a mark in that location.

At the beginning of the game, all spaces would be set to 0, which would mean that the statement checking for a win would be valid right from the beginning.

Unless I'm missing something here...

1

u/Beach-Appropriate May 13 '22

The memories! I had a uni lab for tic tac toe. It mentioned there would be a surprise announcement a week before the due date for bonus marks. The announcement was that for bonus marks we had to submit 4x4(winning 4 in a row) and 5x5 (winning 3 in a row) implementation

If you had built it like the above the code didn’t scale well at all. If you had built it well it was basically just changing some constants

1

u/TheGlamorousWonkyApe May 22 '22

can see why it was marked nsfw

1

u/Kakao_Trees May 12 '22

eh, beginner code gotta start with this, not too bad for a new guy

1

u/Tm1lly May 12 '22

Lolol whoever made this not safe for work 😂

0

u/[deleted] May 13 '22

Any Python program that uses input() is a sign that it's a homework / class assignment. It's just someone learning the language / learning to program in general. Not really funny.

2

u/Espiring May 13 '22

How would you get it instead then? If you want a player input, you ask for input

1

u/[deleted] May 13 '22

If you want a proper terminal UI, you'd be using curses at least, or maybe termbox or prompt_toolkit.

There are very few situations in any application development where you would do the kind of interaction with user that's implied by input() -> print(). If you need to read stdin, then you'll invariably end up at least accessing sys.stdin instead of calling input() because of issues with buffering, or maybe wanting realdline-like functionality, or displaying completion suggestions... input() is too simplistic for real work.