Checking for Winner

Page 1 of 1

7 Replies - 289 Views - Last Post: 01 August 2011 - 01:36 PM Rate Topic: -----

#1 bobmax  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 20
  • Joined: 29-July 11

Checking for Winner

Posted 01 August 2011 - 08:15 AM

from pygame.locals import *
# set up pygame
pygame.init()
mainClock = pygame.time.Clock()
# set up the window
WINDOWWIDTH = 400
WINDOWHEIGHT = 400
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Input')
# set up the colors
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
# set up the player and food data structure
foodCounter = 0
NEWFOOD = 40
FOODSIZE = 20
player = pygame.Rect(300, 100, 50, 50)
foods = []
for i in range(20):
    foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - FOODSIZE), random.randint(0, WINDOWHEIGHT - FOODSIZE), FOODSIZE, FOODSIZE))
# set up movement variables
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
MOVESPEED = 6
# run the game loop
while True:
    # check for events
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            # change the keyboard variables
            if event.key == K_LEFT or event.key == ord('a'):
                moveRight = False
                moveLeft = True
            if event.key == K_RIGHT or event.key == ord('d'):
                moveLeft = False
                moveRight = True
            if event.key == K_UP or event.key == ord('w'):
                moveDown = False
                moveUp = True
            if event.key == K_DOWN or event.key == ord('s'):
                moveUp = False
                moveDown = True
        if event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()
            if event.key == K_LEFT or event.key == ord('a'):
                moveLeft = False
            if event.key == K_RIGHT or event.key == ord('d'):
                moveRight = False
            if event.key == K_UP or event.key == ord('w'):
                moveUp = False
            if event.key == K_DOWN or event.key == ord('s'):
                moveDown = False
            if event.key == ord('x'):
                player.top = random.randint(0, WINDOWHEIGHT - player.height)
                player.left = random.randint(0, WINDOWWIDTH - player.width)
        if event.type == MOUSEBUTTONUP:
            foods.append(pygame.Rect(event.pos[0], event.pos[1], FOODSIZE, FOODSIZE))
    foodCounter += 1
    if foodCounter >= NEWFOOD:
        # add new food
        foodCounter = 0
        foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - FOODSIZE), random.randint(0, WINDOWHEIGHT - FOODSIZE), FOODSIZE, FOODSIZE))
    # draw the black background onto the surface
    windowSurface.fill(BLACK)
    # move the player
    if moveDown and player.bottom < WINDOWHEIGHT:
        player.top += MOVESPEED
    if moveUp and player.top > 0:
        player.top -= MOVESPEED
    if moveLeft and player.left > 0:
        player.left -= MOVESPEED
    if moveRight and player.right < WINDOWWIDTH:
        player.right += MOVESPEED
    # draw the player onto the surface
    pygame.draw.rect(windowSurface, WHITE, player)
    # check if the player has intersected with any food squares.
    for food in foods[:]:
        if player.colliderect(food):
            foods.remove(food)
    # draw the food
    for i in range(len(foods)):
        pygame.draw.rect(windowSurface, GREEN, foods[i])
    # draw the window onto the screen
    pygame.display.update()
    mainClock.tick(40)



HI, this my first game in python.so,now i need some suggestions to improve it and also i need a way to decide weather the player has won or not because until now i have no way to stop it except to close it.

This post has been edited by macosxnerd101: 01 August 2011 - 08:17 AM
Reason for edit:: Title renamed to be more descriptive


Is This A Good Question/Topic? 0
  • +

Replies To: Checking for Winner

#2 stayscrisp  Icon User is offline

  • フカユ
  • member icon

Reputation: 994
  • View blog
  • Posts: 4,158
  • Joined: 14-February 08

Re: Checking for Winner

Posted 01 August 2011 - 08:23 AM

Please explain the basics of your game. How does someone win? What type of game is this?
Was This Post Helpful? 0
  • +
  • -

#3 Jacic  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 54
  • Joined: 15-June 10

Re: Checking for Winner

Posted 01 August 2011 - 12:10 PM

A quick browsing of the code seems to suggest that its a snake game...but don't hold me to that.
Was This Post Helpful? 0
  • +
  • -

#4 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5643
  • View blog
  • Posts: 12,359
  • Joined: 16-October 07

Re: Checking for Winner

Posted 01 August 2011 - 12:57 PM

Two things: functions good, globals bad. Using else if is good.

I like cleaning up code. So, here's cleanup one.
import pygame, random, sys
from pygame.locals import *

# globals ( OMG, it's all bloody globals )

# const
NEWFOOD = 40
WINDOWWIDTH = 400
WINDOWHEIGHT = 400
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
MOVESPEED = 6
FOODSIZE = 20

# global
# game state
# init later
(foodCounter, player, foods, windowSurface, 
	mainClock, moveLeft, moveRight, moveUp, moveDown) = ( None for i in range(9) )


def getNewFoodRect(x=None, y=None):
	if not x:
		x = random.randint(0, WINDOWWIDTH - FOODSIZE)
	if not y:
		y = random.randint(0, WINDOWHEIGHT - FOODSIZE)
	return pygame.Rect(x, y, FOODSIZE, FOODSIZE )

def move(left = moveLeft, right = moveRight, up = moveUp, down = moveDown):
	global moveLeft, moveRight, moveUp, moveDown
	(moveLeft, moveRight, moveUp, moveDown) = (left, right, up, down)


