Python Series Part 12: Example Game

Jarret B

Well-Known Member
Staff member
Joined
May 22, 2017
Messages
377
Reaction score
445
Credits
14,054
In this article, we will put a lot of the previous articles into use to make a Yahtzee style game as we did for BASH. This is the same game design, just in the Python language.

There are a few differences in the logic, since there are different ways to handle logic flow in Python.

Code

I’ll include some code here and there, but I’ll attach the full code at the end for you to download. Simply rename the 'txt' file to 'py'. Most of the code will look similar to the BASH code and the flow is the same.

One major difference is that I removed the function for ‘sortdice’ and replaced the function call with the command ‘roll.sort()’. The built-in function will sort the named array, in this case the array is ‘roll’. By default, this sorts the array in ascending order.

Another place, I remove duplicate array elements by placing the list into a ‘set’. A ‘set’ by definition has no duplicates. This gives us the unique values in the array. This can be useful in the detection of a ‘Small Straight’ or ‘Large Straight’.

Code:
def removedups():
    global list
    list = set()
    x = range(1,6)
    for y in x:
        p = roll[y]
        list.add(p)
    return list

Here, we are moving the elements from the array ‘roll’ into ‘list’

Code:
case 'J': # small straight
    list = getdielist()
    list1 = removedups()
    if ((1 in list1) and (2 in list1) and (3 in list1) and (4 in list1)) or ((2 in list1) and (3 in list1) and (4 in list1) and (5 in list1)) or ((3 in list1) and (4 in list1) and (5 in list1) and (6 in list1)):
        tally = 30
    card[10] = tally

Once we get the list back without the duplicates, we can check for the existence of 4 consecutive numbers on the list. The numbers we are looking for are ‘1,2,3,4’, ‘2,3,4,5’ or ‘3,4,5,6’. If we find one of these four consecutive numbers, then we can set the value of the roll to ‘30’ or leave it at ‘0’. The same is true for the large straight, except we check for five consecutive numbers: ‘1,2,3,4,5’ or ‘2,3,4,5,6’.

The main section of code is:

Code:
#Main Loop
screensize()
initialize()
showcard()
game = 13
while game > 0:
   
Python 12 – Example Game

In this article, we will put a lot of the previous articles into use to make a Yahtzee style game as we did for BASH. This is the same game design, just in the Python language.

There are a few differences in the logic, since there are different ways to handle logic flow in Python.

Code

I’ll include some code here and there, but I’ll attach the full code at the end for you to download. Most of the code will look similar to the BASH code and the flow is the same.

One major difference is that I removed the function for ‘sortdice’ and replaced the function call with the command ‘roll.sort()’. The built-in function will sort the named array, in this case the array is ‘roll’. By default, this sorts the array in ascending order.

Another place, I remove duplicate array elements by placing the list into a ‘set’. A ‘set’ by definition has no duplicates. This gives us the unique values in the array. This can be useful in the detection of a ‘Small Straight’ or ‘Large Straight’.

[code]def removedups():
    global list
   list = set()
   x = range(1,6)
   for y in x:
      p = roll[y]
      list.add(p)
   return list

Here, we are moving the elements from the array ‘roll’ into ‘list’

Code:
case 'J': # small straight
   list = getdielist()
   list1 = removedups()
   if ((1 in list1) and (2 in list1) and (3 in list1) and (4 in list1)) or ((2 in list1) and (3 in list1) and (4 in list1) and (5 in list1)) or ((3 in list1) and (4 in list1) and (5 in list1) and (6 in list1)):
      tally = 30
   card[10] = tally

Once we get the list back without the duplicates, we can check for the existence of 4 consecutive numbers on the list. The numbers we are looking for are ‘1,2,3,4’, ‘2,3,4,5’ or ‘3,4,5,6’. If we find one of these four consecutive numbers, then we can set the value of the roll to ‘30’ or leave it at ‘0’. The same is true for the large straight, except we check for five consecutive numbers: ‘1,2,3,4,5’ or ‘2,3,4,5,6’.

The main section of code is:

Code:
#Main Loop
screensize()
initialize()
showcard()
game = 13
while game > 0:
   turninit()
   rollnow = 0
   rollcount = 1
   breakoutnow = 0
   while (rollcount <= 3 ) and (breakoutnow == 0):
      rollnow = 0
      rolldice()
      showdice()
      showrollcount()
      makeinstr()
      if (rollcount == 3):
         count = range(1,6)
         for i in count:
            reroll[i] = 0
            showdice()
            makelastinstr()
         while (rollnow == 0):
            valid = 0
            inp1 = getuserinput()
            checkinput(inp1)
            if (breakoutnow == 1):
               rollnow = 1
               break
            rollcount = rollcount + 1
            if (rollcount == 4):
               breakoutnow = 1
               rollnow = 0
            if (breakoutnow == 1):
               rollcount = 4
               break
rollcount = 0
subtotal()
grandtotal()
game = game - 1
os.system('clear')
print (f"You finished your game with a score of {gtotal}")

Most of this should be straightforward from the BASH version of the game.

We set the screen size to a minimum size to handle the score card if it is smaller than needed. If the screen size is bigger than needed, then we leave it alone.

Next, we initialize some variables that we use for checking input, as well as the array containing the dice images.

The last function we call for the setup we perform is to display the scorecard on the screen in the initial settings.

Next, we set a variable named ‘game’ to a value of ‘13’. There are 13 choices to fill in the score card before we complete the game.

We then perform a loop while the variable ‘game’ is greater than ‘0’. Within this loop, we allow three dice rolls and then force a selection of an available choice. After we make a choice for scoring, we decrement the variable ‘game’ by one.

During the game play, we set valid scores and keep score for both the upper choices and the lower choices. We combine these two areas to make a grand total. Once the use completes all 13 choices, the flow exits the loop.

Outside the loop, the code clears the screen and displays the final score.

I’m hoping the previous articles covered enough information that you can understand the coding for the game.

Functions

There are 18 functions used in this program. The functions are:
  1. ScreenSize
  2. Initialize
  3. ShowCard
  4. ShowDice
  5. RollDice
  6. TurnInit
  7. ShowRollCount
  8. MakeInstr
  9. MakeLastIntr
  10. ScoreCount
  11. GetDieList
  12. RemoveDups
  13. ScoreRight
  14. ScoreLeft
  15. CheckInput
  16. GetUserInput
  17. Subtotal
  18. GrandTotal
I will not cover each of these since I covered them in the BASH article I mentioned before.

Most of these are straightforward, at least I hope so.

Conclusion

I hope you can see the use of many of the program's commands and functions. Of course, there are multiple ways to accomplish many of the functions. My way is not the only way. Any method that works for you is a valid programming method.

You could optimize some functions better for speed, but there is no need for speed optimization for this game. It is a simple program using text and not graphical routines.
 

Attachments


Members online


Top