SoFunction
Updated on 2024-11-16

python implementation of the Nim game

title

Nim game, which is a famous game with many variants to play. Two players take turns taking a portion of a pile of items. At each step, the players are free to take as many items as they choose, but they must take one and at most half of the items, and then it is the next player's turn. The player who takes the last item loses the game. Priority is randomized.

Code running effect

python code

#/sur/bin/nve python
# coding: utf-8
import os # clear the screen with (r'clear')
import random # Randomize numbers with ()



def clear():
    '''#Linux clear screen''''
    clear = (r'clear')


def optimal(n):
    '''Machine Optimal Take'''
    if n in (1, 2, 3, 4):
        return 1
    take = int(n/2)
    m = 1
    for i in range(take):
        if m>take:
            break
        m *= 2
    take = n-m+1
    if take>int(n/2):
        take = (1, int(n/2))
    return take


def common(n):
    '''General machine holding method'''
    while True:
        if n==1:
            return 1
        return (1, int(n/2))


def effect(first, take, n):
    '''Results output'''
    cl()
    print('\n'*6)
    flag_s = ('Simple', 'Difficulties')[flag-1]
    print('%s\n'%('【%s】'%flag_s).rjust(20))
    print('﹊'*21)
    print(' '*4, end='')
    print('%s has been taken %s. item pile items left %s.'%(first, take, n))
    print('﹊'*21)


def show_error():
    '''Error message printing'''
    print('\n\n%s'%error)
    print('Input error! Please try again.'.rjust(20))
    print('﹊'*21)
    input('Any key to continue ......'.rjust(20))


#Main Codes
cl = clear
s = '''
      Nim game, which is a famous game that
  There are many variants to play.
      Two players take turns taking items from a pile of
  a portion of it. At each move, the players are free to
  choose how many items to take, but must take one
  and at most half of the items, and then it is the turn of the
  the next player.
      The player who takes the last item loses the game.
      The first player is randomized.
'''
# Rule Printing
cl()
print('\n\n%s'%'"Nim" Rules of the Game'.rjust(20))
print()
print('﹊'*21)
print(s)
print('﹊'*21)
input('Any key to continue ......'.rjust(20))
#Difficulty Selection
while True:
    cl()
    print('\n'*6)
    print('\n%s'%'[Difficulty Selection]'.rjust(20))
    print()
    print('﹊'*21)
    print('1. Simple 2. Difficult'.rjust(24))
    print('﹊'*21)
    try:
        flag = int(input('Please select:'.rjust(12)))
        if flag not in (1, 2):
            error()
            continue
        break
    except Exception as error:
        show_error()

#Start the game
p = 'Cutie'
cl()
print('\n'*6)
while True:
    try:
        c = input('Naming the Opponent:'.rjust(12))
        break
    except Exception as error:
        error()
        continue
if flag==2:
    n = (1, 500)
else:
    n = (1, 100)
cl()
print('\n'*6)
print('﹊'*21)
print('%s\n'%'[This game's item pile]''.rjust(21))
print(('%s:%3d'%('Total number of items', n)).rjust(22))
print('﹊'*21)
input('Any key to continue ......'.rjust(20))
# Randomized choice of starters
first = ((c, p))
while n>0:
    # The machine takes
    if flag==2 and first==c:
        take = optimal(n)
        n = n-take
    if flag==1 and first==c:
        take = common(n)
        n = n-take
    if first==c:
        effect(first, take, n)
    if n==0:
        break
    first = p #Convert the player to a first hand
    # Players take
    if first==p:
        while True:
            try:
                take = int(input('\n%s'%'You fetch:'.rjust(12)))
                if take==1 and (n in (1, 2, 3)):
                    break
                if take>int(n/2) or take<1:
                    error()
                    continue 
                break
            except Exception as error:
                show_error()
        n = n-take
    if first==p:
        effect('You', take, n)
        input('Any key to continue ......'.rjust(20))
    if n==0:
        break
    first = c # Convert the machine first hand
    
#Results output
if first==p:
    first = 'You'
cl()
print('\n'*6)
print('﹊'*21)
print(('%s lost!'%first).rjust(20))
print('﹊'*21)

This is the end of this article about python implementation of Nim game. I hope it will be helpful for your learning and I hope you will support me more.