Random Module help in python - python-3.x

So here I have my code to connect 3 game. In order for me to proceed to finish coding the rest of the game, I need your help fixing the loop that determines what player goes first. When the loop randomly selects the player, it blits it's token however it keeps bliting both of the players tokens which means that the random function keeps running. How do I fix it so it runs once. Thanks!
import pygame, sys, random
from pygame.locals import*
#FPS
FPS =7
fpsClock = pygame.time.Clock()
#Display
DISPLAYSURF=pygame.display.set_mode((850, 725), 0, 32)
pygame.display.set_caption('Connect 3~Emoji Edition')
#Colors
WHITE=(255, 255, 255)
#Players
Player1='P1'
Player2='P2'
#Images
#Keyboard
Board=pygame.image.load('Keyboard.png')
Boardx=45
Boardy=200
#Token1
Token1=pygame.image.load('PoopEMJ.png')
Token1=pygame.transform.scale(Token1, (90, 90))
Token1x=375
Token1y=215
#Token2
Token2=pygame.image.load('LaughingEMJ.png')
Token2=pygame.transform.scale(Token2, (90, 90))
Token2x=375
Token2y=215
while True:
DISPLAYSURF.fill(WHITE)
DISPLAYSURF.blit(Board,(Boardx, Boardy))
#Randomly selects players *HELP*
Turn='Player'
if random.randint(0, 1) == 0:
Turn = Player1
DISPLAYSURF.blit(Token1,(Token1x, Token1y))
else:
Turn = Player2
DISPLAYSURF.blit(Token2,(Token2x, Token2y))
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
pygame.display.update()

You have put the code to randomly select the player, in the While True loop.
This means that it will constantly select a new random player and blit it to the screen. you must only select a new random player when the last player has finished their turn, or it is the beginning of the game.

Related

PyGame. Second composition in modul "mixer.music. doesnt playing, but first plays normally [duplicate]

I tried to use python to display image:
import pygame
win = pygame.display.set_mode((500, 500))
DisplayImage("Prologue.jpg", win)
And when it runs, nothing happened. It also happened for
DisplayImage("Streets.jpg", win)
However, when I tried the exact same thing later on in the code, it ran perfectly.
I checked, the picture was in the same folder as the .py file, and I didn't type the name wrong.
The function is:
def DisplayImage(imageName, screen):
screen.fill((0, 0, 0))
Image = pygame.image.load(imageName).convert()
screen_rect = screen.get_rect()
Image_rect = Image.get_rect().fit(screen_rect)
Image = pygame.transform.scale(Image, Image_rect.size)
screen.blit(Image, [0, 0])
pygame.display.update()
Update:
I commented out all of the lines and copy and pasted that line out so it's the only line that runs. It runs perfectly.
Update 2:
Found the issue. The reason it doesn't work was that the pygame window was "not responding". I don't know what caused it to not respond, but in one of the test runs I didn't make it show "not responding", and the images were loaded fine. The "not responding" always shows up when I type in my player name, and the function looks like this:
def createName():
playerName = input("Enter the player name\n")
desiredName = input("Is "+playerName+" the desired name?[1]Yes/[2]No\n")
if desiredName == "1":
return playerName
elif desiredName == "2":
playerName = createName()
Sometimes when I type the player name nothing happens, and the letters only show up after a while. If this happens, the pygame window is bound to not respond.
You cannot use input in the application loop. input waits for an input. While the system is waiting for input, the application loop will halt and the game will not respond.
Use the KEYDOWN event instead of input:
run = True
while run:
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if pygame.key == pygame.K_1:
# [...]
if pygame.key == pygame.K_2:
# [...]
Another option is to get the input in a separate thread.
Minimal example:
import pygame
import threading
pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
color = "red"
def get_input():
global color
color = input('enter color (e.g. blue): ')
input_thread = threading.Thread(target=get_input)
input_thread.start()
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window_center = window.get_rect().center
window.fill(0)
pygame.draw.circle(window, color, window_center, 100)
pygame.display.flip()
pygame.quit()
exit()

My score system in Pygame overlaps over and over again [duplicate]