def processMove(event):
	if event.type == KEYDOWN:
		if event.key == K_LEFT or event.key == ord('a'): move(left = True, right = False)
		elif event.key == K_RIGHT or event.key == ord('d'): move(left = False, right = True)
		elif event.key == K_UP or event.key == ord('w'): move(up = True, down = False)
		elif event.key == K_DOWN or event.key == ord('s'): 	move(up = False, down = True)
		else:
			return False
	elif event.type == KEYUP:
		if event.key == K_LEFT or event.key == ord('a'): move(left = False)
		elif event.key == K_RIGHT or event.key == ord('d'): move(right = False)
		elif event.key == K_UP or event.key == ord('w'): move(up = False)
		elif event.key == K_DOWN or event.key == ord('s'): move(down = False)
		else:
			return False
	else:
		return False
	return True

def processEvents():
	for event in pygame.event.get():
		if not processMove(event):
			if event.type == QUIT:
				return False
			elif event.type == KEYUP:
				if event.key == K_ESCAPE:
					return False
				elif event.key == ord('x'):
					player.top = random.randint(0, WINDOWHEIGHT - player.height)
					player.left = random.randint(0, WINDOWWIDTH - player.width)
			elif event.type == MOUSEBUTTONUP:
				foods.append(getNewFoodRect(event.pos[0], event.pos[1]))
	return True
	
	
def processFood():
	global foodCounter
	foodCounter += 1
	if foodCounter >= NEWFOOD:
		foodCounter = 0
		foods.append(getNewFoodRect())

def movePlayer():
	if moveDown and player.bottom < WINDOWHEIGHT: player.top += MOVESPEED
	if moveUp and player.top > 0: player.top -= MOVESPEED
	if moveLeft and player.left > 0: player.left -= MOVESPEED
	if moveRight and player.right < WINDOWWIDTH: player.right += MOVESPEED
	pygame.draw.rect(windowSurface, WHITE, player)

def drawFood():
	for food in foods[:]:
		if player.colliderect(food):
			foods.remove(food)
	for i in range(len(foods)):
		pygame.draw.rect(windowSurface, GREEN, foods[i])
	

pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Input')
foods = [ getNewFoodRect() for i in range(20) ]
foodCounter = 0
player = pygame.Rect(300, 100, 50, 50)
move(False, False, False, False)
# run the game loop
while True:
	if not processEvents():
		break
	windowSurface.fill(BLACK)
	processFood()
	movePlayer()
	drawFood()
	pygame.display.update()
	mainClock.tick(40)

pygame.quit()




Version 2 might contain something like:
class Player(object):
	MOVESPEED = 6
	WHITE = (255, 255, 255)
	def __init__(self):
		self.rect = pygame.Rect(300, 100, 50, 50)

	def draw(self):
		pygame.draw.rect(windowSurface, Player.WHITE, self.rect)
		
	def move(self, dx=0, dy=0):
		if dy>0 and self.rect.bottom < WINDOWHEIGHT: 
			self.rect.top += Player.MOVESPEED
		elif dy<0 and self.rect.top > 0:
			self.rect.top -= Player.MOVESPEED
			
		if dx>0 and self.rect.right < WINDOWWIDTH: 
			self.rect.right += Player.MOVESPEED
		elif dx<0 and self.rect.left > 0:
			self.rect.left -= Player.MOVESPEED
		
	def randMove(self):
		self.rect.top = random.randint(0, WINDOWHEIGHT - self.rect.height)
		self.rect.left = random.randint(0, WINDOWWIDTH - self.rect.width)




However, I don't really see a win condition in your code.

Hope this helps.
Was This Post Helpful? 0
  • +
  • -

#5 anonymous26  Icon User is offline

  • D.I.C Lover

Reputation: -4
  • View blog
  • Posts: 3,638
  • Joined: 26-November 10

Re: Checking for Winner

Posted 01 August 2011 - 01:07 PM

There are no gameplay rules in the code, you are only drawing, basic movement and collision detection. This makes me think that this isn't your code, because I can't see how you can do all this yet fail to have any notion of gameplay logic. Oh yes, and you cannot explain your own code!

I would suggest that you write your own code first of all, then you will have a much better idea on how to implement gameplay.
Was This Post Helpful? 0
  • +
  • -

#6 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5643
  • View blog
  • Posts: 12,359
  • Joined: 16-October 07

Re: Checking for Winner

Posted 01 August 2011 - 01:11 PM

View PostButchDean, on 01 August 2011 - 04:07 PM, said:

This makes me think that this isn't your code


Oops, missed it. It was kludgey enough I gave them the benefit of the doubt.

Original appears to be here: http://inventwithpyt.../pygameInput.py

The book is free, at least: http://inventwithpython.com/
Was This Post Helpful? 2
  • +
  • -

#7 anonymous26  Icon User is offline

  • D.I.C Lover

Reputation: -4
  • View blog
  • Posts: 3,638
  • Joined: 26-November 10

Re: Checking for Winner

Posted 01 August 2011 - 01:25 PM

Nice work, baavgai! :D
Was This Post Helpful? 0
  • +
  • -

#8 stayscrisp  Icon User is offline

  • フカユ
  • member icon

Reputation: 994
  • View blog
  • Posts: 4,158
  • Joined: 14-February 08

Re: Checking for Winner

Posted 01 August 2011 - 01:36 PM

Nice catch!

@bobmax
We will not do your work for you, post your own attempt at the problem and then we can point you in the right direction.

*Closed*
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1