I made a 3 reel slot machine using the pygame library in Python. This is what I have so far.
I want to improve it to make it work for a 3x5 slot machine with multiple paylines, right now it is a 1x3 slot machine.
I also want to improve on my programming skills as I am still fairly new to programming and have only been doing it for about a year. If anyone has any recommendations on how to make this code cleaner or more efficient, let me know.
nums.json contains this list of numbers. I made this list of numbers so some icons have more weight than others, hence why some give the player more money.
[
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
2,
2
]
This is the slotmachine class file.
import random
import json
f = open("nums.json")
nums = json.load(f)
class SlotMachine:
def __init__(self, windict):
self.windict = windict
self.output = ""
def play(self):
num = random.choice(nums)
self.output += str(num)
return num
def checkwin(self):
if self.output in self.windict:
win = str(self.windict[self.output] * 100)
self.output = ""
return win
else:
loss = "0"
self.output = ""
return loss
This is the main Python file.
import pygame
from slotmachine import SlotMachine
import time
pygame.init()
eagles = "The Best of My Love - On the Border (front).jpg"
beatles = "Abbey Road (front).jpg"
pink = "Wish you were here (front).jpg"
(width, height) = (800, 600)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Ryan's Slot Machine")
white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 128)
screen.fill(white)
bg = pygame.image.load("border.png")
screen.blit(bg, (0, 0))
pygame.display.update()
picdict = {0: eagles, 1: beatles, 2: pink}
positions = ((200, 275), (350, 275), (497, 275))
slot = SlotMachine({"000": 1, "111": 2, "222": 5})
font = pygame.font.Font("freesansbold.ttf", 25)
def icon_to_screen(x, y, path):
icon = pygame.image.load(path)
small_icon = pygame.transform.scale(icon, (100,50))
screen.blit(small_icon, (x, y))
pygame.display.update()
def main():
play = True
while play:
for event in pygame.event.get():
if event.type == pygame.QUIT:
play = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
screen.fill(white)
bg = pygame.image.load("border.png")
screen.blit(bg, (0, 0))
pygame.display.update()
for position in positions:
i = slot.play()
icon_to_screen(position[0], position[1], picdict[i])
time.sleep(.5)
text = font.render(slot.checkwin(), True, green, blue)
screen.blit(text, (670,36))
pygame.display.update()
if __name__ == "__main__":
main()