This question already has an answer here:
How can I move the ball instead of leaving a trail all over the screen in pygame?
(1 answer)
Closed 2 years ago.
I have looked at many YouTube videos and information online but is seems I can't find the answer. Every time I run the code the text appears with a zero but when clicking the enemy to earn points the number 1 overlaps with the zero and it doesn't change. This problem repeats over and over again. What do/can I do? I am new to the python code and there might be some unnecessary code so please bare that in mind if you see a rookie mistake thank you.
import pygame
import time
import random
pygame.init()
from pygame.locals import *
white = (255,255,255)
window = pygame.display.set_mode((800,600))
pygame.display.set_caption("Extended Essay game")
BADGUY = pygame.image.load('enemy.png')
pygame.font.init()
#Enemy char
class Enemy():
def __init__(self, x, y):
self.x = x
self.y = y
def main():
run = True
FPS = 60
x = 0
enemies = 0
clock = pygame.time.Clock()
font = pygame.font.Font('freesansbold.ttf', 32)
window.fill((255,255,255))
window.blit(BADGUY,(0,0))
def update():
text = font.render("Enemies: " + str(enemies), True, (0,0,0))
window.blit(text, (200, 300))
pygame.display.update()
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
window.blit(BADGUY, (random.randint(0, 700), random.randint(0 , 700)))
enemies += 1
update()
main()
You need to clear the screen before putting new stuff on it. Put this at the beginning of update() or right before it is called in the loop:
window.fill((255, 255, 255))

pygame.display.flip() seems to not be working?

I've been working on a project, and when I tested it this happened. After a little testing I soon realized it was something wrong in the pygame display flip part of the code. I really don't see what's wrong here, so I hope one of you do.
import pygame
pygame.init()
screen = pygame.display.set_mode((200, 200))
img = pygame.image.load("test.png")
while 1:
screen.fill((0, 0, 0))
screen.blit(img, (0, 0))
pygame.display.flip()
pygame.time.delay(10)
Now, the result is a blank white screen that's 200 by 200. I hope someone sees what's wrong here. Also, my png doesn't matter here because I get the same result with just the fill(black), so I hope someone knows.
Couple things here:
1) I would recommend using the pygame clock instead of time.delay. Using the clock sets the frames per second to run the code, where the time.delay just sits and waits for the delay.
2) Pygame is event driven, so you need to be checking for events, even if you don't have any yet. otherwise it is interpreted as an infinite loop and locks up. for a more detailed explanation: click here
3) I would offer a way out of the game loop with a flag that can be set to false, that way the program can naturally terminate
import pygame
pygame.init()
screen = pygame.display.set_mode((200, 200))
img = pygame.image.load("test.png")
clock = pygame.time.Clock()
game_running = True
while game_running:
# evaluate the pygame event
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_running = False # or anything else to quit the main loop
screen.fill((0, 0, 0))
screen.blit(img, (0, 0))
pygame.display.flip()
clock.tick(60)

Pygame sprite clamping isse

So Ive been having issues with getting a sprite to stay withing the bounds of the screen. I got it to work with a simple rect(0,0,16,16), but i cant seem to get it to work with a sprite being blit onto the screen. What do i need to change in order to keep my sprite clamped within the screen res? I only just started today using classes to orgonize code so any input is appreciated and helpful.
import pygame
from pygame.locals import *
from pygame import Color
class Game():
""" Lets try to get this going by simple steps
One by one. First step, lets figure how to make a class
that can do the display stuff. Lord have mercy on my soul"""
def __init__(self, wi=256, hi=224, multii=3):
"""Initialization"""
pygame.init()
self.runGame = True
self.width = wi*multii
self.height = hi*multii
self.spritesize = 16*multii
self.clock = pygame.time.Clock()
self.fps = self.clock.get_fps()
self.screen = pygame.display.set_mode((self.width, self.height))
self.kl = []
self.walk = [0, 0]
self.speed = multii*1.5
self.x,self.y = self.width/2, self.height/2
self.playerSpr = pygame.image.load('images/'+'link1.png').convert_alpha()
self.playerRec = Rect(self.playerSpr.get_rect())
def mainLoop(self):
"""Loop through the main game routines
1. Drawing 2. Input handling 3. Updating
Then loop through it until user quits"""
while self.runGame:
self.clock.tick(60)
self.events()
self.draw()
def events(self):
"""Time to handle some events"""
for e in pygame.event.get():
if (e.type == pygame.QUIT) or (e.type == KEYDOWN and e.key == K_ESCAPE):
self.runGame = False
break
if e.type==KEYDOWN:
if e.key==pygame.K_a: self.kl.append(1)
if e.key==pygame.K_d: self.kl.append(2)
if e.key==pygame.K_w: self.kl.append(3)
if e.key==pygame.K_s: self.kl.append(4)
if e.type==pygame.KEYUP:
if e.key==pygame.K_a: self.kl.remove(1)
if e.key==pygame.K_d: self.kl.remove(2)
if e.key==pygame.K_w: self.kl.remove(3)
if e.key==pygame.K_s: self.kl.remove(4)
if self.kl[-1:]==[1]: self.walk=[-self.speed, 0]
elif self.kl[-1:]==[2]: self.walk=[ self.speed, 0]
elif self.kl[-1:]==[3]: self.walk=[0,-self.speed]
elif self.kl[-1:]==[4]: self.walk=[0, self.speed]
else: self.walk=[0, 0]
self.x+=self.walk[0]
self.y+=self.walk[1]
def draw(self):
"""Draw and update the main screen"""
self.fps = self.clock.get_fps()
self.screen.fill(Color('purple'))
#print self.screen.get_rect()
#print player_rect
self.playerSpr.clamp_ip(self.screen.get_rect())
#pygame.draw.rect(self.screen, (255, 255, 255), self.playerrect)
self.screen.blit(self.playerSpr, (self.x,self.y), self.playerRec)
pygame.display.set_caption('Grid2. FPS: '+str(self.fps))
pygame.display.update()
game = Game()
game.mainLoop()
Why not use playerRec to keep track of the position of your player instead of the additional x and y attributes?
I suggest also using the move method (or move_ip):
def events(self):
for e in pygame.event.get():
...
self.playerRec.move_ip(*self.walk) # instead of self.x+=self.walk[0] / self.y+=self.walk[1]
def draw(self):
...
# probably do this right after 'move_ip'
self.playerRec.clamp_ip(self.screen.get_rect())
# note that 'blit' accepts a 'Rect' as second parameter
self.screen.blit(self.playerSpr, self.playerRec)
as a side note: You should consider using a Sprite, since it basically combines an Image and a Rect.
Two things:
You are not stopping movement of the sprite when it comes off the screen.
Make an move functions that will get a direction and will decide if it can move more to the side. That way when the right side of the sprite will be of screen, you will not move more to the right.
Since you put your direction keys in a list that works like a stack, you are only getting 1 direction per keypress. If you also want to move diagonally either make two lists one for both directions or use a easier method such as this:
if KEYDOWN == K_LEFT: direction_x = -1
if KEYUP == K_LEFT AND direction_x == -1: direction_x = 0
do this for every key.

Pygame play a sound when click on certain spot on GUI

I'm an amateur, very inexperience programmer. I've been working on an art project that I am programming using Pygame. I've hit a road block, ad can't figure out how to do what I need it to do.
I need it to play a specific sound when clicking on a specific place on the GUI. For example, when you click on the red button, it plays an audio file that says "red"
I also need it to be able to play sounds with clicking and dragging on the canvas part.
I hope this is enough detail. Thanks for the help!
import pygame, sys, time, random
from pygame.locals import *
# set up pygame
pygame.init()
pygame.mixer.init
pygame.mixer.get_init
bgimg="GUIsmall.gif"
inst="instructionssm.gif"
white=(255,255,255)
screen=pygame.display.set_mode((800,600), pygame.RESIZABLE)
screen.fill(white)
bg=pygame.image.load(bgimg)
instrimg=pygame.image.load(inst)
screen.blit(bg, (0,0))
pygame.display.flip()
red=pygame.mixer.Sound("red.mp3")
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
raise SystemExit
elif event.type==pygame.MOUSEBUTTONDOWN:
red.play(0,0,0)
I think you should have a class button and a collection of buttons:
class Button:
__init__(self, name, position, image_file, sound_file):
self.name = name
self.image = pygame.image.load(image_file)
self.sound = pygame.mixer.Sound(sound_file)
self.position = position
self.rect = pygame.Rect(position, self.image.get_size())
buttons = []
buttons.add( Button("red", (0,0), "red.png", "red.mp3") )
...
Then you can use it in the main loop:
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
raise SystemExit
elif event.type==pygame.MOUSEBUTTONDOWN:
for b in buttons:
if b.rect.collidepoint(event.pos):
b.sound.play()

Resources