Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
moosferatu
Jan 29, 2020
They're probably trying to get you to write it using recursion. For example, have a function that takes as input the current player and scores, and then execute your turn logic. If a player has won return the results, otherwise call the same function again with the updated values.

Aside, when a 1 is rolled do you really accumulate the turn score and not go bust? If so, why would you ever not roll?

Adbot
ADBOT LOVES YOU

Tempora Mutantur
Feb 22, 2005

moosferatu posted:

They're probably trying to get you to write it using recursion. For example, have a function that takes as input the current player and scores, and then execute your turn logic. If a player has won return the results, otherwise call the same function again with the updated values.

that's the right interpretation

or be an rear end in a top hat and write it as an event-driven score system using a single for loop which has its value change to the current highest score after each iteration; each iteration emits a currentPlayerRoll event handled by a currentPlayerRollHandler which does all the score/turn keeping and has a handy function that also updates the variable tracking the for loop and current player so the game ends when a single unbroken for loop runs to completion to 100 and it's completely over-engineered in response to "no while loops"

RPATDO_LAMD
Mar 22, 2013

🐘🪠🍆
Yeah those requirements definitely point towards the prof wanting you to use a specific technique, probably based on whatever's been in the lectures recently.

Avoiding loops entirely by using recursion is probably the easiest way to do it.
Still I'd be kinda surprised if a prof handed an assignment like that out without specifically saying "use recursion", especially with the weird restriction that for loops are ok but while loops are not.

Other notes if you wanna take a non-recursive approach:
Instead of break, you can always get out of a loop with return. of course this requires separating each loop out into its own function instead of putting them all in one big one.
If you're a real sicko you can do it by raising and catching exceptions too! (Don't do that.)

if you want an infinite loop without using while, you can use generator functions, for example
Python code:
import itertools
for x in itertools.repeat(0):
    print(f"x is {x}. I'm looping forever!")
will print "x is 0. I'm looping forever!" infinite times until you kill it.

But this is also kinda stupid and is basically just a dumber way to write a while loop. Unless your teacher specifically wanted you to write/use a generator function just for the sake of writing one, so again I guess check the recent lecture topics?

Tempora Mutantur posted:

that's the right interpretation

or be an rear end in a top hat and write it as an event-driven score system using a single for loop which has its value change to the current highest score after each iteration; each iteration emits a currentPlayerRoll event handled by a currentPlayerRollHandler which does all the score/turn keeping and has a handy function that also updates the variable tracking the for loop and current player so the game ends when a single unbroken for loop runs to completion to 100 and it's completely over-engineered in response to "no while loops"

in python, unlike C, you can't overwite the variable controlling a for loop. Every loop is basically range-based for.

Though you can still hack around it with a generator that depends on some external state, like like this one made with iter:
Python code:
done = False
def is_done(): 
	return done

sentinel_value = True
# this will iterate by calling is_done() over and over until it returns the sentinel value
is_it_done_yet_generator = iter(is_done, sentinel_value)
for _ in is_it_done_yet_generator:
	# do something

	if .... :
		done = True # break the loop
that's an extra dumb way to get around using break though so only use it if you feel like being a clever rear end in a top hat

RPATDO_LAMD fucked around with this message at 04:30 on May 4, 2024

leper khan
Dec 28, 2010
Honest to god thinks Half Life 2 is a bad game. But at least he likes Monster Hunter.
code:

for (;;) {
}

cheetah7071
Oct 20, 2010

honk honk
College Slice
every time I've tried to use recursion in a non-toy piece of code I've immediately run out of stack space and been forced to rewrite it as a while loop lol

mystes
May 31, 2006

cheetah7071 posted:

every time I've tried to use recursion in a non-toy piece of code I've immediately run out of stack space and been forced to rewrite it as a while loop lol
It works better in languages with tail call optimization

RPATDO_LAMD
Mar 22, 2013

🐘🪠🍆
also depends on what exactly you're doing, like recursively walking a tree or doing any kind of binary search thing will only use log(n) stack space

KillHour
Oct 28, 2007


I've been doing a lot of work with data-driven execution in shaders and let me tell you, not having a call stack at all breaks you in ways I can't even describe.

I can flatten a directed acyclic graph into a for loop in my sleep. Structs? Maybe if you don't care about cache coherency. We only do arrays of 4 component vectors here, buddy!

Adbot
ADBOT LOVES YOU

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

A Festivus Miracle posted:

Hey Goons, your gracious assistance please.

So, I wrote a game of Pig, which is a dice game in which two players roll a dice, and then add that dice roll to their score. First to 100 wins. The catch is, if you roll a one, your turn ends and the turn switches to Player 2.
For ease of testing, I set the win condition for the code at 30.

This was for an assignment. My professor said 'no while loops' so I refactored the code into two long for loops. And of course, professor says "we don't break out of loops in this class". So, uh. Here's the code

pre:
#this program simulates a game of pig

import random
import time

player_one_score = 0
player_two_score = 0
current_player = "Player One"

for game_round in range(1, 101):#using an extremely long for loop to simulate 100 rounds
    print(f"It's {current_player}'s turn.")
    turn_score = 0

    for roll_count in range(40): #going to be randomly extremely statistically unlikely to reach this limit
        roll = random.randint(1, 6)
        print(f"{current_player} rolls a {roll}")
        time.sleep(1)#for ease of play

        if roll == 1:
            print("You rolled a 1. Switching to the other player's turn.")
            time.sleep(1)
            if current_player == "Player One":
                player_one_score += turn_score
                current_player = "Player Two"
            else:
                player_two_score += turn_score
                current_player = "Player One"
            break
        else:#if player doesn't roll a one, asks user if they want to roll again
            turn_score += roll
            print(f"{current_player}'s score: {player_one_score + turn_score if current_player == 'Player One' else player_two_score + turn_score}")

        choice = input("Roll again? (y/n): ").lower()#lower to filter input
        if choice == 'n':#not a super fan of this, but it works
            if current_player == "Player One":
                player_one_score += turn_score
                current_player = "Player Two"
            else:
                player_two_score += turn_score
                current_player = "Player One"
            break

    if player_one_score >= 30 or player_two_score >= 30:#from 100 to 30 so this doesn't take a super long time
        break

if player_one_score >= 30:
    print(f"Congratulations! Player One wins with a score of {player_one_score}")
if player_two_score >= 30:
    print(f"Congratulations! Player Two wins with a score of {player_two_score}")
This, well, sucks, but I'm working a full time job now so, I didn't have a super huge amount of time to dedicate to this. I'm not entirely sure how to replace the break statements without breaking the loops and I would appreciate some pointers in that direction.

As others mentioned, figure out what your professor is trying to get the class to do and do that. This is an extremely dumb way to try to teach people to use recursion if that is indeed the case; there's so many better examples that aren't terrible!

Also, saying "we don't use break statements" makes me want to say "ok cool,


code:

finish = [0]
for i in finish
  finish.append(0)
  ...
  if (we would break here)
    finish.pop()
    continue

  ...


I'm not using break here or while loops! We're good, right?" :fuckoff:

Volmarias fucked around with this message at 07:21 on May 4, 2024

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply